SiteController.php 68 KB

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