SiteController.php 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  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. try {
  626. $adminBeUserUid = $this->findAdminBeUserUid($rootUid);
  627. if ($adminBeUserUid !== null) {
  628. $this->delete('be_users', 'uid', $adminBeUserUid, $hard);
  629. }
  630. } catch (NoSuchRecordException $e) {}
  631. try {
  632. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  633. if ($editorsGroupUid !== null) {
  634. $this->delete('be_groups', 'uid', $editorsGroupUid, $hard);
  635. }
  636. } catch (NoSuchRecordException $e) {}
  637. // Look up for the config.yaml file of the website
  638. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  639. $configYamlFile = "";
  640. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  641. if (!$isDeleted) {
  642. $yamlFile = $subdir . '/config.yaml';
  643. } else {
  644. $yamlFile = $subdir . '/config.yaml.deleted';
  645. }
  646. if (is_file($yamlFile)) {
  647. $conf = Yaml::parseFile($yamlFile);
  648. if ($conf['rootPageId'] == $rootUid) {
  649. $configYamlFile = $yamlFile;
  650. break;
  651. }
  652. }
  653. }
  654. if (!$isDeleted) {
  655. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  656. } else {
  657. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  658. }
  659. // If hard deletion, verify that upload dirs are empty
  660. if ($hard && is_dir($uploadDir)) {
  661. foreach (scandir($uploadDir) as $subdir) {
  662. if ($subdir == '.' or $subdir == '..') {
  663. continue;
  664. }
  665. $subdir = $uploadDir . $subdir;
  666. if (!is_dir($subdir)) {
  667. throw new \RuntimeException(
  668. 'The directory ' . $uploadDir . ' contains non-directory files' .
  669. ', this humble script prefers not to take care of them automatically. Abort.');
  670. }
  671. if (is_readable($subdir)) {
  672. foreach (scandir($subdir) as $filename) {
  673. if ($filename != '.' && $filename != '..') {
  674. throw new \RuntimeException(
  675. 'The directory ' . $subdir . ' is not empty, ' .
  676. 'this humble script prefers not to take care of them automatically. Abort.');
  677. }
  678. }
  679. }
  680. }
  681. }
  682. // If soft deletion, check that no deleted file or directory exist
  683. if (!$hard) {
  684. $toRename = [];
  685. if (!$hard) {
  686. if (is_file($configYamlFile)) {
  687. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  688. }
  689. if (is_dir($uploadDir)) {
  690. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  691. }
  692. }
  693. foreach ($toRename as $initialPath => $newPath) {
  694. if (is_file($newPath)) {
  695. throw new \RuntimeException(
  696. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  697. }
  698. }
  699. }
  700. // Delete or rename files and dirs
  701. if ($hard) {
  702. if (is_file($configYamlFile)) {
  703. unlink($configYamlFile);
  704. }
  705. if (is_dir(dirname($configYamlFile))) {
  706. rmdir(dirname($configYamlFile));
  707. }
  708. if (is_dir($uploadDir . 'images')) {
  709. rmdir($uploadDir . 'images');
  710. }
  711. if (is_dir($uploadDir . 'Forms')) {
  712. rmdir($uploadDir . 'Forms');
  713. }
  714. if (is_dir($uploadDir)) {
  715. rmdir($uploadDir);
  716. }
  717. } else {
  718. $renamed = [];
  719. foreach ($toRename as $initialPath => $newPath) {
  720. rename($initialPath, $newPath);
  721. $renamed[$initialPath] = $newPath;
  722. }
  723. }
  724. // Add the redirection
  725. if ($redirectTo) {
  726. $this->addRedirection($originUrl, $targetUrl);
  727. }
  728. // Try to commit the result
  729. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  730. if (!$commitSuccess) {
  731. throw new \RuntimeException('Something went wrong while commiting the result');
  732. }
  733. return $rootUid;
  734. } catch(\Throwable $e) {
  735. // rollback
  736. $this->connectionPool->getConnectionByName('Default')->rollback();
  737. if (!$hard) {
  738. foreach ($renamed as $initialPath => $newPath) {
  739. rename($newPath, $initialPath);
  740. }
  741. }
  742. throw $e;
  743. } finally {
  744. if (file_exists($confirm_file)) {
  745. unlink($confirm_file);
  746. }
  747. }
  748. }
  749. /**
  750. * Delete a record from the typo3 db.
  751. * If $hard is true, the record is permanently deleted.
  752. * Else, it's just marked as deleted.
  753. *
  754. * @param string $table
  755. * @param string $whereKey
  756. * @param $whereValue
  757. * @param int $hard
  758. */
  759. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  760. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  761. if (!$hard) {
  762. $queryBuilder
  763. ->update($table)
  764. ->set('deleted', 1)
  765. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  766. ->execute();
  767. } else {
  768. $queryBuilder
  769. ->delete($table)
  770. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  771. ->execute();
  772. }
  773. }
  774. /**
  775. * Undo a soft-deletion performed using deleteSiteAction()
  776. *
  777. * @param int $organizationId
  778. * @return int
  779. * @throws NoSuchWebsiteException
  780. * @throws \Doctrine\DBAL\ConnectionException
  781. * @throws \Doctrine\DBAL\DBALException
  782. */
  783. public function undeleteSiteAction(int $organizationId) {
  784. $rootUid = $this->findRootUidFor($organizationId);
  785. // start transactions
  786. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  787. // keep track of renamed file for an eventual rollback
  788. $renamed = [];
  789. try {
  790. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  791. foreach($pages as $page) {
  792. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  793. $queryBuilder
  794. ->update('tt_content')
  795. ->set('deleted', 0)
  796. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  797. ->execute();
  798. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  799. $queryBuilder
  800. ->update('pages')
  801. ->set('deleted', 0)
  802. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  803. ->execute();
  804. }
  805. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  806. $queryBuilder
  807. ->update('tt_content')
  808. ->set('deleted', 0)
  809. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  810. ->execute();
  811. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  812. $queryBuilder
  813. ->update('pages')
  814. ->set('deleted', 0)
  815. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  816. ->execute();
  817. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  818. $queryBuilder
  819. ->update('sys_template')
  820. ->set('deleted', 0)
  821. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  822. ->execute();
  823. // remove filemounts
  824. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  825. $queryBuilder
  826. ->update('sys_filemounts')
  827. ->set('deleted', 0)
  828. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  829. ->execute();
  830. $queryBuilder
  831. ->update('sys_filemounts')
  832. ->set('deleted', 0)
  833. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  834. ->execute();
  835. try {
  836. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid, false);
  837. if ($editorsGroupUid !== null) {
  838. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  839. $queryBuilder
  840. ->update('be_groups')
  841. ->set('deleted', 0)
  842. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  843. ->execute();
  844. }
  845. } catch (NoSuchRecordException $e) {}
  846. try {
  847. $adminBeUserUid = $this->findAdminBeUserUid($rootUid, false);
  848. if ($adminBeUserUid !== null) {
  849. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  850. $queryBuilder
  851. ->update('be_users')
  852. ->set('deleted', 0)
  853. ->where($queryBuilder->expr()->eq('uid', $adminBeUserUid))
  854. ->execute();
  855. }
  856. } catch (NoSuchRecordException $e) {}
  857. // Look up for the config.yaml file of the website
  858. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  859. $configYamlFile = "";
  860. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  861. $yamlFile = $subdir . '/config.yaml.deleted';
  862. if (is_file($yamlFile)) {
  863. $conf = Yaml::parseFile($yamlFile);
  864. if ($conf['rootPageId'] == $rootUid) {
  865. $configYamlFile = $yamlFile;
  866. break;
  867. }
  868. }
  869. }
  870. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  871. $toRename = [];
  872. if (is_file($configYamlFile)) {
  873. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  874. }
  875. if (is_dir($uploadDir)) {
  876. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  877. }
  878. foreach ($toRename as $initialPath => $newPath) {
  879. if (is_file($newPath)) {
  880. throw new \RuntimeException(
  881. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  882. }
  883. }
  884. $renamed = [];
  885. foreach ($toRename as $initialPath => $newPath) {
  886. rename($initialPath, $newPath);
  887. $renamed[$initialPath] = $newPath;
  888. }
  889. // remove eventual redirection from this site to another
  890. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  891. $this->removeRedirectionsFrom($originUrl);
  892. // Try to commit the result
  893. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  894. if (!$commitSuccess) {
  895. throw new \RuntimeException('Something went wrong while commiting the result');
  896. }
  897. return $rootUid;
  898. } catch(\Throwable $e) {
  899. // rollback
  900. $this->connectionPool->getConnectionByName('Default')->rollback();
  901. foreach ($renamed as $initialPath => $newPath) {
  902. rename($newPath, $initialPath);
  903. }
  904. throw $e;
  905. }
  906. }
  907. /**
  908. * Clear the cache of the organization's website
  909. *
  910. * @param int $organizationId the organization's id whom site cache should be cleared
  911. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  912. * @return int
  913. * @throws NoSuchWebsiteException
  914. */
  915. public function clearSiteCacheAction(int $organizationId, $clearAll=false): int
  916. {
  917. $rootUid = $this->findRootUidFor($organizationId);
  918. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  919. return $rootUid;
  920. }
  921. /**
  922. * Perform a full scan of the website and returns a list of warnings
  923. *
  924. * @param int $organizationId
  925. * @param int $rootUid
  926. * @return array
  927. */
  928. private function scanSite(int $organizationId, int $rootUid) {
  929. $warnings = [];
  930. // fetch pages and root page
  931. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  932. $rootPage = null;
  933. $pageIndex = [];
  934. foreach ($pages as $page) {
  935. $pageIndex[$page['uid']] = $page;
  936. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  937. }
  938. // fetch organization and extradata
  939. $organization = $this->fetchOrganization($organizationId);
  940. $extraData = $this->fetchOrganizationExtraData($organizationId);
  941. // load site's settings (uncomment if needed)
  942. // $config = $this->findConfigFor($rootUid);
  943. // Check site's title
  944. if (trim($rootPage['title']) != trim($organization->getName())) {
  945. $warnings[] = "Site's title does not match the organization name";
  946. }
  947. // Who is the expected owner among the be_users? there should be only one.
  948. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  949. $queryBuilder->getRestrictions()->removeAll();
  950. $beUsers = $queryBuilder
  951. ->select('uid', 'username')
  952. ->from('be_users')
  953. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  954. ->execute()
  955. ->fetchAll();
  956. $owner = null;
  957. if (count($beUsers) > 1) {
  958. $warnings[] = 'Website is mounted on more than one be_user: ' .
  959. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  960. } elseif (count($beUsers) == 0) {
  961. $warnings[] = 'Website is not mounted on any be_user';
  962. } else {
  963. $owner = $beUsers[0];
  964. }
  965. // are template constants up to date?
  966. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  967. $actual_constants = $queryBuilder
  968. ->select('constants')
  969. ->from('sys_template')
  970. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  971. ->execute()
  972. ->fetchColumn(0);
  973. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  974. $norm = function ($s) {
  975. return strtolower(preg_replace('/\s/', '', $s));
  976. };
  977. if ($norm($expected_constants) != $norm($actual_constants)) {
  978. $warnings[] = 'Template constants need an update';
  979. }
  980. $expected_templates = [
  981. "OpenTalent.OtTemplating->home" => 0,
  982. "OpenTalent.OtTemplating->legal" => 0,
  983. "OpenTalent.OtTemplating->contact" => 0
  984. ];
  985. foreach ($pages as $page) {
  986. if ($page['deleted']) {
  987. continue;
  988. }
  989. // Is it the correct owner?
  990. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  991. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  992. }
  993. if (!$page['is_siteroot']) {
  994. // is the parent page state (deleted, hidden, restricted) the same as this page?
  995. $parent = $pageIndex[$page['pid']];
  996. if ($parent['deleted']) {
  997. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  998. }
  999. if ($parent['hidden'] && !$page['hidden']) {
  1000. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  1001. }
  1002. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  1003. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  1004. }
  1005. }
  1006. // an expected template was found, remove it from the list of expected
  1007. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  1008. !$page['deleted'] && !$page['hidden']) {
  1009. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  1010. }
  1011. }
  1012. foreach ($expected_templates as $template => $_) {
  1013. $warnings[] = 'No page with template ' . $template;
  1014. }
  1015. return $warnings;
  1016. }
  1017. /**
  1018. * Get the current status and informations of the organization's website
  1019. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  1020. *
  1021. * The status is among:
  1022. *
  1023. * - STATUS_NO_SUCH_WEBSITE
  1024. * - STATUS_EXISTING
  1025. * - STATUS_EXISTING_DELETED
  1026. * - STATUS_EXISTING_HIDDEN
  1027. * - STATUS_EXISTING_WITH_WARNINGS
  1028. *
  1029. * @param int $organizationId the organization's id whom site cache should be cleared
  1030. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1031. * the website pages will be performed.
  1032. * @return SiteStatus
  1033. */
  1034. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  1035. {
  1036. try {
  1037. $siteInfos = $this->getSiteInfosAction($organizationId);
  1038. } catch (NoSuchWebsiteException $e) {
  1039. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  1040. }
  1041. if ($siteInfos->isDeleted()) {
  1042. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  1043. }
  1044. if ($siteInfos->isHiddenOrRestricted()) {
  1045. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  1046. }
  1047. $warnings = null;
  1048. if ($fullScan) {
  1049. // ** Look for potential issues
  1050. $warnings = $this->scanSite($organizationId, $siteInfos->getRootUid());
  1051. }
  1052. return new SiteStatus(
  1053. $organizationId,
  1054. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  1055. $siteInfos,
  1056. $warnings
  1057. );
  1058. }
  1059. /**
  1060. * Set a new domain for the website.
  1061. * If $redirect is true, also add a redirection from the former domain to the new one
  1062. *
  1063. * @param int $organizationId
  1064. * @param string $newDomain
  1065. * @param bool $redirect
  1066. * @return int
  1067. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1068. * @throws NoSuchWebsiteException
  1069. */
  1070. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1071. {
  1072. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1073. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1074. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1075. }
  1076. $infos = $this->getSiteInfosAction($organizationId);
  1077. $originUrl = $infos->getBaseUrl();
  1078. $rootUid = $infos->getRootUid();
  1079. if (preg_replace('/https?:\/\//', '', $originUrl) == preg_replace('/https?:\/\//', '', $newDomain) ) {
  1080. throw new \RuntimeException('The new domain should be different of the current one');
  1081. }
  1082. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1083. if ($redirect) {
  1084. // Add the redirection
  1085. $this->addRedirection($originUrl, $newDomain);
  1086. }
  1087. return $rootUid;
  1088. }
  1089. /**
  1090. * Return all of the redirections from the given domain name,
  1091. * even if they have been marked as deleted.
  1092. *
  1093. * @param $domain string Domain name, without the http(s):// part
  1094. * @return array Rows from the sys_redirect table
  1095. */
  1096. protected function getRedirectionsFrom(string $domain): array
  1097. {
  1098. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1099. $queryBuilder->getRestrictions()->removeAll();
  1100. return $queryBuilder
  1101. ->select('*')
  1102. ->from('sys_redirect')
  1103. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1104. ->execute()
  1105. ->fetchAll();
  1106. }
  1107. /**
  1108. * Return all of the redirections to the given domain name,
  1109. * even if they have been marked as deleted.
  1110. *
  1111. * @param $domain string Domain name, without the http(s):// part
  1112. * @return array Rows from the sys_redirect table
  1113. */
  1114. protected function getRedirectionsTo(string $domain): array
  1115. {
  1116. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1117. $queryBuilder->getRestrictions()->removeAll();
  1118. return $queryBuilder
  1119. ->select('*')
  1120. ->from('sys_redirect')
  1121. ->where(
  1122. $queryBuilder->expr()->in(
  1123. 'target',
  1124. [
  1125. 'http://' . $queryBuilder->expr()->literal($domain),
  1126. 'https://' . $queryBuilder->expr()->literal($domain)
  1127. ]
  1128. )
  1129. )
  1130. ->execute()
  1131. ->fetchAll();
  1132. }
  1133. /**
  1134. * Add a new redirection from $fromDomain to $toDomain.
  1135. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1136. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1137. *
  1138. * @param $fromDomain
  1139. * @param $toDomain
  1140. * @return int Status of the operation
  1141. */
  1142. public function addRedirection($fromDomain, $toDomain): int
  1143. {
  1144. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1145. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1146. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1147. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1148. }
  1149. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1150. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1151. }
  1152. $existing = $this->getRedirectionsFrom($fromDomain);
  1153. $toUpdate = null;
  1154. foreach ($existing as $redirection) {
  1155. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1156. // a redirection from this domain already exists, and it is not deleted nor disabled
  1157. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1158. // the target is not the same domain
  1159. throw new \RuntimeException(
  1160. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1161. );
  1162. } else {
  1163. // else, target is already the same domain, it will be updated
  1164. $toUpdate = $redirection;
  1165. break;
  1166. }
  1167. } else {
  1168. // a redirection from this domain already exists, but it is deleted or disabled
  1169. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1170. // the target is the same domain, we'll reactivate this record
  1171. $toUpdate = $redirection;
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1177. $data = [
  1178. 'deleted' => 0,
  1179. 'disabled' => 0,
  1180. 'source_host' => $fromDomain,
  1181. 'source_path' => '/.*/',
  1182. 'is_regexp' => 1,
  1183. 'force_https' => 0,
  1184. 'respect_query_parameters' => 0,
  1185. 'keep_query_parameters' => 1,
  1186. 'target' => 'https://' . $toDomain,
  1187. 'target_statuscode' => 301
  1188. ];
  1189. if ($toUpdate !== null) {
  1190. $q = $queryBuilder
  1191. ->update('sys_redirect')
  1192. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1193. foreach ($data as $k => $v) {
  1194. $q->set($k, $v);
  1195. }
  1196. $q->execute();
  1197. return self::REDIRECTION_UPDATED;
  1198. } else {
  1199. $queryBuilder
  1200. ->insert('sys_redirect')
  1201. ->values($data)
  1202. ->execute();
  1203. return self::REDIRECTION_CREATED;
  1204. }
  1205. }
  1206. /**
  1207. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1208. * If $hard is true, delete it completely.
  1209. *
  1210. * @param $fromDomain
  1211. * @param bool $hard
  1212. * @return int Number of affected rows
  1213. */
  1214. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1215. {
  1216. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1217. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1218. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1219. }
  1220. $existing = $this->getRedirectionsFrom($fromDomain);
  1221. $deleted = 0;
  1222. foreach ($existing as $redirection) {
  1223. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1224. $deleted += 1;
  1225. }
  1226. return $deleted;
  1227. }
  1228. /**
  1229. * Set the rights of admin and editors of the website
  1230. * on all of the existing pages, including deleted ones
  1231. *
  1232. * @param int $organizationId
  1233. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1234. * @param int|null $editorsGroupUid Force the editors be-group uid
  1235. * @param int|null $adminUid Force the admin be-user uid
  1236. * @return int The uid of the website root page
  1237. * @throws NoSuchWebsiteException
  1238. * @throws NoSuchRecordException
  1239. */
  1240. protected function setBeUserPerms(
  1241. int $organizationId,
  1242. bool $createIfMissing = false,
  1243. int $editorsGroupUid = null,
  1244. int $adminUid = null
  1245. ): int
  1246. {
  1247. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1248. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1249. "and force the admin or group uid at the same time.");
  1250. }
  1251. $rootUid = $this->findRootUidFor($organizationId);
  1252. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1253. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']];
  1254. if ($editorsGroupUid == null) {
  1255. try {
  1256. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1257. } catch (NoSuchRecordException $e) {
  1258. if (!$createIfMissing) {
  1259. throw $e;
  1260. }
  1261. }
  1262. }
  1263. if ($adminUid == null) {
  1264. try {
  1265. $adminUid = $this->findAdminBeUserUid($rootUid);
  1266. } catch (NoSuchRecordException $e) {
  1267. if (!$createIfMissing) {
  1268. throw $e;
  1269. }
  1270. }
  1271. }
  1272. // Creates or update the admin be_group
  1273. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1274. $organizationId,
  1275. $rootUid,
  1276. $organizationExtraData['admin'],
  1277. $editorsGroupUid
  1278. );
  1279. // Creates or update the admin be_user
  1280. $adminUid = $this->createOrUpdateBeUser(
  1281. $organizationId,
  1282. $rootUid,
  1283. $editorsGroupUid,
  1284. $organizationExtraData['admin'],
  1285. $adminUid
  1286. );
  1287. // Reset the appartenance to groups
  1288. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1289. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1290. $queryBuilder
  1291. ->update('be_users')
  1292. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1293. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1294. ->execute();
  1295. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1296. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1297. $queryBuilder
  1298. ->update('be_groups')
  1299. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1300. ->set('subgroup', $mainEditorGroupUid)
  1301. ->execute();
  1302. // setup default owner for the website
  1303. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1304. $tsConfig = $queryBuilder->select('TSconfig')
  1305. ->from('pages')
  1306. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1307. ->execute()
  1308. ->fetchColumn(0);
  1309. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1310. $tsConfig .= "\nTCEMAIN {\n" .
  1311. " permissions.userid = " . $adminUid ."\n" .
  1312. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1313. "}";
  1314. $queryBuilder
  1315. ->update('pages')
  1316. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1317. ->set('TSconfig', $tsConfig)
  1318. ->execute();
  1319. // fetch pages and root page
  1320. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  1321. // To understand how the rights levels are computed:
  1322. // @see https://ressources.opentalent.fr/display/EX/Droits+des+BE+Users
  1323. foreach ($pages as $page) {
  1324. if ($page['is_siteroot']) {
  1325. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1326. if ($isPremium) {
  1327. $adminPerms += self::PERM_NEW;
  1328. }
  1329. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT;
  1330. } else if (
  1331. $page['slug'] == '/footer' ||
  1332. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->legal' ||
  1333. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->contact' ||
  1334. $page['slug'] == '/plan-du-site'
  1335. ) {
  1336. $adminPerms = self::PERM_SHOW;
  1337. if ($isPremium) {
  1338. $adminPerms += self::PERM_NEW;
  1339. }
  1340. $editorsPerms = self::PERM_SHOW;
  1341. } else if (
  1342. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->members' ||
  1343. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->membersCa' ||
  1344. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structures' ||
  1345. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->events' ||
  1346. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structuresEvents'
  1347. ) {
  1348. $adminPerms = self::PERM_SHOW;
  1349. if ($isPremium) {
  1350. $adminPerms += self::PERM_NEW + self::PERM_EDIT_PAGE;
  1351. }
  1352. $editorsPerms = self::PERM_SHOW;
  1353. } else {
  1354. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1355. if ($isPremium) {
  1356. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1357. }
  1358. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1359. if ($isPremium) {
  1360. $editorsPerms += self::PERM_NEW;
  1361. }
  1362. }
  1363. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1364. $queryBuilder
  1365. ->update('pages')
  1366. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1367. ->set('perms_userid', $adminUid)
  1368. ->set('perms_groupid', $editorsGroupUid)
  1369. ->set('perms_user', $adminPerms)
  1370. ->set('perms_group', $editorsPerms)
  1371. ->set('perms_everybody', 0)
  1372. ->execute();
  1373. }
  1374. return $rootUid;
  1375. }
  1376. /**
  1377. * CLI action for resetting the rights of admin and editors of the website
  1378. * on all of the existing pages, including deleted ones
  1379. *
  1380. * @param int $organizationId
  1381. * @param bool $createIfMissing
  1382. * @return int
  1383. * @throws NoSuchRecordException
  1384. * @throws NoSuchWebsiteException
  1385. * @throws \Throwable
  1386. */
  1387. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1388. {
  1389. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1390. try {
  1391. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1392. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1393. if (!$commitSuccess) {
  1394. throw new \RuntimeException('Something went wrong while commiting the result');
  1395. }
  1396. return $rootUid;
  1397. }
  1398. catch (\Throwable $e) {
  1399. // rollback
  1400. $this->connectionPool->getConnectionByName('Default')->rollback();
  1401. throw $e;
  1402. }
  1403. }
  1404. /**
  1405. * Retrieve the Organization object from the repository and then,
  1406. * from the Opentalent API
  1407. *
  1408. * @param $organizationId
  1409. * @return Organization
  1410. */
  1411. private function fetchOrganization($organizationId): Organization
  1412. {
  1413. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1414. try {
  1415. return $organizationRepository->findById($organizationId);
  1416. } catch (ApiRequestException $e) {
  1417. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1418. }
  1419. }
  1420. /**
  1421. * Try to find the root page uid of the organization's website and return it.
  1422. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1423. *
  1424. * @param $organizationId
  1425. * @return int
  1426. * @throws NoSuchWebsiteException
  1427. */
  1428. private function findRootUidFor($organizationId): int
  1429. {
  1430. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1431. $queryBuilder->getRestrictions()->removeAll();
  1432. $rows = $queryBuilder
  1433. ->select('uid')
  1434. ->from('pages')
  1435. ->where('is_siteroot=1')
  1436. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1437. ->execute()
  1438. ->fetchAll();
  1439. if (count($rows) > 1) {
  1440. throw new \RuntimeException("More than one website match this organization id");
  1441. }
  1442. $rootUid = (int)$rows[0]['uid'];
  1443. if ($rootUid > 0) {
  1444. return $rootUid;
  1445. }
  1446. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1447. }
  1448. /**
  1449. * Try to find the id of the organization owning this website.
  1450. *
  1451. * @param $rootUid
  1452. * @return int
  1453. * @throws NoSuchWebsiteException
  1454. */
  1455. private function findOrganizationIdUidFor($rootUid): int
  1456. {
  1457. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1458. $queryBuilder->getRestrictions()->removeAll();
  1459. $organizationId = $queryBuilder
  1460. ->select('tx_opentalent_structure_id')
  1461. ->from('pages')
  1462. ->where('is_siteroot=1')
  1463. ->andWhere($queryBuilder->expr()->eq('uid', $rootUid))
  1464. ->execute()
  1465. ->fetchColumn(0);
  1466. if ($organizationId > 0) {
  1467. return $organizationId;
  1468. }
  1469. throw new NoSuchWebsiteException("No organization found for website " . $rootUid);
  1470. }
  1471. /**
  1472. * Determine which folder-type Typo3 page should contain the new website
  1473. * CREATES IT if needed, and return its uid
  1474. *
  1475. * @return int
  1476. */
  1477. private function getParentFolderUid(): int
  1478. {
  1479. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1480. $siteCount = $queryBuilder
  1481. ->count('uid')
  1482. ->from('pages')
  1483. ->where('is_siteroot=1')
  1484. ->execute()
  1485. ->fetchColumn(0);
  1486. $thousand = (int)(($siteCount + 1) / 1000);
  1487. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1488. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1489. $uid = $queryBuilder
  1490. ->select('uid')
  1491. ->from('pages')
  1492. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1493. ->andWhere('dokType=254')
  1494. ->execute()
  1495. ->fetchColumn(0);
  1496. if ($uid == null) {
  1497. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1498. $queryBuilder->insert('pages')
  1499. ->values([
  1500. 'pid' => 0,
  1501. 'title' => $folderName,
  1502. 'dokType' => 254,
  1503. 'sorting' => 11264,
  1504. 'perms_userid' => 1,
  1505. 'perms_groupid' => 31,
  1506. 'perms_group' => 27,
  1507. ])
  1508. ->execute();
  1509. $uid = $queryBuilder->getConnection()->lastInsertId();
  1510. }
  1511. return $uid;
  1512. }
  1513. /**
  1514. * Insert a new row in the 'pages' table of the Typo3 DB
  1515. * and return its uid
  1516. *
  1517. * @param Organization $organization
  1518. * @param int $pid
  1519. * @param string $title
  1520. * @param string $slug
  1521. * @param string $template
  1522. * @param array $moreValues
  1523. * @return int
  1524. */
  1525. private function insertPage(Organization $organization,
  1526. int $pid,
  1527. string $title,
  1528. string $slug,
  1529. string $template = '',
  1530. array $moreValues = []
  1531. ): int
  1532. {
  1533. $defaultValues = [
  1534. 'pid' => $pid,
  1535. 'perms_groupid' => 3,
  1536. 'perms_user' => 27,
  1537. 'cruser_id' => 1,
  1538. 'dokType' => self::DOK_PAGE,
  1539. 'title' => $title,
  1540. 'slug' => $slug,
  1541. 'backend_layout' => 'flux__grid',
  1542. 'backend_layout_next_level' => 'flux__grid',
  1543. 'tx_opentalent_structure_id' => $organization->getId()
  1544. ];
  1545. if ($template) {
  1546. $defaultValues['tx_fed_page_controller_action'] = $template;
  1547. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1548. }
  1549. $values = array_merge($defaultValues, $moreValues);
  1550. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1551. $queryBuilder->insert('pages')
  1552. ->values($values)
  1553. ->execute();
  1554. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1555. $this->createdPagesIndex[$slug] = $uid;
  1556. return $uid;
  1557. }
  1558. /**
  1559. * Insert the root page of a new organization's website
  1560. * and return its uid
  1561. *
  1562. * @param Organization $organization
  1563. * @return int
  1564. */
  1565. private function insertRootPage(Organization $organization): int
  1566. {
  1567. return $this->insertPage(
  1568. $organization,
  1569. $this->getParentFolderUid(),
  1570. $organization->getName(),
  1571. '/',
  1572. self::TEMPLATE_HOME,
  1573. [
  1574. 'is_siteroot' => 1,
  1575. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1576. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1577. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1578. ]
  1579. );
  1580. }
  1581. /**
  1582. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1583. *
  1584. * @param int $pid
  1585. * @param string $cType
  1586. * @param string $bodyText
  1587. * @param int $colPos
  1588. * @param array $moreValues
  1589. */
  1590. private function insertContent(int $pid,
  1591. string $cType=self::CTYPE_TEXT,
  1592. string $bodyText = '',
  1593. int $colPos=0,
  1594. array $moreValues = []) {
  1595. $defaultValues = [
  1596. 'pid' => $pid,
  1597. 'cruser_id' => 1,
  1598. 'CType' => $cType,
  1599. 'colPos' => $colPos,
  1600. 'bodyText' => $bodyText
  1601. ];
  1602. $values = array_merge($defaultValues, $moreValues);
  1603. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1604. $queryBuilder->insert('tt_content')
  1605. ->values($values)
  1606. ->execute();
  1607. }
  1608. private function fetchOrganizationExtraData(int $organizationId) {
  1609. $cnn = new PDO(
  1610. "mysql:host=prod-back;dbname=opentalent",
  1611. 'dbcloner',
  1612. 'wWZ4hYcrmHLW2mUK',
  1613. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1614. );
  1615. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1616. $stmt = $cnn->prepare(
  1617. "SELECT o.id, o.name, o.facebook, o.twitter,
  1618. o.category, o.logo_id, p.logoDonorsMove
  1619. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1620. ON o.parameters_id = p.id
  1621. WHERE o.id=" . $organizationId . ";"
  1622. );
  1623. $stmt->execute();
  1624. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1625. $data = $stmt->fetch();
  1626. $stmt = $cnn->prepare(
  1627. "SELECT c.email
  1628. FROM opentalent.ContactPoint c
  1629. INNER JOIN opentalent.organization_contactpoint o
  1630. ON o.contactPoint_id = c.id
  1631. WHERE c.contactType = 'PRINCIPAL'
  1632. AND o.organization_id = " . $organizationId . ";"
  1633. );
  1634. $stmt->execute();
  1635. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1636. $data['email'] = $stmt->fetch()['email'];
  1637. $stmt = $cnn->prepare(
  1638. "SELECT n.name, n.logo, n.url
  1639. FROM opentalent.Network n
  1640. INNER JOIN
  1641. (opentalent.NetworkOrganization l
  1642. INNER JOIN opentalent.Organization o
  1643. ON l.organization_id = o.id)
  1644. ON l.network_id = n.id
  1645. WHERE l.endDate is NULL
  1646. AND o.id=" . $organizationId . ";"
  1647. );
  1648. $stmt->execute();
  1649. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1650. $data['network'] = $stmt->fetch();
  1651. $stmt = $cnn->prepare(
  1652. "SELECT p.username, p.id as person_id, s.product
  1653. FROM opentalent.Person p
  1654. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1655. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1656. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1657. );
  1658. $stmt->execute();
  1659. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1660. $data['admin'] = $stmt->fetch();
  1661. return $data;
  1662. }
  1663. /**
  1664. * Return the content of `sys_template`.`constants` of
  1665. * the website of the given organization
  1666. *
  1667. * @param int $organizationId
  1668. * @param array $organizationExtraData
  1669. * @return string
  1670. */
  1671. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1672. {
  1673. return "plugin.tx_ottemplating {\n" .
  1674. " settings {\n" .
  1675. " organization {\n" .
  1676. " id = " . $organizationId . "\n" .
  1677. " name = " . $organizationExtraData['name'] . "\n" .
  1678. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1679. " email = " . $organizationExtraData['email'] . "\n" .
  1680. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1681. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1682. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1683. " }\n" .
  1684. " network {\n" .
  1685. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1686. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1687. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1688. " }\n" .
  1689. " }\n" .
  1690. "}";
  1691. }
  1692. /**
  1693. * Create the given directory, give its property to the www-data group and
  1694. * record it as a newly created dir (for an eventual rollback)
  1695. *
  1696. * @param string $dirPath
  1697. */
  1698. private function mkDir(string $dirPath) {
  1699. mkdir($dirPath);
  1700. $this->createdDirs[] = $dirPath;
  1701. chgrp($dirPath, 'www-data');
  1702. }
  1703. /**
  1704. * Write the given file with content, give its property to the www-data group and
  1705. * record it as a newly created file (for an eventual rollback)
  1706. *
  1707. * @param string $path
  1708. * @param string $content
  1709. */
  1710. private function writeFile(string $path, string $content) {
  1711. $f = fopen($path, "w");
  1712. try
  1713. {
  1714. fwrite($f, $content);
  1715. $this->createdFiles[] = $path;
  1716. chgrp($path, 'www-data');
  1717. } finally {
  1718. fclose($f);
  1719. }
  1720. }
  1721. /**
  1722. * Try to find the config file of the website in the less resource-consuming way
  1723. * and parse it.
  1724. *
  1725. * @param int $rootUid
  1726. * @return array Path of the configuration file and parsed configuration of the website
  1727. */
  1728. protected function findConfigFileAndContentFor(int $rootUid): array
  1729. {
  1730. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1731. $candidates = array_filter(
  1732. scandir($configs_directory),
  1733. function ($x) { return $x != '.' && $x != '..'; }
  1734. );
  1735. // try to filter by directory name
  1736. foreach ($candidates as $subdir) {
  1737. if (preg_match('/\.*_' . $rootUid . '$/', $subdir)) {
  1738. $filename = $configs_directory . $subdir . '/config.yaml';
  1739. $yamlConfig = Yaml::parseFile($filename);
  1740. if ($yamlConfig['rootPageId'] === $rootUid) {
  1741. return [$filename, $yamlConfig];
  1742. }
  1743. }
  1744. }
  1745. // it wasn't found the easy way, let's look to each file... :(
  1746. foreach ($candidates as $subdir) {
  1747. $filename = $configs_directory . $subdir . '/config.yaml';
  1748. $yamlConfig = Yaml::parseFile($filename);
  1749. if ($yamlConfig['rootPageId'] === $rootUid) {
  1750. return [$filename, $yamlConfig];
  1751. }
  1752. }
  1753. return [null, []];
  1754. }
  1755. /**
  1756. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1757. * @param int $rootUid
  1758. * @return array Configuration of the website
  1759. */
  1760. protected function findConfigFor(int $rootUid): array
  1761. {
  1762. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1763. return $pathAndConfig[1];
  1764. }
  1765. /**
  1766. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1767. * @param int $rootUid
  1768. * @return string Path of the config file of the given website
  1769. */
  1770. protected function findConfigFilePathFor(int $rootUid): string
  1771. {
  1772. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1773. return $pathAndConfig[0];
  1774. }
  1775. /**
  1776. * Create or update the .../sites/.../config.yaml file of the given site
  1777. *
  1778. * @param int $organizationId
  1779. * @param int $rootUid
  1780. * @param string $domain
  1781. * @param bool $forceRecreate
  1782. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1783. */
  1784. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false): string
  1785. {
  1786. $existing = $this->findConfigFileAndContentFor($rootUid);
  1787. $configFilename = $existing[0];
  1788. $config = $existing[1];
  1789. $subdomain = explode('.', $domain)[0];
  1790. if (!$configFilename) {
  1791. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1792. $configFilename = $configDir . "/config.yaml";
  1793. $isNew = true;
  1794. if (file_exists($configFilename)) {
  1795. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1796. }
  1797. } else {
  1798. $configDir = dirname($configFilename);
  1799. $config['base'] = 'https://' . $domain;
  1800. $isNew = false;
  1801. }
  1802. if ($isNew || $forceRecreate) {
  1803. $config = ['base' => 'https://' . $domain,
  1804. 'baseVariants' => [
  1805. ['base' => $subdomain . '/',
  1806. 'condition' => 'applicationContext == "Development"']
  1807. ],
  1808. 'errorHandling' => [
  1809. ['errorCode' => '404',
  1810. 'errorHandler' => 'PHP',
  1811. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1812. ['errorCode' => '403',
  1813. 'errorHandler' => 'PHP',
  1814. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1815. ],
  1816. 'flux_content_types' => '',
  1817. 'flux_page_templates' => '',
  1818. 'languages' => [[
  1819. 'title' => 'Fr',
  1820. 'enabled' => True,
  1821. 'base' => '/',
  1822. 'typo3Language' => 'fr',
  1823. 'locale' => 'fr_FR',
  1824. 'iso-639-1' => 'fr',
  1825. 'navigationTitle' => 'Fr',
  1826. 'hreflang' => 'fr-FR',
  1827. 'direction' => 'ltr',
  1828. 'flag' => 'fr',
  1829. 'languageId' => '0',
  1830. ]],
  1831. 'rootPageId' => $rootUid,
  1832. 'routes' => []
  1833. ];
  1834. }
  1835. $yamlConfig = Yaml::dump($config, 99, 2);
  1836. if (!file_exists($configDir)) {
  1837. $this->mkDir($configDir);
  1838. }
  1839. $this->writeFile($configFilename, $yamlConfig);
  1840. // Set the owner and mods, in case www-data is not the one who run this command
  1841. // @see https://www.php.net/manual/fr/function.stat.php
  1842. try {
  1843. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1844. chown($configFilename, $stats['4']);
  1845. chgrp($configFilename, $stats['5']);
  1846. chmod($configFilename, $stats['2']);
  1847. } catch (\Exception $e) {
  1848. }
  1849. // Flush cache:
  1850. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1851. $cacheSystem->remove('site-configuration');
  1852. $cacheSystem->remove('pseudo-sites');
  1853. return $configFilename;
  1854. }
  1855. /**
  1856. * Create the BE user for the website, then return its uid
  1857. * The user shall be already created in the Opentalent DB
  1858. * This is a minimal creation, that shall be completed by the ot_connect ext
  1859. *
  1860. * @param int $organizationId
  1861. * @param int $rootUid
  1862. * @param int $siteGroupUid
  1863. * @param array $userData
  1864. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  1865. * @return int The uid of the created be_user
  1866. */
  1867. private function createOrUpdateBeUser(int $organizationId,
  1868. int $rootUid,
  1869. int $siteGroupUid,
  1870. array $userData,
  1871. int $updateUid = null): int
  1872. {
  1873. if (!isset($userData['username'])) {
  1874. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1875. }
  1876. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1877. $randomStr = (new Random)->generateRandomHexString(20);
  1878. $adminGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  1879. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  1880. $values = [
  1881. 'username' => $userData['username'],
  1882. 'password' => $randomStr,
  1883. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  1884. 'deleted' => 0,
  1885. 'lang' => 'fr',
  1886. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  1887. 'userMods' => '', // inherited from the base AdminGroup
  1888. 'db_mountpoints' => $rootUid,
  1889. 'options' => 2,
  1890. 'tx_opentalent_opentalentId' => $userData['id'],
  1891. 'tx_opentalent_organizationId' => $organizationId,
  1892. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1893. ];
  1894. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1895. if ($updateUid != null) {
  1896. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  1897. foreach ($values as $k => $v) {
  1898. $q->set($k, $v);
  1899. }
  1900. $q->execute();
  1901. return $updateUid;
  1902. } else {
  1903. $queryBuilder->insert('be_users')
  1904. ->values($values)
  1905. ->execute();
  1906. return (int)$queryBuilder->getConnection()->lastInsertId();
  1907. }
  1908. }
  1909. /**
  1910. * Create the BE editors group for the website, then return its uid
  1911. *
  1912. * @param int $organizationId
  1913. * @param int $rootUid
  1914. * @param array $userData
  1915. * @param int|null $updateUid If passed, this method will update this be group instead of creating a new one
  1916. * @return int The uid of the created be_group
  1917. */
  1918. private function createOrUpdateBeGroup(int $organizationId,
  1919. int $rootUid,
  1920. array $userData,
  1921. int $updateUid = null): int
  1922. {
  1923. $groupName = 'editors_' . $organizationId;
  1924. // get the existing filemounts
  1925. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1926. $queryBuilder
  1927. ->select('uid')
  1928. ->from('sys_filemounts')
  1929. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1930. $statement = $queryBuilder->execute();
  1931. $rows = $statement->fetchAll(3) ?: [];
  1932. $files = [];
  1933. foreach ($rows as $row) {
  1934. $files[] = $row[0];
  1935. }
  1936. $mainGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  1937. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  1938. $values = [
  1939. 'title' => $groupName,
  1940. 'deleted' => 0,
  1941. 'subgroup' => $mainGroupUid,
  1942. 'db_mountpoints' => $rootUid,
  1943. 'file_mountPoints' => join(',', $files),
  1944. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1945. 'groupMods' => '', // inherited from the base EditorsGroup
  1946. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  1947. 'tables_select' => '', // inherited from the base EditorsGroup
  1948. 'tables_modify' => '', // inherited from the base EditorsGroup
  1949. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  1950. ];
  1951. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1952. if ($updateUid !== null) {
  1953. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  1954. foreach ($values as $k => $v) {
  1955. $q->set($k, $v);
  1956. }
  1957. $q->execute();
  1958. return $updateUid;
  1959. } else {
  1960. $queryBuilder->insert('be_groups')
  1961. ->values($values)
  1962. ->execute();
  1963. return $queryBuilder->getConnection()->lastInsertId();
  1964. }
  1965. }
  1966. /**
  1967. * Try to find and return the uid of the editors be_group
  1968. * for this website
  1969. *
  1970. * @param int $rootUid
  1971. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  1972. * @return int
  1973. * @throws NoSuchRecordException
  1974. */
  1975. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  1976. $editorsGroups = [
  1977. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  1978. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  1979. ];
  1980. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1981. if (!$withRestrictions) {
  1982. $queryBuilder->getRestrictions()->removeAll();
  1983. }
  1984. $beGroups = $queryBuilder
  1985. ->select('uid', 'subgroup')
  1986. ->from('be_groups')
  1987. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  1988. ->execute()
  1989. ->fetchAll();
  1990. $editorsGroupUid = null;
  1991. foreach ($beGroups as $beGroup) {
  1992. // the editor group shall be a subgroup of one of the Editors group, and have this website mounted
  1993. if (in_array($beGroup['subgroup'], $editorsGroups)) {
  1994. $editorsGroupUid = $beGroup['uid'];
  1995. }
  1996. }
  1997. if ($editorsGroupUid == null) {
  1998. throw new NoSuchRecordException("No editors be_group found " .
  1999. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  2000. }
  2001. return $editorsGroupUid;
  2002. }
  2003. /**
  2004. * Try to find and return the uid of the admin be_user
  2005. * for this website
  2006. *
  2007. * @param int $rootUid
  2008. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2009. * @return int
  2010. * @throws NoSuchRecordException
  2011. * @throws NoSuchWebsiteException
  2012. */
  2013. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2014. $adminGroups = [
  2015. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2016. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2017. ];
  2018. $adminUid = null;
  2019. try {
  2020. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2021. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2022. if (!$withRestrictions) {
  2023. $queryBuilder->getRestrictions()->removeAll();
  2024. }
  2025. $beUsers = $queryBuilder
  2026. ->select('uid', 'usergroup')
  2027. ->from('be_users')
  2028. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2029. ->execute()
  2030. ->fetchAll();
  2031. foreach ($beUsers as $beUser) {
  2032. // the admin shall be both in the website editors group and in the Admin group
  2033. $isAdmin = false;
  2034. $isInThisWebsiteGroup = false;
  2035. foreach (explode(',', $beUser['usergroup']) as $group) {
  2036. if (in_array($group, $adminGroups)) {
  2037. $isAdmin = true;
  2038. }
  2039. if ($group == $editorsGroupUid) {
  2040. $isInThisWebsiteGroup = true;
  2041. }
  2042. }
  2043. if ($isAdmin && $isInThisWebsiteGroup) {
  2044. $adminUid = $beUser['uid'];
  2045. }
  2046. }
  2047. } catch (NoSuchRecordException $e) {
  2048. // the editors group does not exist
  2049. }
  2050. // Try to find if there is a be_user who still is in the v8.7 architecture
  2051. if ($adminUid == null) {
  2052. $organizationId = $this->findOrganizationIdUidFor($rootUid);
  2053. $extraData = $this->fetchOrganizationExtraData($organizationId);
  2054. $expectedUsername = $extraData['admin']['username'];
  2055. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2056. if (!$withRestrictions) {
  2057. $queryBuilder->getRestrictions()->removeAll();
  2058. }
  2059. $row = $queryBuilder
  2060. ->select('uid', 'db_mountpoints')
  2061. ->from('be_users')
  2062. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2063. ->execute()
  2064. ->fetch();
  2065. if ($row['uid']) {
  2066. if ((string)$rootUid != (string)$row['db_mountpoints']) {
  2067. throw new \RuntimeException(
  2068. "The be_user named '" . $expectedUsername .
  2069. "' has unexpected mounted website(s) (expected: " . $rootUid .
  2070. ", found: " . (string)$row['db_mountpoints'] . "). Abort."
  2071. );
  2072. }
  2073. $adminUid = $row['uid'];
  2074. }
  2075. }
  2076. if ($adminUid == null) {
  2077. throw new NoSuchRecordException("No admin be_user found " .
  2078. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2079. }
  2080. return $adminUid;
  2081. }
  2082. /**
  2083. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2084. *
  2085. * @param int $groupType
  2086. * @return int
  2087. */
  2088. protected function getBaseBeGroupUid(int $groupType): int
  2089. {
  2090. $expectedName = self::BEGROUP_NAME[$groupType];
  2091. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2092. $uid = $queryBuilder
  2093. ->select('uid')
  2094. ->from('be_groups')
  2095. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2096. ->execute()
  2097. ->fetchColumn(0);
  2098. if (!$uid) {
  2099. throw new \RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2100. }
  2101. return $uid;
  2102. }
  2103. /**
  2104. * Enable frontend editing for user
  2105. *
  2106. * @param int $adminUid
  2107. */
  2108. private function enableFeEditing(int $adminUid) {
  2109. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  2110. $user = $BE_USER->getRawUserByUid($adminUid);
  2111. $BE_USER->user = $user;
  2112. $BE_USER->backendSetUC();
  2113. $BE_USER->uc['frontend_editing'] = 1;
  2114. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2115. $BE_USER->writeUC($BE_USER->uc);
  2116. }
  2117. }