$group)if(isset($affected[$f])||isset($added[(int)$gid]))yield [$board,(int)$gid];} } // Input comes only from the authenticated central SSO identity, never GET/POST. function dune_missing_system_boards(array $projection, array $boards): array { if (($projection['version'] ?? null) !== 1) throw new RuntimeException('Forum membership projection unavailable'); $missing=[]; foreach ($projection['organisations'] ?? [] as $grant) { if (!in_array($grant['kind'] ?? '', ['clan','company'],true) || ($grant['read'] ?? false) !== true || ($grant['post'] ?? false) !== true) continue; if (!preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i',$grant['id'] ?? '')) throw new RuntimeException('Invalid verified organisation'); $key=$grant['kind'].':'.$grant['id']; if (isset($boards[$key]) || isset($missing[$key])) continue; if (!is_string($grant['name'] ?? null) || trim($grant['name']) === '' || strlen($grant['name'])>120) throw new RuntimeException('Verified organisation name unavailable'); $missing[$key]=['kind'=>$grant['kind'],'id'=>$grant['id'],'name'=>$grant['name']]; } return array_values($missing); } function dune_provision_system_boards(array $input,?callable $prepare=null,?callable $review=null,?callable $beforeCommit=null): array { global $db,$cache,$dune_board_template; if (!is_array($input) || !isset($input['organisations']) || !is_array($input['organisations'])) throw new RuntimeException('Organisation snapshot required'); foreach ($input['organisations'] as $org) { if (!in_array($org['kind'] ?? '', ['clan','company','politics'], true) || !preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i', $org['id'] ?? '') || !is_string($org['name'] ?? null) || trim($org['name']) === '' || my_strlen($org['name']) > 120) throw new RuntimeException('Invalid organisation'); } $lock = $db->fetch_array($db->write_query("SELECT GET_LOCK('dune_system_boards_provision',10) acquired")); if ((int)($lock['acquired'] ?? 0) !== 1) throw new RuntimeException('System Boards publication is busy'); try { $db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_system_boards (kind VARCHAR(12) NOT NULL, organisation_id VARCHAR(36) NOT NULL, fid INT NOT NULL, member_gid INT NOT NULL DEFAULT 0, leader_gid INT NOT NULL DEFAULT 0, PRIMARY KEY(kind,organisation_id), UNIQUE KEY forum_id(fid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); if($prepare)$prepare(); // MyBB core tables may be MyISAM. Keep registry bindings durable under // this advisory lock; per-object markers recover an interrupted insert. // A SQL rollback cannot undo native MyISAM rows. if($review)$review($input); if($review&&!$input['organisations']){return ['status'=>'unchanged','organisations'=>0,'rootForum'=>null];} $groups = []; $affected=[]; $added=[]; $activate=[]; $query = $db->simple_select('usergroups'); while ($row = $db->fetch_array($query)) $groups[(int)$row['gid']] = $row; if (!isset($groups[2])) throw new RuntimeException('Registered group unavailable'); $dune_board_template = $db->fetch_array($db->simple_select('forums', '*', "type='f'", ['limit'=>1])); if (!$dune_board_template) throw new RuntimeException('Native forum template unavailable'); $permissionColumns = ['canview','canviewthreads','canonlyviewownthreads','candlattachments','canpostthreads','canpostreplys','canonlyreplyownthreads','canpostattachments','canratethreads','caneditposts','candeleteposts','candeletethreads','caneditattachments','canviewdeletionnotice','modposts','modthreads','mod_edit_posts','modattachments','canpostpolls','canvotepolls','cansearch']; $root = dune_provision_make_board('system','root','System Boards',0); $clans = dune_provision_make_board('system','clans','Clan Boards',(int)$root['fid']); $companies = dune_provision_make_board('system','companies','Company Boards',(int)$root['fid']); $elections=dune_provision_make_board('system','elections','Election Board',(int)$root['fid'],'f'); foreach([$root,$clans,$companies,$elections]as $system)$activate[(int)$system['fid']]=true; $categories=['clan'=>$clans,'company'=>$companies]; if(array_filter($input['organisations'],fn($org)=>$org['kind']==='politics')){$categories['politics']=dune_provision_make_board('system','politics','Political Boards',(int)$root['fid']);$activate[(int)$categories['politics']['fid']]=true;} foreach ($input['organisations'] as $org) { $board = dune_provision_make_board($org['kind'], $org['id'], $org['name'], (int)$categories[$org['kind']]['fid'], 'f'); $affected[(int)$board['fid']]=true;$activate[(int)$board['fid']]=true; foreach (['member_gid','leader_gid'] as $field) { $role=$field==='leader_gid'?'leaders':'members'; $title=my_substr((['clan'=>'Clan','company'=>'Company','politics'=>'Office'])[$org['kind']].' '.$role.' ยท '.$org['name'],0,45); if ((int)$board[$field] > 0) { $db->update_query('usergroups',['title'=>$db->escape_string($title)],'gid='.(int)$board[$field]); continue; } [$gid,$group,$created]=dune_provision_board_group($org,$field,$title,$groups[2]); $board[$field]=$gid;$groups[$gid]=$group;if($created)$added[$gid]=true; $db->update_query('dune_system_boards', [$field=>$gid], 'fid='.(int)$board['fid']); } $moderator = ['fid'=>(int)$board['fid'], 'id'=>(int)$board['leader_gid'], 'isgroup'=>1, 'caneditposts'=>1,'cansoftdeleteposts'=>1,'canrestoreposts'=>1,'cansoftdeletethreads'=>1,'canrestorethreads'=>1, 'canopenclosethreads'=>1,'canstickunstickthreads'=>1,'canapproveunapprovethreads'=>1,'canapproveunapproveposts'=>1, 'canapproveunapproveattachs'=>1,'canmanagethreads'=>1,'canmanagepolls'=>1,'canpostclosedthreads'=>1,'canmanagereportedposts'=>1,'canviewmodlog'=>1]; $db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id='.(int)$board['leader_gid'].' AND isgroup=1'); $db->insert_query('moderators', $moderator); // Existing native Moderators retain moderation on every new board; // Super Moderators and Administrators already have native global power. $moderator['id']=6; $db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id=6 AND isgroup=1'); $db->insert_query('moderators', $moderator); } // All affected boards are complete after every new group is known. New // groups are denied on unrelated private boards, without rewriting the // entire existing board-by-group matrix for every small change. $query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company','politics')"); $boards=[];while($board=$db->fetch_array($query))$boards[]=$board; foreach(dune_board_permission_targets($boards,$groups,$affected,$added)as [$board,$gid]){ $member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true); dune_provision_save_permissions((int)$board['fid'], (int)$gid, dune_board_private_permissions($permissionColumns, $member)); } // No guest feed may publish System Boards topics. dune_provision_save_permissions((int)$root['fid'], 1, dune_board_private_permissions($permissionColumns, false)); foreach($activate as $fid=>$unused)$db->update_query('forums', ['active'=>1], 'fid='.(int)$fid); if($beforeCommit)$beforeCommit($groups); $db->write_query('COMMIT'); foreach (['usergroups','forums','forumpermissions','moderators'] as $key) { $method='update_'.$key; $cache->$method(); } return ['status'=>'provisioned', 'organisations'=>count($input['organisations']), 'rootForum'=>(int)$root['fid']]; } catch (Throwable $error) { $db->write_query('ROLLBACK'); throw $error; } finally { $db->write_query("SELECT RELEASE_LOCK('dune_system_boards_provision')"); } } function dune_provision_board_row($kind, $id) { global $db; return $db->fetch_array($db->simple_select('dune_system_boards', '*', "kind='".$db->escape_string($kind)."' AND organisation_id='".$db->escape_string($id)."'")); } function dune_provision_make_board($kind, $id, $name, $parent, $type = 'c') { global $db, $dune_board_template; if ($existing = dune_provision_board_row($kind, $id)) { $title=htmlspecialchars($name,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); $forum=$db->fetch_array($db->simple_select('forums','name','fid='.(int)$existing['fid'])); if(!$forum)throw new RuntimeException('Existing native board is unavailable'); if($forum['name']!==$title)$db->update_query('forums',['name'=>$db->escape_string($title)],'fid='.(int)$existing['fid']); return $existing; } $marker=''; $matches=[];$query=$db->simple_select('forums','*',"description='".$db->escape_string($marker)."'",['limit'=>2]);while($match=$db->fetch_array($query))$matches[]=$match; if(count($matches)>1)throw new RuntimeException('Interrupted board mapping is ambiguous'); if($matches){ $recovered=$matches[0];if((int)$recovered['pid']!==$parent||$recovered['type']!==$type)throw new RuntimeException('Interrupted board parent requires review'); $parentRow=$parent?$db->fetch_array($db->simple_select('forums','parentlist','fid='.$parent)):null; $db->update_query('forums',['parentlist'=>$db->escape_string(($parentRow?$parentRow['parentlist'].',':'').$recovered['fid'])],'fid='.(int)$recovered['fid']); $db->insert_query('dune_system_boards',['kind'=>$db->escape_string($kind),'organisation_id'=>$db->escape_string($id),'fid'=>(int)$recovered['fid']]); return dune_provision_board_row($kind,$id); } $row = $dune_board_template; unset($row['fid']); foreach (['threads','posts','lastpost','lastposteruid','unapprovedthreads','unapprovedposts','deletedthreads','deletedposts'] as $key) if (array_key_exists($key, $row)) $row[$key] = 0; foreach (['lastposter','lastpostsubject','linkto','password','rules','rulestitle'] as $key) if (array_key_exists($key, $row)) $row[$key] = ''; $row = array_merge($row, ['name'=>htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), 'description'=>$marker, 'type'=>$type, 'pid'=>$parent, 'parentlist'=>'', 'disporder'=>1000, 'active'=>0, 'open'=>1, 'allowhtml'=>0, 'allowmycode'=>1, 'allowsmilies'=>1, 'allowimgcode'=>1, 'showinjump'=>1]); foreach ($row as $key=>$value) if (is_string($value)) $row[$key]=$db->escape_string($value); $fid = (int)$db->insert_query('forums', $row); $parentRow = $parent ? $db->fetch_array($db->simple_select('forums','parentlist','fid='.$parent)) : null; $parentlist = ($parentRow ? $parentRow['parentlist'].',' : '').$fid; $db->update_query('forums', ['parentlist'=>$db->escape_string($parentlist)], 'fid='.$fid); $db->insert_query('dune_system_boards', ['kind'=>$db->escape_string($kind), 'organisation_id'=>$db->escape_string($id), 'fid'=>$fid]); return dune_provision_board_row($kind, $id); } function dune_provision_save_permissions(int $fid, int $gid, array $permissions): void { global $db; $where = 'fid='.$fid.' AND gid='.$gid; $existing = $db->fetch_array($db->simple_select('forumpermissions', 'pid', $where)); if ($existing) $db->update_query('forumpermissions', $permissions, $where); else $db->insert_query('forumpermissions', array_merge($permissions, ['fid'=>$fid,'gid'=>$gid])); } // A native group and its marker are one atomic MyISAM row. If the following // registry update was interrupted, the next delivery adopts that exact row. function dune_provision_board_group(array $org,string $field,string $title,array $template): array { global $db;$marker=''; $matches=[];$query=$db->simple_select('usergroups','*',"description='".$db->escape_string($marker)."'",['limit'=>2]);while($row=$db->fetch_array($query))$matches[]=$row; if(count($matches)>1)throw new RuntimeException('Interrupted board group is ambiguous'); if($matches){$row=$matches[0];if(!empty($row['cancp'])||!empty($row['issupermod']))throw new RuntimeException('Interrupted board group privileges require review');$db->update_query('usergroups',['title'=>$db->escape_string($title)],'gid='.(int)$row['gid']);return [(int)$row['gid'],$row,true];} $group=$template;unset($group['gid']);$group['title']=$title;$group['description']=$marker;$group['cancp']=0;$group['issupermod']=0;$group['canmodcp']=$field==='leader_gid'?1:0; foreach($group as $key=>$value)if(is_string($value))$group[$key]=$db->escape_string($value); $gid=(int)$db->insert_query('usergroups',$group);return [$gid,$group,true]; }