SiteController.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use http\Exception\RuntimeException;
  4. use Opentalent\OtAdmin\Domain\Entity\SiteInfos;
  5. use Opentalent\OtAdmin\Domain\Entity\SiteStatus;
  6. use Opentalent\OtAdmin\Exception\NoSuchRecordException;
  7. use Opentalent\OtAdmin\Exception\NoSuchWebsiteException;
  8. use Opentalent\OtCore\Cache\OtCacheManager;
  9. use Opentalent\OtCore\Controller\ActionController;
  10. use Opentalent\OtCore\Domain\Model\Organization;
  11. use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
  12. use Opentalent\OtCore\Exception\ApiRequestException;
  13. use PDO;
  14. use Symfony\Component\Yaml\Yaml;
  15. use TYPO3\CMS\Core\Crypto\Random;
  16. use TYPO3\CMS\Core\Utility\GeneralUtility;
  17. use TYPO3\CMS\Extbase\Object\ObjectManager;
  18. /**
  19. * The SiteController implements some admin-only operations
  20. * on Typo3 websites, like creation or update.
  21. */
  22. class SiteController extends ActionController
  23. {
  24. // Templates names
  25. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  26. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  27. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  28. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  29. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  30. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  31. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  32. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  33. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  34. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  35. const TEMPLATE_LEGAL = "OpenTalent.OtTemplating->legal";
  36. // Pages dokType values
  37. const DOK_PAGE = 1;
  38. const DOK_SHORTCUT = 4;
  39. const DOK_FOLDER = 116;
  40. // Contents CTypes
  41. const CTYPE_TEXT = 'text';
  42. const CTYPE_IMAGE = 'image';
  43. const CTYPE_TEXTPIC = 'textpic';
  44. const CTYPE_TEXTMEDIA = 'textmedia';
  45. const CTYPE_HTML = 'html';
  46. const CTYPE_HEADER = 'header';
  47. const CTYPE_UPLOADS = 'uploads';
  48. const CTYPE_LIST = 'list';
  49. const CTYPE_SITEMAP = 'menu_sitemap';
  50. // Default values
  51. const DEFAULT_THEME = 'Classic';
  52. const DEFAULT_COLOR = 'light-blue';
  53. // BE rights
  54. const BEGROUP_EDITOR_STANDARD = 10;
  55. const BEGROUP_EDITOR_PREMIUM = 20;
  56. const BEGROUP_ADMIN_STANDARD = 30;
  57. const BEGROUP_ADMIN_PREMIUM = 40;
  58. const BEGROUP_NAME = [
  59. self::BEGROUP_EDITOR_STANDARD => "Editor_Standard",
  60. self::BEGROUP_EDITOR_PREMIUM => "Editor_Premium",
  61. self::BEGROUP_ADMIN_STANDARD => "Admin_Standard",
  62. self::BEGROUP_ADMIN_PREMIUM => "Admin_Premium"
  63. ];
  64. const IS_PRODUCT_PREMIUM = [
  65. "school-standard" => false,
  66. "artist-standard" => false,
  67. "school-premium" => true,
  68. "artist-premium" => true,
  69. "manager" => true,
  70. ];
  71. // access permissions
  72. const PERM_SHOW = 1;
  73. const PERM_EDIT_CONTENT = 16;
  74. const PERM_EDIT_PAGE = 2;
  75. const PERM_DELETE = 4;
  76. const PERM_NEW = 8;
  77. // Creation mode
  78. const MODE_PROD = 1;
  79. const MODE_DEV = 1;
  80. // Domain name validation
  81. const RX_DOMAIN = "/([a-z0-9A-Z]\.)*[a-z0-9-]+\.([a-z0-9]{2,24})+(\.co\.([a-z0-9]{2,24})|\.([a-z0-9]{2,24}))*\/?/";
  82. // Redirections creation status
  83. const REDIRECTION_UNKNOWN_STATUS = 0;
  84. const REDIRECTION_UPDATED = 1;
  85. const REDIRECTION_CREATED = 2;
  86. /**
  87. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  88. */
  89. private $connectionPool;
  90. public function injectConnectionPool(\TYPO3\CMS\Core\Database\ConnectionPool $connectionPool)
  91. {
  92. $this->connectionPool = $connectionPool;
  93. }
  94. /**
  95. * @var \TYPO3\CMS\Core\Cache\CacheManager
  96. */
  97. private $cacheManager;
  98. public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager $cacheManager)
  99. {
  100. $this->cacheManager = $cacheManager;
  101. }
  102. /**
  103. * Index of the pages created during the process
  104. * >> [slug => uid]
  105. * @var array
  106. */
  107. private array $createdPagesIndex;
  108. /**
  109. * List of the directories created in the process (for rollback purposes)
  110. * @var array
  111. */
  112. private array $createdDirs;
  113. /**
  114. * List of the files created in the process (for rollback purposes)
  115. * @var array
  116. */
  117. private array $createdFiles;
  118. public function __construct()
  119. {
  120. parent::__construct();
  121. $this->createdPagesIndex = [];
  122. $this->createdDirs = [];
  123. $this->createdFiles = [];
  124. }
  125. /**
  126. * Return the SiteInfos object for the organization's website
  127. *
  128. * @param int $organizationId
  129. * @return SiteInfos
  130. * @throws NoSuchWebsiteException
  131. */
  132. public function getSiteInfosAction(int $organizationId): SiteInfos
  133. {
  134. $rootUid = $this->findRootUidFor($organizationId);
  135. $config = $this->findConfigFor($rootUid);
  136. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  137. $rootPage = $this->otPageRepository->getPage($rootUid);
  138. $site = new SiteInfos(
  139. $rootUid,
  140. $rootPage['title'],
  141. $config['base'],
  142. $rootPage['tx_opentalent_template'],
  143. $rootPage['tx_opentalent_template_preferences'],
  144. $rootPage['tx_opentalent_matomo_id'],
  145. self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']] ?? false,
  146. (bool)$rootPage['deleted'],
  147. (bool)($rootPage['hidden'] || $rootPage['fe_group'] < 0),
  148. null,
  149. null,
  150. $rootPage['perms_userid'],
  151. $rootPage['perms_groupid']
  152. );
  153. // Owners
  154. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  155. $queryBuilder->getRestrictions()->removeAll();
  156. $beUsers = $queryBuilder
  157. ->select('uid', 'username')
  158. ->from('be_users')
  159. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  160. ->execute()
  161. ->fetchAll();
  162. foreach ($beUsers as $beUser) {
  163. $site->addMountedForBeUser($beUser);
  164. }
  165. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  166. $queryBuilder->getRestrictions()->removeAll();
  167. $beGroups = $queryBuilder
  168. ->select('uid', 'title')
  169. ->from('be_groups')
  170. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  171. ->execute()
  172. ->fetchAll();
  173. foreach ($beGroups as $beGroup) {
  174. $site->addMountedForBeGroups($beGroup);
  175. }
  176. return $site;
  177. }
  178. /**
  179. * Creates a new website for the given organization, and
  180. * returns the root page uid of the newly created site
  181. *
  182. * @param int $organizationId
  183. * @param int $mode Can be either MODE_PROD or MODE_DEV, MODE_PROD being the normal behaviour.
  184. * If MODE_DEV is used, sites urls will be of the form 'http://host/subdomain'
  185. * instead of 'http://subdomain/host'
  186. * @return int Uid of the root page of the newly created website
  187. * @throws \RuntimeException|\Throwable
  188. */
  189. public function createSiteAction(int $organizationId, int $mode=self::MODE_PROD): int
  190. {
  191. $organization = $this->fetchOrganization($organizationId);
  192. // This extra-data can not be retrieved from the API for now, but
  193. // this shall be set up as soon as possible, to avoid requesting
  194. // the prod-back DB directly.
  195. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  196. $isNetwork = $organizationExtraData['category'] == 'NETWORK';
  197. // Is there already a website with this organization's id?
  198. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  199. $queryBuilder->getRestrictions()->removeAll();
  200. $statement = $queryBuilder
  201. ->select('uid')
  202. ->from('pages')
  203. ->where($queryBuilder->expr()->eq('tx_opentalent_structure_id', $queryBuilder->createNamedParameter($organization->getId())))
  204. ->andWhere('is_siteroot=1')
  205. ->execute();
  206. if ($statement->rowCount() > 0) {
  207. throw new \RuntimeException("A website with this organization's id already exists: " . $organization->getName() . "\n(if you can't see it, it might have been soft-deleted)");
  208. }
  209. // ** Create the new website
  210. // start transactions
  211. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  212. // keep tracks of the created folders and files to be able to remove them during a rollback
  213. try {
  214. // Create the site pages:
  215. // > Root page
  216. $rootUid = $this->insertRootPage($organization);
  217. // > 'Accueil' shortcut
  218. $this->insertPage(
  219. $organization,
  220. $rootUid,
  221. 'Accueil',
  222. '/accueil',
  223. '',
  224. [
  225. 'dokType' => self::DOK_SHORTCUT,
  226. 'shortcut' => $rootUid
  227. ]
  228. );
  229. // > 'Présentation' page
  230. $this->insertPage(
  231. $organization,
  232. $rootUid,
  233. 'Présentation',
  234. '/presentation'
  235. );
  236. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  237. $this->insertPage(
  238. $organization,
  239. $this->createdPagesIndex['/presentation'],
  240. 'Qui sommes nous?',
  241. '/qui-sommes-nous',
  242. '',
  243. ['hidden' => 1]
  244. );
  245. // > 'Présentation > Les adhérents' page
  246. $this->insertPage(
  247. $organization,
  248. $this->createdPagesIndex['/presentation'],
  249. 'Les adhérents',
  250. '/les-adherents',
  251. self::TEMPLATE_MEMBERS
  252. );
  253. // > 'Présentation > Les membres du CA' page
  254. $this->insertPage(
  255. $organization,
  256. $this->createdPagesIndex['/presentation'],
  257. 'Les membres du CA',
  258. '/les-membres-du-ca',
  259. self::TEMPLATE_MEMBERSCA
  260. );
  261. if ($isNetwork) {
  262. // > 'Présentation > Les sociétés adhérentes' page
  263. $this->insertPage(
  264. $organization,
  265. $this->createdPagesIndex['/presentation'],
  266. 'Les sociétés adhérentes',
  267. '/societes-adherentes',
  268. self::TEMPLATE_STRUCTURES
  269. );
  270. }
  271. // > 'Présentation > Historique' page (hidden by default)
  272. $this->insertPage(
  273. $organization,
  274. $this->createdPagesIndex['/presentation'],
  275. 'Historique',
  276. '/historique',
  277. '',
  278. ['hidden' => 1]
  279. );
  280. // ~ Contact shortcut will be created after the contact page
  281. // > 'Actualités' page (hidden by default)
  282. $this->insertPage(
  283. $organization,
  284. $rootUid,
  285. 'Actualités',
  286. '/actualites',
  287. self::TEMPLATE_NEWS,
  288. ['hidden' => 1]
  289. );
  290. // > 'Saison en cours' page
  291. $this->insertPage(
  292. $organization,
  293. $rootUid,
  294. 'Saison en cours',
  295. '/saison-en-cours'
  296. );
  297. // > 'Saison en cours > Les évènements' page
  298. $this->insertPage(
  299. $organization,
  300. $this->createdPagesIndex['/saison-en-cours'],
  301. 'Les évènements',
  302. '/les-evenements',
  303. self::TEMPLATE_EVENTS
  304. );
  305. if ($isNetwork) {
  306. // > 'Présentation > Les sociétés adhérentes' page
  307. $this->insertPage(
  308. $organization,
  309. $this->createdPagesIndex['/presentation'],
  310. 'Évènements des structures',
  311. '/evenements-des-structures',
  312. self::TEMPLATE_STRUCTURESEVENTS
  313. );
  314. }
  315. // > 'Vie interne' page (restricted, hidden by default)
  316. $this->insertPage(
  317. $organization,
  318. $rootUid,
  319. 'Vie interne',
  320. '/vie-interne',
  321. '',
  322. [
  323. 'hidden' => 1,
  324. 'fe_group' => -2
  325. ]
  326. );
  327. // > 'Footer' page (not in the menu)
  328. $this->insertPage(
  329. $organization,
  330. $rootUid,
  331. 'Footer',
  332. '/footer',
  333. '',
  334. [
  335. 'dokType' => self::DOK_FOLDER,
  336. 'nav_hide' => 1
  337. ]
  338. );
  339. // > 'Footer > Contact' page
  340. $this->insertPage(
  341. $organization,
  342. $this->createdPagesIndex['/footer'],
  343. 'Contact',
  344. '/contact',
  345. self::TEMPLATE_CONTACT
  346. );
  347. // > 'Footer > Plan du site' page
  348. $this->insertPage(
  349. $organization,
  350. $this->createdPagesIndex['/footer'],
  351. 'Plan du site',
  352. '/plan-du-site'
  353. );
  354. // > 'Footer > Mentions légales' page
  355. $this->insertPage(
  356. $organization,
  357. $this->createdPagesIndex['/footer'],
  358. 'Mentions légales',
  359. '/mentions-legales',
  360. self::TEMPLATE_LEGAL
  361. );
  362. // > 'Présentation > Contact' shortcut
  363. $this->insertPage(
  364. $organization,
  365. $this->createdPagesIndex['/presentation'],
  366. 'Contact',
  367. '/ecrivez-nous',
  368. '',
  369. [
  370. 'dokType' => self::DOK_SHORTCUT,
  371. 'shortcut' => $this->createdPagesIndex['/contact']
  372. ]
  373. );
  374. // > 'Page introuvable' page (not in the menu, read-only)
  375. $this->insertPage(
  376. $organization,
  377. $rootUid,
  378. 'Page introuvable',
  379. '/page-introuvable',
  380. '',
  381. [
  382. 'nav_hide' => 1,
  383. 'no_search' => 1
  384. ]
  385. );
  386. // Add content to these pages
  387. // >> root page content
  388. $this->insertContent(
  389. $rootUid,
  390. self::CTYPE_TEXTPIC,
  391. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  392. 0
  393. );
  394. // >> page 'qui sommes nous?'
  395. $this->insertContent(
  396. $this->createdPagesIndex['/qui-sommes-nous'],
  397. self::CTYPE_TEXT,
  398. 'Qui sommes nous ...',
  399. 0
  400. );
  401. // >> page 'historique'
  402. $this->insertContent(
  403. $this->createdPagesIndex['/historique'],
  404. self::CTYPE_TEXT,
  405. "Un peu d'histoire ...",
  406. 0
  407. );
  408. // >> page 'plan du site'
  409. $this->insertContent(
  410. $this->createdPagesIndex['/plan-du-site'],
  411. self::CTYPE_SITEMAP
  412. );
  413. // Build and update the domain
  414. if ($mode == self::MODE_PROD) {
  415. $domain = $organization->getSubDomain() . '.opentalent.fr';
  416. } elseif ($mode == self::MODE_DEV) {
  417. $domain = $organization->getSubDomain() . '/';
  418. } else {
  419. throw new RuntimeException('Unknown value for $mode: ' . $mode);
  420. }
  421. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_domain');
  422. $queryBuilder->insert('sys_domain')
  423. ->values([
  424. 'pid' => $rootUid,
  425. 'domainName' => $domain
  426. ])
  427. ->execute();
  428. // update sys_template
  429. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  430. $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
  431. $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
  432. $include .= ",EXT:form/Configuration/TypoScript/";
  433. $include .= ",EXT:news/Configuration/TypoScript";
  434. $include .= ",EXT:frontend_editing/Configuration/TypoScript";
  435. $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
  436. $include .= ",EXT:ot_templating/Configuration/TypoScript";
  437. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  438. $queryBuilder->insert('sys_template')
  439. ->values([
  440. 'pid' => $rootUid,
  441. 'title' => $organization->getName(),
  442. 'sitetitle' => $organization->getName(),
  443. 'root' => 1,
  444. 'clear' => 3,
  445. 'config' => "config.frontend_editing = 1",
  446. 'include_static_file' => $include,
  447. 'constants' => $constants
  448. ])
  449. ->execute();
  450. // Create the site config.yaml file
  451. $this->writeConfigFile($organizationId, $rootUid, $domain, true);
  452. // Create the user_upload directory and update the sys_filemounts table
  453. $uploadRelPath = "/user_upload/" . $organizationId;
  454. $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
  455. if (file_exists($uploadDir)) {
  456. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  457. }
  458. $defaultUploadDir = $uploadDir . '/images';
  459. $formsDir = $uploadDir . '/Forms';
  460. $this->mkDir($uploadDir);
  461. $this->mkDir($defaultUploadDir);
  462. $this->mkDir($formsDir);
  463. // Insert the filemounts points (sys_filemounts)
  464. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  465. $queryBuilder->insert('sys_filemounts')
  466. ->values([
  467. 'title' => 'Documents',
  468. 'path' => $defaultUploadDir,
  469. 'base' => 1
  470. ])
  471. ->execute();
  472. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  473. $queryBuilder->insert('sys_filemounts')
  474. ->values([
  475. 'title' => 'Forms_' . $organizationId,
  476. 'path' => $formsDir,
  477. 'base' => 1
  478. ])
  479. ->execute();
  480. // Create the BE Editors group
  481. // -- NB: this user will then be auto-updated by the ot_connect extension --
  482. $beGroupUid = $this->createOrUpdateBeGroup(
  483. $organizationId,
  484. $rootUid,
  485. $organizationExtraData['admin']
  486. );
  487. // Create the BE User
  488. // -- NB: this user will then be auto-updated by the ot_connect extension --
  489. $beUserUid = $this->createOrUpdateBeUser(
  490. $organizationId,
  491. $rootUid,
  492. $beGroupUid,
  493. $organizationExtraData['admin']
  494. );
  495. // Update the user TsConfig
  496. $tsconfig = "options.uploadFieldsInTopOfEB = 1\n" .
  497. "options.defaultUploadFolder=1:" . $defaultUploadDir . "\n";
  498. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  499. $queryBuilder
  500. ->update('be_users')
  501. ->where($queryBuilder->expr()->eq('uid', $beUserUid))
  502. ->set('TSconfig', $tsconfig)
  503. ->execute();
  504. // Setup user and group rights
  505. $this->setBeUserPerms($organizationId, false, $beGroupUid, $beUserUid);
  506. // Try to commit the result
  507. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  508. if (!$commitSuccess) {
  509. throw new \RuntimeException('Something went wrong while commiting the result');
  510. }
  511. } catch(\Throwable $e) {
  512. // rollback
  513. $this->connectionPool->getConnectionByName('Default')->rollback();
  514. // remove created files and dirs
  515. foreach (array_reverse($this->createdFiles) as $filename) {
  516. unlink($filename);
  517. }
  518. $this->createdFiles = [];
  519. foreach (array_reverse($this->createdDirs) as $dirname) {
  520. rmdir($dirname);
  521. }
  522. $this->createdDirs = [];
  523. throw $e;
  524. }
  525. // Extra steps that do not need any rollback:
  526. $this->enableFeEditing($beUserUid);
  527. return $rootUid;
  528. }
  529. /**
  530. * Update the `sys_template`.`constants` field of the given
  531. * organization's website with the data fetched from the opentalent DB.
  532. *
  533. * @param int $organizationId
  534. * @return int
  535. * @throws NoSuchWebsiteException
  536. */
  537. public function updateSiteConstantsAction(int $organizationId): int
  538. {
  539. $rootUid = $this->findRootUidFor($organizationId);
  540. // This extra-data can not be retrieved from the API for now, but
  541. // this shall be set up as soon as possible, to avoid requesting
  542. // the prod-back DB directly.
  543. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  544. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  545. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  546. $queryBuilder
  547. ->update('sys_template')
  548. ->set('constants', $constants)
  549. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  550. ->execute();
  551. OtCacheManager::clearSiteCache($rootUid, true);
  552. return $rootUid;
  553. }
  554. /**
  555. * Delete the website with all its pages, contents and related records
  556. *
  557. * If the hard parameter is false, the records' `deleted` field will be set to true and
  558. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  559. *
  560. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  561. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  562. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  563. *
  564. * $redirectTo is the optional organization id to whom requests will be redirected
  565. *
  566. * @param int $organizationId
  567. * @param bool $hard
  568. * @param int|null $redirectTo
  569. * @return int
  570. * @throws NoSuchWebsiteException
  571. * @throws \Doctrine\DBAL\ConnectionException
  572. * @throws \Doctrine\DBAL\DBALException
  573. */
  574. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null) {
  575. $rootUid = $this->findRootUidFor($organizationId);
  576. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  577. $isDeleted = $queryBuilder
  578. ->select('deleted')
  579. ->from('pages')
  580. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  581. ->execute()
  582. ->fetchColumn(0) == 1;
  583. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  584. if ($hard && !file_exists($confirm_file)) {
  585. throw new \RuntimeException(
  586. "You are going to completely delete the website with root uid " . $rootUid .
  587. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  588. $confirm_file . "', and launch this command again."
  589. );
  590. }
  591. // Prepare the redirection
  592. if ($redirectTo) {
  593. if ($redirectTo == $organizationId) {
  594. throw new \InvalidArgumentException('redirectTo value has to be different from the organizationId');
  595. }
  596. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  597. $targetUrl = $this->getSiteInfosAction($redirectTo)->getBaseUrl();
  598. }
  599. // start transactions
  600. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  601. // keep track of renamed file for an eventual rollback
  602. $renamed = [];
  603. try {
  604. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  605. foreach($pages as $page) {
  606. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  607. $this->delete('pages', 'uid', $page['uid'], $hard);
  608. }
  609. $this->delete('tt_content', 'pid', $rootUid, $hard);
  610. $this->delete('pages', 'uid', $rootUid, $hard);
  611. $this->delete('sys_template', 'pid', $rootUid, $hard);
  612. if ($hard) {
  613. // there is no 'deleted' field in sys_domain
  614. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  615. }
  616. // remove filemounts
  617. $this->delete('sys_filemounts',
  618. 'path',
  619. "'/user_upload/" . $organizationId . "/images'",
  620. $hard);
  621. $this->delete('sys_filemounts',
  622. 'path',
  623. "'/user_upload/" . $organizationId . "/Forms'",
  624. $hard);
  625. $adminBeUserUid = $this->findAdminBeUserUid($rootUid);
  626. if ($adminBeUserUid !== null) {
  627. $this->delete('be_users', 'uid', $adminBeUserUid, $hard);
  628. }
  629. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  630. if ($editorsGroupUid !== null) {
  631. $this->delete('be_groups', 'uid', $editorsGroupUid, $hard);
  632. }
  633. // Look up for the config.yaml file of the website
  634. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  635. $configYamlFile = "";
  636. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  637. if (!$isDeleted) {
  638. $yamlFile = $subdir . '/config.yaml';
  639. } else {
  640. $yamlFile = $subdir . '/config.yaml.deleted';
  641. }
  642. if (is_file($yamlFile)) {
  643. $conf = Yaml::parseFile($yamlFile);
  644. if ($conf['rootPageId'] == $rootUid) {
  645. $configYamlFile = $yamlFile;
  646. break;
  647. }
  648. }
  649. }
  650. if (!$isDeleted) {
  651. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  652. } else {
  653. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  654. }
  655. // If hard deletion, verify that upload dirs are empty
  656. if ($hard && is_dir($uploadDir)) {
  657. foreach (scandir($uploadDir) as $subdir) {
  658. if ($subdir == '.' or $subdir == '..') {
  659. continue;
  660. }
  661. $subdir = $uploadDir . $subdir;
  662. if (!is_dir($subdir)) {
  663. throw new \RuntimeException(
  664. 'The directory ' . $uploadDir . ' contains non-directory files' .
  665. ', this humble script prefers not to take care of them automatically. Abort.');
  666. }
  667. if (is_readable($subdir)) {
  668. foreach (scandir($subdir) as $filename) {
  669. if ($filename != '.' && $filename != '..') {
  670. throw new \RuntimeException(
  671. 'The directory ' . $subdir . ' is not empty, ' .
  672. 'this humble script prefers not to take care of them automatically. Abort.');
  673. }
  674. }
  675. }
  676. }
  677. }
  678. // If soft deletion, check that no deleted file or directory exist
  679. if (!$hard) {
  680. $toRename = [];
  681. if (!$hard) {
  682. if (is_file($configYamlFile)) {
  683. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  684. }
  685. if (is_dir($uploadDir)) {
  686. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  687. }
  688. }
  689. foreach ($toRename as $initialPath => $newPath) {
  690. if (is_file($newPath)) {
  691. throw new \RuntimeException(
  692. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  693. }
  694. }
  695. }
  696. // Delete or rename files and dirs
  697. if ($hard) {
  698. if (is_file($configYamlFile)) {
  699. unlink($configYamlFile);
  700. }
  701. if (is_dir(dirname($configYamlFile))) {
  702. rmdir(dirname($configYamlFile));
  703. }
  704. if (is_dir($uploadDir . 'images')) {
  705. rmdir($uploadDir . 'images');
  706. }
  707. if (is_dir($uploadDir . 'Forms')) {
  708. rmdir($uploadDir . 'Forms');
  709. }
  710. if (is_dir($uploadDir)) {
  711. rmdir($uploadDir);
  712. }
  713. } else {
  714. $renamed = [];
  715. foreach ($toRename as $initialPath => $newPath) {
  716. rename($initialPath, $newPath);
  717. $renamed[$initialPath] = $newPath;
  718. }
  719. }
  720. // Add the redirection
  721. if ($redirectTo) {
  722. $this->addRedirection($originUrl, $targetUrl);
  723. }
  724. // Try to commit the result
  725. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  726. if (!$commitSuccess) {
  727. throw new \RuntimeException('Something went wrong while commiting the result');
  728. }
  729. return $rootUid;
  730. } catch(\Throwable $e) {
  731. // rollback
  732. $this->connectionPool->getConnectionByName('Default')->rollback();
  733. if (!$hard) {
  734. foreach ($renamed as $initialPath => $newPath) {
  735. rename($newPath, $initialPath);
  736. }
  737. }
  738. throw $e;
  739. } finally {
  740. if (file_exists($confirm_file)) {
  741. unlink($confirm_file);
  742. }
  743. }
  744. }
  745. /**
  746. * Delete a record from the typo3 db.
  747. * If $hard is true, the record is permanently deleted.
  748. * Else, it's just marked as deleted.
  749. *
  750. * @param string $table
  751. * @param string $whereKey
  752. * @param $whereValue
  753. * @param int $hard
  754. */
  755. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  756. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  757. if (!$hard) {
  758. $queryBuilder
  759. ->update($table)
  760. ->set('deleted', 1)
  761. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  762. ->execute();
  763. } else {
  764. $queryBuilder
  765. ->delete($table)
  766. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  767. ->execute();
  768. }
  769. }
  770. /**
  771. * Undo a soft-deletion performed using deleteSiteAction()
  772. *
  773. * @param int $organizationId
  774. * @return int
  775. * @throws NoSuchWebsiteException
  776. * @throws \Doctrine\DBAL\ConnectionException
  777. * @throws \Doctrine\DBAL\DBALException
  778. */
  779. public function undeleteSiteAction(int $organizationId) {
  780. $rootUid = $this->findRootUidFor($organizationId);
  781. // start transactions
  782. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  783. // keep track of renamed file for an eventual rollback
  784. $renamed = [];
  785. try {
  786. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  787. foreach($pages as $page) {
  788. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  789. $queryBuilder
  790. ->update('tt_content')
  791. ->set('deleted', 0)
  792. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  793. ->execute();
  794. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  795. $queryBuilder
  796. ->update('pages')
  797. ->set('deleted', 0)
  798. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  799. ->execute();
  800. }
  801. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  802. $queryBuilder
  803. ->update('tt_content')
  804. ->set('deleted', 0)
  805. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  806. ->execute();
  807. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  808. $queryBuilder
  809. ->update('pages')
  810. ->set('deleted', 0)
  811. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  812. ->execute();
  813. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  814. $queryBuilder
  815. ->update('sys_template')
  816. ->set('deleted', 0)
  817. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  818. ->execute();
  819. // remove filemounts
  820. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  821. $queryBuilder
  822. ->update('sys_filemounts')
  823. ->set('deleted', 0)
  824. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  825. ->execute();
  826. $queryBuilder
  827. ->update('sys_filemounts')
  828. ->set('deleted', 0)
  829. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  830. ->execute();
  831. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  832. $queryBuilder
  833. ->update('be_users')
  834. ->set('deleted', 0)
  835. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  836. ->execute();
  837. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid, false);
  838. if ($editorsGroupUid !== null) {
  839. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  840. $queryBuilder
  841. ->update('be_groups')
  842. ->set('deleted', 0)
  843. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  844. ->execute();
  845. }
  846. $adminBeUserUid = $this->findAdminBeUserUid($rootUid, false);
  847. if ($adminBeUserUid !== null) {
  848. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  849. $queryBuilder
  850. ->update('be_users')
  851. ->set('deleted', 0)
  852. ->where($queryBuilder->expr()->eq('uid', $adminBeUserUid))
  853. ->execute();
  854. }
  855. // Look up for the config.yaml file of the website
  856. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  857. $configYamlFile = "";
  858. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  859. $yamlFile = $subdir . '/config.yaml.deleted';
  860. if (is_file($yamlFile)) {
  861. $conf = Yaml::parseFile($yamlFile);
  862. if ($conf['rootPageId'] == $rootUid) {
  863. $configYamlFile = $yamlFile;
  864. break;
  865. }
  866. }
  867. }
  868. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  869. $toRename = [];
  870. if (is_file($configYamlFile)) {
  871. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  872. }
  873. if (is_dir($uploadDir)) {
  874. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  875. }
  876. foreach ($toRename as $initialPath => $newPath) {
  877. if (is_file($newPath)) {
  878. throw new \RuntimeException(
  879. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  880. }
  881. }
  882. $renamed = [];
  883. foreach ($toRename as $initialPath => $newPath) {
  884. rename($initialPath, $newPath);
  885. $renamed[$initialPath] = $newPath;
  886. }
  887. // remove eventual redirection from this site to another
  888. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  889. $this->removeRedirectionsFrom($originUrl);
  890. // Try to commit the result
  891. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  892. if (!$commitSuccess) {
  893. throw new \RuntimeException('Something went wrong while commiting the result');
  894. }
  895. return $rootUid;
  896. } catch(\Throwable $e) {
  897. // rollback
  898. $this->connectionPool->getConnectionByName('Default')->rollback();
  899. foreach ($renamed as $initialPath => $newPath) {
  900. rename($newPath, $initialPath);
  901. }
  902. throw $e;
  903. }
  904. }
  905. /**
  906. * Clear the cache of the organization's website
  907. *
  908. * @param int $organizationId the organization's id whom site cache should be cleared
  909. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  910. * @return int
  911. * @throws NoSuchWebsiteException
  912. */
  913. public function clearSiteCacheAction(int $organizationId, $clearAll=false): int
  914. {
  915. $rootUid = $this->findRootUidFor($organizationId);
  916. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  917. return $rootUid;
  918. }
  919. /**
  920. * Perform a full scan of the website and returns a list of warnings
  921. *
  922. * @param int $organizationId
  923. * @param int $rootUid
  924. * @return array
  925. */
  926. private function scanSite(int $organizationId, int $rootUid) {
  927. $warnings = [];
  928. // fetch pages and root page
  929. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  930. $rootPage = null;
  931. $pageIndex = [];
  932. foreach ($pages as $page) {
  933. $pageIndex[$page['uid']] = $page;
  934. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  935. }
  936. // fetch organization and extradata
  937. $organization = $this->fetchOrganization($organizationId);
  938. $extraData = $this->fetchOrganizationExtraData($organizationId);
  939. // load site's settings (uncomment if needed)
  940. // $config = $this->findConfigFor($rootUid);
  941. // Check site's title
  942. if (trim($rootPage['title']) != trim($organization->getName())) {
  943. $warnings[] = "Site's title does not match the organization name";
  944. }
  945. // Who is the expected owner among the be_users? there should be only one.
  946. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  947. $queryBuilder->getRestrictions()->removeAll();
  948. $beUsers = $queryBuilder
  949. ->select('uid', 'username')
  950. ->from('be_users')
  951. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  952. ->execute()
  953. ->fetchAll();
  954. $owner = null;
  955. if (count($beUsers) > 1) {
  956. $warnings[] = 'Website is mounted on more than one be_user: ' .
  957. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  958. } elseif (count($beUsers) == 0) {
  959. $warnings[] = 'Website is not mounted on any be_user';
  960. } else {
  961. $owner = $beUsers[0];
  962. }
  963. // are template constants up to date?
  964. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  965. $actual_constants = $queryBuilder
  966. ->select('constants')
  967. ->from('sys_template')
  968. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  969. ->execute()
  970. ->fetchColumn(0);
  971. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  972. $norm = function ($s) {
  973. return strtolower(preg_replace('/\s/', '', $s));
  974. };
  975. if ($norm($expected_constants) != $norm($actual_constants)) {
  976. $warnings[] = 'Template constants need an update';
  977. }
  978. $expected_templates = [
  979. "OpenTalent.OtTemplating->home" => 0,
  980. "OpenTalent.OtTemplating->legal" => 0,
  981. "OpenTalent.OtTemplating->contact" => 0
  982. ];
  983. foreach ($pages as $page) {
  984. if ($page['deleted']) {
  985. continue;
  986. }
  987. // Is it the correct owner?
  988. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  989. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  990. }
  991. if (!$page['is_siteroot']) {
  992. // is the parent page state (deleted, hidden, restricted) the same as this page?
  993. $parent = $pageIndex[$page['pid']];
  994. if ($parent['deleted']) {
  995. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  996. }
  997. if ($parent['hidden'] && !$page['hidden']) {
  998. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  999. }
  1000. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  1001. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  1002. }
  1003. }
  1004. // an expected template was found, remove it from the list of expected
  1005. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  1006. !$page['deleted'] && !$page['hidden']) {
  1007. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  1008. }
  1009. }
  1010. foreach ($expected_templates as $template => $_) {
  1011. $warnings[] = 'No page with template ' . $template;
  1012. }
  1013. return $warnings;
  1014. }
  1015. /**
  1016. * Get the current status and informations of the organization's website
  1017. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  1018. *
  1019. * The status is among:
  1020. *
  1021. * - STATUS_NO_SUCH_WEBSITE
  1022. * - STATUS_EXISTING
  1023. * - STATUS_EXISTING_DELETED
  1024. * - STATUS_EXISTING_HIDDEN
  1025. * - STATUS_EXISTING_WITH_WARNINGS
  1026. *
  1027. * @param int $organizationId the organization's id whom site cache should be cleared
  1028. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1029. * the website pages will be performed.
  1030. * @return SiteStatus
  1031. */
  1032. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  1033. {
  1034. try {
  1035. $siteInfos = $this->getSiteInfosAction($organizationId);
  1036. } catch (NoSuchWebsiteException $e) {
  1037. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  1038. }
  1039. if ($siteInfos->isDeleted()) {
  1040. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  1041. }
  1042. if ($siteInfos->isHiddenOrRestricted()) {
  1043. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  1044. }
  1045. $warnings = null;
  1046. if ($fullScan) {
  1047. // ** Look for potential issues
  1048. $warnings = $this->scanSite($organizationId, $siteInfos->getRootUid());
  1049. }
  1050. return new SiteStatus(
  1051. $organizationId,
  1052. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  1053. $siteInfos,
  1054. $warnings
  1055. );
  1056. }
  1057. /**
  1058. * Set a new domain for the website.
  1059. * If $redirect is true, also add a redirection from the former domain to the new one
  1060. *
  1061. * @param int $organizationId
  1062. * @param string $newDomain
  1063. * @param bool $redirect
  1064. * @return int
  1065. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1066. * @throws NoSuchWebsiteException
  1067. */
  1068. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1069. {
  1070. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1071. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1072. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1073. }
  1074. $infos = $this->getSiteInfosAction($organizationId);
  1075. $originUrl = $infos->getBaseUrl();
  1076. $rootUid = $infos->getRootUid();
  1077. if (preg_replace('/https?:\/\//', '', $originUrl) == preg_replace('/https?:\/\//', '', $newDomain) ) {
  1078. throw new \RuntimeException('The new domain should be different of the current one');
  1079. }
  1080. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1081. if ($redirect) {
  1082. // Add the redirection
  1083. $this->addRedirection($originUrl, $newDomain);
  1084. }
  1085. return $rootUid;
  1086. }
  1087. /**
  1088. * Return all of the redirections from the given domain name,
  1089. * even if they have been marked as deleted.
  1090. *
  1091. * @param $domain string Domain name, without the http(s):// part
  1092. * @return array Rows from the sys_redirect table
  1093. */
  1094. protected function getRedirectionsFrom(string $domain): array
  1095. {
  1096. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1097. $queryBuilder->getRestrictions()->removeAll();
  1098. return $queryBuilder
  1099. ->select('*')
  1100. ->from('sys_redirect')
  1101. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1102. ->execute()
  1103. ->fetchAll();
  1104. }
  1105. /**
  1106. * Return all of the redirections to the given domain name,
  1107. * even if they have been marked as deleted.
  1108. *
  1109. * @param $domain string Domain name, without the http(s):// part
  1110. * @return array Rows from the sys_redirect table
  1111. */
  1112. protected function getRedirectionsTo(string $domain): array
  1113. {
  1114. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1115. $queryBuilder->getRestrictions()->removeAll();
  1116. return $queryBuilder
  1117. ->select('*')
  1118. ->from('sys_redirect')
  1119. ->where(
  1120. $queryBuilder->expr()->in(
  1121. 'target',
  1122. [
  1123. 'http://' . $queryBuilder->expr()->literal($domain),
  1124. 'https://' . $queryBuilder->expr()->literal($domain)
  1125. ]
  1126. )
  1127. )
  1128. ->execute()
  1129. ->fetchAll();
  1130. }
  1131. /**
  1132. * Add a new redirection from $fromDomain to $toDomain.
  1133. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1134. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1135. *
  1136. * @param $fromDomain
  1137. * @param $toDomain
  1138. * @return int Status of the operation
  1139. */
  1140. public function addRedirection($fromDomain, $toDomain): int
  1141. {
  1142. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1143. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1144. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1145. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1146. }
  1147. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1148. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1149. }
  1150. $existing = $this->getRedirectionsFrom($fromDomain);
  1151. $toUpdate = null;
  1152. foreach ($existing as $redirection) {
  1153. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1154. // a redirection from this domain already exists, and it is not deleted nor disabled
  1155. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1156. // the target is not the same domain
  1157. throw new \RuntimeException(
  1158. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1159. );
  1160. } else {
  1161. // else, target is already the same domain, it will be updated
  1162. $toUpdate = $redirection;
  1163. break;
  1164. }
  1165. } else {
  1166. // a redirection from this domain already exists, but it is deleted or disabled
  1167. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1168. // the target is the same domain, we'll reactivate this record
  1169. $toUpdate = $redirection;
  1170. break;
  1171. }
  1172. }
  1173. }
  1174. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1175. $data = [
  1176. 'deleted' => 0,
  1177. 'disabled' => 0,
  1178. 'source_host' => $fromDomain,
  1179. 'source_path' => '/.*/',
  1180. 'is_regexp' => 1,
  1181. 'force_https' => 0,
  1182. 'respect_query_parameters' => 0,
  1183. 'keep_query_parameters' => 1,
  1184. 'target' => 'https://' . $toDomain,
  1185. 'target_statuscode' => 301
  1186. ];
  1187. if ($toUpdate !== null) {
  1188. $q = $queryBuilder
  1189. ->update('sys_redirect')
  1190. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1191. foreach ($data as $k => $v) {
  1192. $q->set($k, $v);
  1193. }
  1194. $q->execute();
  1195. return self::REDIRECTION_UPDATED;
  1196. } else {
  1197. $queryBuilder
  1198. ->insert('sys_redirect')
  1199. ->values($data)
  1200. ->execute();
  1201. return self::REDIRECTION_CREATED;
  1202. }
  1203. }
  1204. /**
  1205. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1206. * If $hard is true, delete it completely.
  1207. *
  1208. * @param $fromDomain
  1209. * @param bool $hard
  1210. * @return int Number of affected rows
  1211. */
  1212. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1213. {
  1214. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1215. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1216. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1217. }
  1218. $existing = $this->getRedirectionsFrom($fromDomain);
  1219. $deleted = 0;
  1220. foreach ($existing as $redirection) {
  1221. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1222. $deleted += 1;
  1223. }
  1224. return $deleted;
  1225. }
  1226. /**
  1227. * Set the rights of admin and editors of the website
  1228. * on all of the existing pages, including deleted ones
  1229. *
  1230. * @param int $organizationId
  1231. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1232. * @param int|null $editorsGroupUid Force the editors be-group uid
  1233. * @param int|null $adminUid Force the admin be-user uid
  1234. * @return int The uid of the website root page
  1235. * @throws NoSuchWebsiteException
  1236. * @throws NoSuchRecordException
  1237. */
  1238. protected function setBeUserPerms(
  1239. int $organizationId,
  1240. bool $createIfMissing = false,
  1241. int $editorsGroupUid = null,
  1242. int $adminUid = null
  1243. ): int
  1244. {
  1245. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1246. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1247. "and force the admin or group uid at the same time.");
  1248. }
  1249. $rootUid = $this->findRootUidFor($organizationId);
  1250. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1251. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']];
  1252. if ($editorsGroupUid == null) {
  1253. try {
  1254. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1255. } catch (NoSuchRecordException $e) {
  1256. if (!$createIfMissing) {
  1257. throw $e;
  1258. }
  1259. }
  1260. }
  1261. if ($adminUid == null) {
  1262. try {
  1263. $adminUid = $this->findAdminBeUserUid($rootUid);
  1264. } catch (NoSuchRecordException $e) {
  1265. if (!$createIfMissing) {
  1266. throw $e;
  1267. }
  1268. }
  1269. }
  1270. // Creates or update the admin be_group
  1271. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1272. $organizationId,
  1273. $rootUid,
  1274. $organizationExtraData['admin'],
  1275. $editorsGroupUid
  1276. );
  1277. // Creates or update the admin be_user
  1278. $adminUid = $this->createOrUpdateBeUser(
  1279. $organizationId,
  1280. $rootUid,
  1281. $editorsGroupUid,
  1282. $organizationExtraData['admin'],
  1283. $adminUid
  1284. );
  1285. // Reset the appartenance to groups
  1286. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1287. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1288. $queryBuilder
  1289. ->update('be_users')
  1290. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1291. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1292. ->execute();
  1293. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1294. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1295. $queryBuilder
  1296. ->update('be_groups')
  1297. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1298. ->set('subgroup', $mainEditorGroupUid)
  1299. ->execute();
  1300. // setup default owner for the website
  1301. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1302. $tsConfig = $queryBuilder->select('TSconfig')
  1303. ->from('pages')
  1304. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1305. ->execute()
  1306. ->fetchColumn(0);
  1307. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1308. $tsConfig .= "\nTCEMAIN {\n" .
  1309. " permissions.userid = " . $adminUid ."\n" .
  1310. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1311. "}";
  1312. $queryBuilder
  1313. ->update('pages')
  1314. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1315. ->set('TSconfig', $tsConfig)
  1316. ->execute();
  1317. // fetch pages and root page
  1318. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  1319. // To understand how the rights levels are computed:
  1320. // @see https://ressources.opentalent.fr/display/EX/Droits+des+BE+Users
  1321. foreach ($pages as $page) {
  1322. if ($page['is_siteroot']) {
  1323. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1324. if ($isPremium) {
  1325. $adminPerms += self::PERM_NEW;
  1326. }
  1327. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT;
  1328. } else if (
  1329. $page['slug'] == '/footer' ||
  1330. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->legal' ||
  1331. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->contact' ||
  1332. $page['slug'] == '/plan-du-site'
  1333. ) {
  1334. $adminPerms = self::PERM_SHOW;
  1335. if ($isPremium) {
  1336. $adminPerms += self::PERM_NEW;
  1337. }
  1338. $editorsPerms = self::PERM_SHOW;
  1339. } else if (
  1340. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->members' ||
  1341. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->membersCa' ||
  1342. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structures' ||
  1343. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->events' ||
  1344. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structuresEvents'
  1345. ) {
  1346. $adminPerms = self::PERM_SHOW;
  1347. if ($isPremium) {
  1348. $adminPerms += self::PERM_NEW + self::PERM_EDIT_PAGE;
  1349. }
  1350. $editorsPerms = self::PERM_SHOW;
  1351. } else {
  1352. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1353. if ($isPremium) {
  1354. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1355. }
  1356. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1357. if ($isPremium) {
  1358. $editorsPerms += self::PERM_NEW;
  1359. }
  1360. }
  1361. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1362. $queryBuilder
  1363. ->update('pages')
  1364. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1365. ->set('perms_userid', $adminUid)
  1366. ->set('perms_groupid', $editorsGroupUid)
  1367. ->set('perms_user', $adminPerms)
  1368. ->set('perms_group', $editorsPerms)
  1369. ->set('perms_everybody', 0)
  1370. ->execute();
  1371. }
  1372. return $rootUid;
  1373. }
  1374. /**
  1375. * CLI action for resetting the rights of admin and editors of the website
  1376. * on all of the existing pages, including deleted ones
  1377. *
  1378. * @param int $organizationId
  1379. * @param bool $createIfMissing
  1380. * @return int
  1381. * @throws NoSuchRecordException
  1382. * @throws NoSuchWebsiteException
  1383. * @throws \Throwable
  1384. */
  1385. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1386. {
  1387. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1388. try {
  1389. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1390. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1391. if (!$commitSuccess) {
  1392. throw new \RuntimeException('Something went wrong while commiting the result');
  1393. }
  1394. return $rootUid;
  1395. }
  1396. catch (\Throwable $e) {
  1397. // rollback
  1398. $this->connectionPool->getConnectionByName('Default')->rollback();
  1399. throw $e;
  1400. }
  1401. }
  1402. /**
  1403. * Retrieve the Organization object from the repository and then,
  1404. * from the Opentalent API
  1405. *
  1406. * @param $organizationId
  1407. * @return Organization
  1408. */
  1409. private function fetchOrganization($organizationId): Organization
  1410. {
  1411. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1412. try {
  1413. return $organizationRepository->findById($organizationId);
  1414. } catch (ApiRequestException $e) {
  1415. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1416. }
  1417. }
  1418. /**
  1419. * Try to find the root page uid of the organization's website and return it.
  1420. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1421. *
  1422. * @param $organizationId
  1423. * @return int
  1424. * @throws NoSuchWebsiteException
  1425. */
  1426. private function findRootUidFor($organizationId): int
  1427. {
  1428. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1429. $queryBuilder->getRestrictions()->removeAll();
  1430. $rootUid = $queryBuilder
  1431. ->select('uid')
  1432. ->from('pages')
  1433. ->where('is_siteroot=1')
  1434. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1435. ->execute()
  1436. ->fetchColumn(0);
  1437. if ($rootUid > 0) {
  1438. return $rootUid;
  1439. }
  1440. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1441. }
  1442. /**
  1443. * Try to find the id of the organization owning this website.
  1444. *
  1445. * @param $rootUid
  1446. * @return int
  1447. * @throws NoSuchWebsiteException
  1448. */
  1449. private function findOrganizationIdUidFor($rootUid): int
  1450. {
  1451. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1452. $queryBuilder->getRestrictions()->removeAll();
  1453. $organizationId = $queryBuilder
  1454. ->select('tx_opentalent_structure_id')
  1455. ->from('pages')
  1456. ->where('is_siteroot=1')
  1457. ->andWhere($queryBuilder->expr()->eq('uid', $rootUid))
  1458. ->execute()
  1459. ->fetchColumn(0);
  1460. if ($organizationId > 0) {
  1461. return $organizationId;
  1462. }
  1463. throw new NoSuchWebsiteException("No organization found for website " . $rootUid);
  1464. }
  1465. /**
  1466. * Determine which folder-type Typo3 page should contain the new website
  1467. * CREATES IT if needed, and return its uid
  1468. *
  1469. * @return int
  1470. */
  1471. private function getParentFolderUid(): int
  1472. {
  1473. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1474. $siteCount = $queryBuilder
  1475. ->count('uid')
  1476. ->from('pages')
  1477. ->where('is_siteroot=1')
  1478. ->execute()
  1479. ->fetchColumn(0);
  1480. $thousand = (int)(($siteCount + 1) / 1000);
  1481. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1482. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1483. $uid = $queryBuilder
  1484. ->select('uid')
  1485. ->from('pages')
  1486. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1487. ->andWhere('dokType=254')
  1488. ->execute()
  1489. ->fetchColumn(0);
  1490. if ($uid == null) {
  1491. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1492. $queryBuilder->insert('pages')
  1493. ->values([
  1494. 'pid' => 0,
  1495. 'title' => $folderName,
  1496. 'dokType' => 254,
  1497. 'sorting' => 11264,
  1498. 'perms_userid' => 1,
  1499. 'perms_groupid' => 31,
  1500. 'perms_group' => 27,
  1501. ])
  1502. ->execute();
  1503. $uid = $queryBuilder->getConnection()->lastInsertId();
  1504. }
  1505. return $uid;
  1506. }
  1507. /**
  1508. * Insert a new row in the 'pages' table of the Typo3 DB
  1509. * and return its uid
  1510. *
  1511. * @param Organization $organization
  1512. * @param int $pid
  1513. * @param string $title
  1514. * @param string $slug
  1515. * @param string $template
  1516. * @param array $moreValues
  1517. * @return int
  1518. */
  1519. private function insertPage(Organization $organization,
  1520. int $pid,
  1521. string $title,
  1522. string $slug,
  1523. string $template = '',
  1524. array $moreValues = []
  1525. ): int
  1526. {
  1527. $defaultValues = [
  1528. 'pid' => $pid,
  1529. 'perms_groupid' => 3,
  1530. 'perms_user' => 27,
  1531. 'cruser_id' => 1,
  1532. 'dokType' => self::DOK_PAGE,
  1533. 'title' => $title,
  1534. 'slug' => $slug,
  1535. 'backend_layout' => 'flux__grid',
  1536. 'backend_layout_next_level' => 'flux__grid',
  1537. 'tx_opentalent_structure_id' => $organization->getId()
  1538. ];
  1539. if ($template) {
  1540. $defaultValues['tx_fed_page_controller_action'] = $template;
  1541. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1542. }
  1543. $values = array_merge($defaultValues, $moreValues);
  1544. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1545. $queryBuilder->insert('pages')
  1546. ->values($values)
  1547. ->execute();
  1548. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1549. $this->createdPagesIndex[$slug] = $uid;
  1550. return $uid;
  1551. }
  1552. /**
  1553. * Insert the root page of a new organization's website
  1554. * and return its uid
  1555. *
  1556. * @param Organization $organization
  1557. * @return int
  1558. */
  1559. private function insertRootPage(Organization $organization): int
  1560. {
  1561. return $this->insertPage(
  1562. $organization,
  1563. $this->getParentFolderUid(),
  1564. $organization->getName(),
  1565. '/',
  1566. self::TEMPLATE_HOME,
  1567. [
  1568. 'is_siteroot' => 1,
  1569. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1570. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1571. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1572. ]
  1573. );
  1574. }
  1575. /**
  1576. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1577. *
  1578. * @param int $pid
  1579. * @param string $cType
  1580. * @param string $bodyText
  1581. * @param int $colPos
  1582. * @param array $moreValues
  1583. */
  1584. private function insertContent(int $pid,
  1585. string $cType=self::CTYPE_TEXT,
  1586. string $bodyText = '',
  1587. int $colPos=0,
  1588. array $moreValues = []) {
  1589. $defaultValues = [
  1590. 'pid' => $pid,
  1591. 'cruser_id' => 1,
  1592. 'CType' => $cType,
  1593. 'colPos' => $colPos,
  1594. 'bodyText' => $bodyText
  1595. ];
  1596. $values = array_merge($defaultValues, $moreValues);
  1597. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1598. $queryBuilder->insert('tt_content')
  1599. ->values($values)
  1600. ->execute();
  1601. }
  1602. private function fetchOrganizationExtraData(int $organizationId) {
  1603. $cnn = new PDO(
  1604. "mysql:host=prod-back;dbname=opentalent",
  1605. 'dbcloner',
  1606. 'wWZ4hYcrmHLW2mUK',
  1607. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1608. );
  1609. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1610. $stmt = $cnn->prepare(
  1611. "SELECT o.id, o.name, o.facebook, o.twitter,
  1612. o.category, o.logo_id, p.logoDonorsMove
  1613. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1614. ON o.parameters_id = p.id
  1615. WHERE o.id=" . $organizationId . ";"
  1616. );
  1617. $stmt->execute();
  1618. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1619. $data = $stmt->fetch();
  1620. $stmt = $cnn->prepare(
  1621. "SELECT c.email
  1622. FROM opentalent.ContactPoint c
  1623. INNER JOIN opentalent.organization_contactpoint o
  1624. ON o.contactPoint_id = c.id
  1625. WHERE c.contactType = 'PRINCIPAL'
  1626. AND o.organization_id = " . $organizationId . ";"
  1627. );
  1628. $stmt->execute();
  1629. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1630. $data['email'] = $stmt->fetch()['email'];
  1631. $stmt = $cnn->prepare(
  1632. "SELECT n.name, n.logo, n.url
  1633. FROM opentalent.Network n
  1634. INNER JOIN
  1635. (opentalent.NetworkOrganization l
  1636. INNER JOIN opentalent.Organization o
  1637. ON l.organization_id = o.id)
  1638. ON l.network_id = n.id
  1639. WHERE l.endDate is NULL
  1640. AND o.id=" . $organizationId . ";"
  1641. );
  1642. $stmt->execute();
  1643. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1644. $data['network'] = $stmt->fetch();
  1645. $stmt = $cnn->prepare(
  1646. "SELECT p.username, p.id as person_id, s.product
  1647. FROM opentalent.Person p
  1648. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1649. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1650. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1651. );
  1652. $stmt->execute();
  1653. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1654. $data['admin'] = $stmt->fetch();
  1655. return $data;
  1656. }
  1657. /**
  1658. * Return the content of `sys_template`.`constants` of
  1659. * the website of the given organization
  1660. *
  1661. * @param int $organizationId
  1662. * @param array $organizationExtraData
  1663. * @return string
  1664. */
  1665. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1666. {
  1667. return "plugin.tx_ottemplating {\n" .
  1668. " settings {\n" .
  1669. " organization {\n" .
  1670. " id = " . $organizationId . "\n" .
  1671. " name = " . $organizationExtraData['name'] . "\n" .
  1672. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1673. " email = " . $organizationExtraData['email'] . "\n" .
  1674. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1675. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1676. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1677. " }\n" .
  1678. " network {\n" .
  1679. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1680. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1681. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1682. " }\n" .
  1683. " }\n" .
  1684. "}";
  1685. }
  1686. /**
  1687. * Create the given directory, give its property to the www-data group and
  1688. * record it as a newly created dir (for an eventual rollback)
  1689. *
  1690. * @param string $dirPath
  1691. */
  1692. private function mkDir(string $dirPath) {
  1693. mkdir($dirPath);
  1694. $this->createdDirs[] = $dirPath;
  1695. chgrp($dirPath, 'www-data');
  1696. }
  1697. /**
  1698. * Write the given file with content, give its property to the www-data group and
  1699. * record it as a newly created file (for an eventual rollback)
  1700. *
  1701. * @param string $path
  1702. * @param string $content
  1703. */
  1704. private function writeFile(string $path, string $content) {
  1705. $f = fopen($path, "w");
  1706. try
  1707. {
  1708. fwrite($f, $content);
  1709. $this->createdFiles[] = $path;
  1710. chgrp($path, 'www-data');
  1711. } finally {
  1712. fclose($f);
  1713. }
  1714. }
  1715. /**
  1716. * Try to find the config file of the website in the less resource-consuming way
  1717. * and parse it.
  1718. *
  1719. * @param int $rootUid
  1720. * @return array Path of the configuration file and parsed configuration of the website
  1721. */
  1722. protected function findConfigFileAndContentFor(int $rootUid): array
  1723. {
  1724. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1725. $candidates = array_filter(
  1726. scandir($configs_directory),
  1727. function ($x) { return $x != '.' && $x != '..'; }
  1728. );
  1729. // try to filter by directory name
  1730. foreach ($candidates as $subdir) {
  1731. if (preg_match('/\.*_' . $rootUid . '$/', $subdir)) {
  1732. $filename = $configs_directory . $subdir . '/config.yaml';
  1733. $yamlConfig = Yaml::parseFile($filename);
  1734. if ($yamlConfig['rootPageId'] === $rootUid) {
  1735. return [$filename, $yamlConfig];
  1736. }
  1737. }
  1738. }
  1739. // it wasn't found the easy way, let's look to each file... :(
  1740. foreach ($candidates as $subdir) {
  1741. $filename = $configs_directory . $subdir . '/config.yaml';
  1742. $yamlConfig = Yaml::parseFile($filename);
  1743. if ($yamlConfig['rootPageId'] === $rootUid) {
  1744. return [$filename, $yamlConfig];
  1745. }
  1746. }
  1747. return [null, []];
  1748. }
  1749. /**
  1750. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1751. * @param int $rootUid
  1752. * @return array Configuration of the website
  1753. */
  1754. protected function findConfigFor(int $rootUid): array
  1755. {
  1756. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1757. return $pathAndConfig[1];
  1758. }
  1759. /**
  1760. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1761. * @param int $rootUid
  1762. * @return string Path of the config file of the given website
  1763. */
  1764. protected function findConfigFilePathFor(int $rootUid): string
  1765. {
  1766. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1767. return $pathAndConfig[0];
  1768. }
  1769. /**
  1770. * Create or update the .../sites/.../config.yaml file of the given site
  1771. *
  1772. * @param int $organizationId
  1773. * @param int $rootUid
  1774. * @param string $domain
  1775. * @param bool $forceRecreate
  1776. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1777. */
  1778. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false): string
  1779. {
  1780. $existing = $this->findConfigFileAndContentFor($rootUid);
  1781. $configFilename = $existing[0];
  1782. $config = $existing[1];
  1783. $subdomain = explode('.', $domain)[0];
  1784. if (!$configFilename) {
  1785. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1786. $configFilename = $configDir . "/config.yaml";
  1787. $isNew = true;
  1788. if (file_exists($configFilename)) {
  1789. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1790. }
  1791. } else {
  1792. $configDir = dirname($configFilename);
  1793. $config['base'] = 'https://' . $domain;
  1794. $isNew = false;
  1795. }
  1796. if ($isNew || $forceRecreate) {
  1797. $config = ['base' => 'https://' . $domain,
  1798. 'baseVariants' => [
  1799. ['base' => $subdomain . '/',
  1800. 'condition' => 'applicationContext == "Development"']
  1801. ],
  1802. 'errorHandling' => [
  1803. ['errorCode' => '404',
  1804. 'errorHandler' => 'PHP',
  1805. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1806. ['errorCode' => '403',
  1807. 'errorHandler' => 'PHP',
  1808. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1809. ],
  1810. 'flux_content_types' => '',
  1811. 'flux_page_templates' => '',
  1812. 'languages' => [[
  1813. 'title' => 'Fr',
  1814. 'enabled' => True,
  1815. 'base' => '/',
  1816. 'typo3Language' => 'fr',
  1817. 'locale' => 'fr_FR',
  1818. 'iso-639-1' => 'fr',
  1819. 'navigationTitle' => 'Fr',
  1820. 'hreflang' => 'fr-FR',
  1821. 'direction' => 'ltr',
  1822. 'flag' => 'fr',
  1823. 'languageId' => '0',
  1824. ]],
  1825. 'rootPageId' => $rootUid,
  1826. 'routes' => []
  1827. ];
  1828. }
  1829. $yamlConfig = Yaml::dump($config, 99, 2);
  1830. if (!file_exists($configDir)) {
  1831. $this->mkDir($configDir);
  1832. }
  1833. $this->writeFile($configFilename, $yamlConfig);
  1834. // Set the owner and mods, in case www-data is not the one who run this command
  1835. // @see https://www.php.net/manual/fr/function.stat.php
  1836. try {
  1837. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1838. chown($configFilename, $stats['4']);
  1839. chgrp($configFilename, $stats['5']);
  1840. chmod($configFilename, $stats['2']);
  1841. } catch (\Exception $e) {
  1842. }
  1843. // Flush cache:
  1844. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1845. $cacheSystem->remove('site-configuration');
  1846. $cacheSystem->remove('pseudo-sites');
  1847. return $configFilename;
  1848. }
  1849. /**
  1850. * Create the BE user for the website, then return its uid
  1851. * The user shall be already created in the Opentalent DB
  1852. * This is a minimal creation, that shall be completed by the ot_connect ext
  1853. *
  1854. * @param int $organizationId
  1855. * @param int $rootUid
  1856. * @param int $siteGroupUid
  1857. * @param array $userData
  1858. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  1859. * @return int The uid of the created be_user
  1860. */
  1861. private function createOrUpdateBeUser(int $organizationId,
  1862. int $rootUid,
  1863. int $siteGroupUid,
  1864. array $userData,
  1865. int $updateUid = null): int
  1866. {
  1867. if (!isset($userData['username'])) {
  1868. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1869. }
  1870. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1871. $randomStr = (new Random)->generateRandomHexString(20);
  1872. $adminGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  1873. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  1874. $values = [
  1875. 'username' => $userData['username'],
  1876. 'password' => $randomStr,
  1877. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  1878. 'deleted' => 0,
  1879. 'lang' => 'fr',
  1880. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  1881. 'userMods' => '', // inherited from the base AdminGroup
  1882. 'db_mountpoints' => $rootUid,
  1883. 'options' => 2,
  1884. 'tx_opentalent_opentalentId' => $userData['id'],
  1885. 'tx_opentalent_organizationId' => $organizationId,
  1886. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1887. ];
  1888. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1889. if ($updateUid != null) {
  1890. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  1891. foreach ($values as $k => $v) {
  1892. $q->set($k, $v);
  1893. }
  1894. $q->execute();
  1895. return $updateUid;
  1896. } else {
  1897. $queryBuilder->insert('be_users')
  1898. ->values($values)
  1899. ->execute();
  1900. return (int)$queryBuilder->getConnection()->lastInsertId();
  1901. }
  1902. }
  1903. /**
  1904. * Create the BE editors group for the website, then return its uid
  1905. *
  1906. * @param int $organizationId
  1907. * @param int $rootUid
  1908. * @param array $userData
  1909. * @param int|null $updateUid If passed, this method will update this be group instead of creating a new one
  1910. * @return int The uid of the created be_group
  1911. */
  1912. private function createOrUpdateBeGroup(int $organizationId,
  1913. int $rootUid,
  1914. array $userData,
  1915. int $updateUid = null): int
  1916. {
  1917. $groupName = 'editors_' . $organizationId;
  1918. // get the existing filemounts
  1919. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1920. $queryBuilder
  1921. ->select('uid')
  1922. ->from('sys_filemounts')
  1923. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1924. $statement = $queryBuilder->execute();
  1925. $rows = $statement->fetchAll(3) ?: [];
  1926. $files = [];
  1927. foreach ($rows as $row) {
  1928. $files[] = $row[0];
  1929. }
  1930. $mainGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  1931. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  1932. $values = [
  1933. 'title' => $groupName,
  1934. 'deleted' => 0,
  1935. 'subgroup' => $mainGroupUid,
  1936. 'db_mountpoints' => $rootUid,
  1937. 'file_mountPoints' => join(',', $files),
  1938. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1939. 'groupMods' => '', // inherited from the base EditorsGroup
  1940. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  1941. 'tables_select' => '', // inherited from the base EditorsGroup
  1942. 'tables_modify' => '', // inherited from the base EditorsGroup
  1943. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  1944. ];
  1945. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1946. if ($updateUid !== null) {
  1947. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  1948. foreach ($values as $k => $v) {
  1949. $q->set($k, $v);
  1950. }
  1951. $q->execute();
  1952. return $updateUid;
  1953. } else {
  1954. $queryBuilder->insert('be_groups')
  1955. ->values($values)
  1956. ->execute();
  1957. return $queryBuilder->getConnection()->lastInsertId();
  1958. }
  1959. }
  1960. /**
  1961. * Try to find and return the uid of the editors be_group
  1962. * for this website
  1963. *
  1964. * @param int $rootUid
  1965. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  1966. * @return int
  1967. * @throws NoSuchRecordException
  1968. */
  1969. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  1970. $editorsGroups = [
  1971. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  1972. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  1973. ];
  1974. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1975. if (!$withRestrictions) {
  1976. $queryBuilder->getRestrictions()->removeAll();
  1977. }
  1978. $beGroups = $queryBuilder
  1979. ->select('uid', 'subgroup')
  1980. ->from('be_groups')
  1981. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  1982. ->execute()
  1983. ->fetchAll();
  1984. $editorsGroupUid = null;
  1985. foreach ($beGroups as $beGroup) {
  1986. // the editor group shall be a subgroup of one of the Editors group, and have this website mounted
  1987. if (in_array($beGroup['subgroup'], $editorsGroups)) {
  1988. $editorsGroupUid = $beGroup['uid'];
  1989. }
  1990. }
  1991. if ($editorsGroupUid == null) {
  1992. throw new NoSuchRecordException("No editors be_group found " .
  1993. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  1994. }
  1995. return $editorsGroupUid;
  1996. }
  1997. /**
  1998. * Try to find and return the uid of the admin be_user
  1999. * for this website
  2000. *
  2001. * @param int $rootUid
  2002. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2003. * @return int
  2004. * @throws NoSuchRecordException
  2005. * @throws NoSuchWebsiteException
  2006. */
  2007. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2008. $adminGroups = [
  2009. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2010. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2011. ];
  2012. $adminUid = null;
  2013. try {
  2014. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2015. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2016. if (!$withRestrictions) {
  2017. $queryBuilder->getRestrictions()->removeAll();
  2018. }
  2019. $beUsers = $queryBuilder
  2020. ->select('uid', 'usergroup')
  2021. ->from('be_users')
  2022. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2023. ->execute()
  2024. ->fetchAll();
  2025. foreach ($beUsers as $beUser) {
  2026. // the admin shall be both in the website editors group and in the Admin group
  2027. $isAdmin = false;
  2028. $isInThisWebsiteGroup = false;
  2029. foreach (explode(',', $beUser['usergroup']) as $group) {
  2030. if (in_array($group, $adminGroups)) {
  2031. $isAdmin = true;
  2032. }
  2033. if ($group == $editorsGroupUid) {
  2034. $isInThisWebsiteGroup = true;
  2035. }
  2036. }
  2037. if ($isAdmin && $isInThisWebsiteGroup) {
  2038. $adminUid = $beUser['uid'];
  2039. }
  2040. }
  2041. } catch (NoSuchRecordException $e) {
  2042. // the editors group does not exist
  2043. }
  2044. // Try to find if there is a be_user who still is in the v8.7 architecture
  2045. if ($adminUid == null) {
  2046. $organizationId = $this->findOrganizationIdUidFor($rootUid);
  2047. $extraData = $this->fetchOrganizationExtraData($organizationId);
  2048. $expectedUsername = $extraData['admin']['username'];
  2049. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2050. if (!$withRestrictions) {
  2051. $queryBuilder->getRestrictions()->removeAll();
  2052. }
  2053. $row = $queryBuilder
  2054. ->select('uid', 'db_mountpoints')
  2055. ->from('be_users')
  2056. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2057. ->execute()
  2058. ->fetch();
  2059. if ($row['uid']) {
  2060. if ((string)$rootUid != (string)$row['db_mountpoints']) {
  2061. throw new \RuntimeException("The be_user named '" . $expectedUsername . "' has unexpected mounted website(s)");
  2062. }
  2063. $adminUid = $row['uid'];
  2064. }
  2065. }
  2066. if ($adminUid == null) {
  2067. throw new NoSuchRecordException("No admin be_user found " .
  2068. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2069. }
  2070. return $adminUid;
  2071. }
  2072. /**
  2073. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2074. *
  2075. * @param int $groupType
  2076. * @return int
  2077. */
  2078. protected function getBaseBeGroupUid(int $groupType): int
  2079. {
  2080. $expectedName = self::BEGROUP_NAME[$groupType];
  2081. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2082. $uid = $queryBuilder
  2083. ->select('uid')
  2084. ->from('be_groups')
  2085. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2086. ->execute()
  2087. ->fetchColumn(0);
  2088. if (!$uid) {
  2089. throw new \RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2090. }
  2091. return $uid;
  2092. }
  2093. /**
  2094. * Enable frontend editing for user
  2095. *
  2096. * @param int $adminUid
  2097. */
  2098. private function enableFeEditing(int $adminUid) {
  2099. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  2100. $user = $BE_USER->getRawUserByUid($adminUid);
  2101. $BE_USER->user = $user;
  2102. $BE_USER->backendSetUC();
  2103. $BE_USER->uc['frontend_editing'] = 1;
  2104. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2105. $BE_USER->writeUC($BE_USER->uc);
  2106. }
  2107. }