SiteController.php 69 KB

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