SiteController.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use Opentalent\OtTemplating\Domain\Model\Organization;
  4. use Opentalent\OtTemplating\Domain\Repository\OrganizationRepository;
  5. use Opentalent\OtTemplating\Exception\ApiRequestException;
  6. use Opentalent\OtTemplating\Page\OtPageRepository;
  7. use PDO;
  8. use Psr\Log\LoggerAwareInterface;
  9. use Symfony\Component\Yaml\Yaml;
  10. use TYPO3\CMS\Core\Crypto\Random;
  11. use TYPO3\CMS\Core\Database\ConnectionPool;
  12. use TYPO3\CMS\Core\Utility\GeneralUtility;
  13. use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
  14. use TYPO3\CMS\Extbase\Object\ObjectManager;
  15. /**
  16. * The SiteController implements some admin-only operations
  17. * on Typo3 websites, like creation or update.
  18. */
  19. class SiteController extends ActionController
  20. {
  21. // Templates names
  22. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  23. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  24. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  25. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  26. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  27. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  28. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  29. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  30. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  31. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  32. // Pages dokType values
  33. const DOK_PAGE = 1;
  34. const DOK_SHORTCUT = 4;
  35. const DOK_FOLDER = 116;
  36. // Contents CTypes
  37. const CTYPE_TEXT = 'text';
  38. const CTYPE_IMAGE = 'image';
  39. const CTYPE_TEXTPIC = 'textpic';
  40. const CTYPE_TEXTMEDIA = 'textmedia';
  41. const CTYPE_HTML = 'html';
  42. const CTYPE_HEADER = 'header';
  43. const CTYPE_UPLOADS = 'uploads';
  44. const CTYPE_LIST = 'list';
  45. const CTYPE_SITEMAP = 'menu_sitemap';
  46. // Default values
  47. const DEFAULT_THEME = 'Classic';
  48. const DEFAULT_COLOR = 'light-blue';
  49. // BE rights
  50. CONST PRODUCT_MAPPING = [
  51. "school-standard" => 1, // Association writer basic
  52. "artist-standard" => 1, // Association writer basic
  53. "school-premium" => 3, // Association writer full
  54. "artist-premium" => 3, // Association writer full
  55. "manager" => 3, // Association writer full
  56. ];
  57. /**
  58. * Doctrine connection pool
  59. * @var object|LoggerAwareInterface|\TYPO3\CMS\Core\SingletonInterface
  60. */
  61. private $cnnPool;
  62. /**
  63. * Index of the pages created during the process
  64. * >> [slug => uid]
  65. * @var array
  66. */
  67. private $createdPagesIndex;
  68. /**
  69. * List of the directories created in the process (for rollback purposes)
  70. * @var array
  71. */
  72. private $createdDirs;
  73. /**
  74. * List of the files created in the process (for rollback purposes)
  75. * @var array
  76. */
  77. private $createdFiles;
  78. public function __construct()
  79. {
  80. parent::__construct();
  81. $this->cnnPool = GeneralUtility::makeInstance(ConnectionPool::class);
  82. $this->createdPagesIndex = [];
  83. $this->createdDirs = [];
  84. $this->createdFiles = [];
  85. }
  86. /**
  87. * Creates a new website for the given organization, and
  88. * returns the root page uid of the newly created site
  89. *
  90. * @param int $organizationId
  91. * @return int Uid of the root page of the newly created website
  92. * @throws \RuntimeException|\Exception
  93. */
  94. public function createSiteAction(int $organizationId) {
  95. $organization = $this->fetchOrganization($organizationId);
  96. // This extra-data can not be retrieved from the API for now, but
  97. // this shall be set up as soon as possible, to avoid requesting
  98. // the prod-back DB directly.
  99. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  100. $isNetwork = $organizationExtraData['category'] == 'NETWORK';
  101. // ** Test the existence of a website with this name and or organization id
  102. // Is there a site with this organization's name?
  103. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  104. $queryBuilder->getRestrictions()->removeAll();
  105. $queryBuilder
  106. ->select('uid')
  107. ->from('pages')
  108. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($organization->getName())))
  109. ->andWhere('is_siteroot=1');
  110. $statement = $queryBuilder->execute();
  111. if ($statement->rowCount() > 0) {
  112. throw new \RuntimeException('A website with this name already exists: ' . $organization->getName() . "\n(if you can't see it, it might have been soft-deleted)");
  113. }
  114. // Is there a site with this organization's id?
  115. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  116. $queryBuilder->getRestrictions()->removeAll();
  117. $statement = $queryBuilder
  118. ->select('uid')
  119. ->from('pages')
  120. ->where($queryBuilder->expr()->eq('tx_opentalent_structure_id', $queryBuilder->createNamedParameter($organization->getId())))
  121. ->andWhere('is_siteroot=1')
  122. ->execute();
  123. if ($statement->rowCount() > 0) {
  124. 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)");
  125. }
  126. // ** Create the new website
  127. // start transactions
  128. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  129. // keep tracks of the created folders and files to be able to remove them during a rollback
  130. try {
  131. // Create the site pages:
  132. // > Root page
  133. $rootUid = $this->insertRootPage($organization);
  134. // > 'Accueil' shortcut
  135. $this->insertPage(
  136. $organization,
  137. $rootUid,
  138. 'Accueil',
  139. '/accueil',
  140. '',
  141. [
  142. 'dokType' => self::DOK_SHORTCUT,
  143. 'shortcut' => $rootUid
  144. ]
  145. );
  146. // > 'Présentation' page
  147. $this->insertPage(
  148. $organization,
  149. $rootUid,
  150. 'Présentation',
  151. '/presentation'
  152. );
  153. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  154. $this->insertPage(
  155. $organization,
  156. $this->createdPagesIndex['/presentation'],
  157. 'Qui sommes nous?',
  158. '/qui-sommes-nous',
  159. '',
  160. ['hidden' => 1]
  161. );
  162. // > 'Présentation > Les adhérents' page
  163. $this->insertPage(
  164. $organization,
  165. $this->createdPagesIndex['/presentation'],
  166. 'Les adhérents',
  167. '/les-adherents',
  168. self::TEMPLATE_MEMBERS
  169. );
  170. // > 'Présentation > Les membres du CA' page
  171. $this->insertPage(
  172. $organization,
  173. $this->createdPagesIndex['/presentation'],
  174. 'Les membres du CA',
  175. '/les-membres-du-ca',
  176. self::TEMPLATE_MEMBERSCA
  177. );
  178. if ($isNetwork) {
  179. // > 'Présentation > Les sociétés adhérentes' page
  180. $this->insertPage(
  181. $organization,
  182. $this->createdPagesIndex['/presentation'],
  183. 'Les sociétés adhérentes',
  184. '/societes-adherentes',
  185. self::TEMPLATE_STRUCTURES
  186. );
  187. }
  188. // > 'Présentation > Historique' page (hidden by default)
  189. $this->insertPage(
  190. $organization,
  191. $this->createdPagesIndex['/presentation'],
  192. 'Historique',
  193. '/historique',
  194. '',
  195. ['hidden' => 1]
  196. );
  197. // ~ Contact shortcut will be created after the contact page
  198. // > 'Actualités' page (hidden by default)
  199. $this->insertPage(
  200. $organization,
  201. $rootUid,
  202. 'Actualités',
  203. '/actualites',
  204. self::TEMPLATE_NEWS,
  205. ['hidden' => 1]
  206. );
  207. // > 'Saison en cours' page
  208. $this->insertPage(
  209. $organization,
  210. $rootUid,
  211. 'Saison en cours',
  212. '/saison-en-cours'
  213. );
  214. // > 'Saison en cours > Les évènements' page
  215. $this->insertPage(
  216. $organization,
  217. $this->createdPagesIndex['/saison-en-cours'],
  218. 'Les évènements',
  219. '/les-evenements',
  220. self::TEMPLATE_EVENTS
  221. );
  222. if ($isNetwork) {
  223. // > 'Présentation > Les sociétés adhérentes' page
  224. $this->insertPage(
  225. $organization,
  226. $this->createdPagesIndex['/presentation'],
  227. 'Évènements des structures',
  228. '/evenements-des-structures',
  229. self::TEMPLATE_STRUCTURESEVENTS
  230. );
  231. }
  232. // > 'Vie interne' page (restricted, hidden by default)
  233. $this->insertPage(
  234. $organization,
  235. $rootUid,
  236. 'Vie interne',
  237. '/vie-interne',
  238. '',
  239. [
  240. 'hidden' => 1,
  241. 'fe_group' => -2
  242. ]
  243. );
  244. // > 'Footer' page (not in the menu)
  245. $this->insertPage(
  246. $organization,
  247. $rootUid,
  248. 'Footer',
  249. '/footer',
  250. '',
  251. [
  252. 'dokType' => self::DOK_FOLDER,
  253. 'nav_hide' => 1
  254. ]
  255. );
  256. // > 'Footer > Contact' page
  257. $this->insertPage(
  258. $organization,
  259. $this->createdPagesIndex['/footer'],
  260. 'Contact',
  261. '/contact',
  262. self::TEMPLATE_CONTACT
  263. );
  264. // > 'Footer > Plan du site' page
  265. $this->insertPage(
  266. $organization,
  267. $this->createdPagesIndex['/footer'],
  268. 'Plan du site',
  269. '/plan-du-site'
  270. );
  271. // > 'Footer > Mentions légales' page
  272. $this->insertPage(
  273. $organization,
  274. $this->createdPagesIndex['/footer'],
  275. 'Mentions légales',
  276. '/mentions-legales'
  277. );
  278. // > 'Présentation > Contact' shortcut
  279. $this->insertPage(
  280. $organization,
  281. $this->createdPagesIndex['/presentation'],
  282. 'Contact',
  283. '/ecrivez-nous',
  284. '',
  285. [
  286. 'dokType' => self::DOK_SHORTCUT,
  287. 'shortcut' => $this->createdPagesIndex['/contact']
  288. ]
  289. );
  290. // > 'Page introuvable' page (not in the menu, read-only)
  291. $this->insertPage(
  292. $organization,
  293. $rootUid,
  294. 'Page introuvable',
  295. '/page-introuvable',
  296. '',
  297. [
  298. 'nav_hide' => 1,
  299. 'no_search' => 1
  300. ]
  301. );
  302. // Add content to these pages
  303. // >> root page content
  304. $this->insertContent(
  305. $rootUid,
  306. self::CTYPE_TEXTPIC,
  307. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  308. 0
  309. );
  310. // >> page 'qui sommes nous?'
  311. $this->insertContent(
  312. $this->createdPagesIndex['/qui-sommes-nous'],
  313. self::CTYPE_TEXT,
  314. 'Qui sommes nous ...',
  315. 0
  316. );
  317. // >> page 'historique'
  318. $this->insertContent(
  319. $this->createdPagesIndex['/historique'],
  320. self::CTYPE_TEXT,
  321. "Un peu d'histoire ...",
  322. 0
  323. );
  324. // >> page 'plan du site'
  325. $this->insertContent(
  326. $this->createdPagesIndex['/plan-du-site'],
  327. self::CTYPE_SITEMAP
  328. );
  329. // >> page 'mentions légales'
  330. $this->insertContent(
  331. $this->createdPagesIndex['/mentions-legales'],
  332. self::CTYPE_TEXT,
  333. '<p style="margin-bottom: 0"><b>Mentions Légales</b></p>',
  334. 0
  335. );
  336. // Build and update the domain
  337. $domain = $organization->getSubDomain() . '.opentalent.fr';
  338. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_domain');
  339. $queryBuilder->insert('sys_domain')
  340. ->values([
  341. 'pid' => $rootUid,
  342. 'domainName' => $domain
  343. ])
  344. ->execute();
  345. // update sys_template
  346. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  347. $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
  348. $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
  349. $include .= ",EXT:form/Configuration/TypoScript/";
  350. $include .= ",EXT:news/Configuration/TypoScript";
  351. $include .= ",EXT:frontend_editing/Configuration/TypoScript";
  352. $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
  353. $include .= ",EXT:ot_templating/Configuration/TypoScript";
  354. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  355. $queryBuilder->insert('sys_template')
  356. ->values([
  357. 'pid' => $rootUid,
  358. 'title' => $organization->getName(),
  359. 'sitetitle' => $organization->getName(),
  360. 'root' => 1,
  361. 'clear' => 3,
  362. 'config' => "config = 'config.frontend_editing = 1",
  363. 'include_static_file' => $include,
  364. 'constants' => $constants
  365. ])
  366. ->execute();
  367. // Create the site config.yaml file
  368. $this->writeConfigFile($organizationId, $rootUid, $domain);
  369. // Create the user_upload directory and update the sys_filemounts table
  370. $uploadRelPath = "/user_upload/" . $organizationId;
  371. $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
  372. if (file_exists($uploadDir)) {
  373. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  374. }
  375. $this->mkDir($uploadDir);
  376. $this->mkDir($uploadDir . '/images');
  377. $this->mkDir($uploadDir . '/Forms');
  378. // Insert the filemounts points (sys_filemounts)
  379. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  380. $queryBuilder->insert('sys_filemounts')
  381. ->values([
  382. 'title' => 'Documents',
  383. 'path' => $uploadRelPath . '/images',
  384. 'base' => 1
  385. ])
  386. ->execute();
  387. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  388. $queryBuilder->insert('sys_filemounts')
  389. ->values([
  390. 'title' => 'Forms_' . $organizationId,
  391. 'path' => $uploadRelPath . '/Forms',
  392. 'base' => 1
  393. ])
  394. ->execute();
  395. // Create the BE User
  396. // -- NB: this user will then be auto-updated by the ot_connect extension --
  397. $beUserUid = $this->createBeUser(
  398. $organizationId,
  399. $rootUid,
  400. $domain,
  401. $organizationExtraData['admin']
  402. );
  403. // Give the keys of the website to this user (makes him the owner)
  404. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  405. foreach($this->createdPagesIndex as $slug => $uid) {
  406. $queryBuilder
  407. ->update('pages')
  408. ->where($queryBuilder->expr()->eq('uid', $uid))
  409. ->set('perms_userid', $beUserUid)
  410. ->execute();
  411. }
  412. // Try to commit the result
  413. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  414. if (!$commitSuccess) {
  415. throw new \RuntimeException('Something went wrong while commiting the result');
  416. }
  417. } catch(\Exception $e) {
  418. // rollback
  419. $this->cnnPool->getConnectionByName('Default')->rollback();
  420. // remove created files and dirs
  421. foreach (array_reverse($this->createdFiles) as $filename) {
  422. unlink($filename);
  423. }
  424. $this->createdFiles = [];
  425. foreach (array_reverse($this->createdDirs) as $dirname) {
  426. rmdir($dirname);
  427. }
  428. $this->createdDirs = [];
  429. throw $e;
  430. }
  431. // Extra steps that do not need any rollback:
  432. $this->enableFeEditing($beUserUid);
  433. return $rootUid;
  434. }
  435. /**
  436. * Update the `sys_template`.`constants` field of the given
  437. * organization's website with the data fetched from the opentalent DB.
  438. *
  439. * @param int $organizationId
  440. * @return int
  441. */
  442. public function updateSiteConstantsAction(int $organizationId) {
  443. $rootUid = $this->findRootUidFor($organizationId);
  444. // This extra-data can not be retrieved from the API for now, but
  445. // this shall be set up as soon as possible, to avoid requesting
  446. // the prod-back DB directly.
  447. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  448. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  449. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  450. $queryBuilder
  451. ->update('sys_template')
  452. ->set('constants', $constants)
  453. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  454. ->execute();
  455. return $rootUid;
  456. }
  457. /**
  458. * Delete the website with all its pages, contents and related records
  459. *
  460. * If the hard parameter is false, the records' `deleted` field will be set to true and
  461. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  462. *
  463. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  464. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  465. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  466. *
  467. * @param int $organizationId
  468. * @param bool $hard
  469. * @return int
  470. * @throws \Exception
  471. */
  472. public function deleteSiteAction(int $organizationId, bool $hard=false) {
  473. $rootUid = $this->findRootUidFor($organizationId);
  474. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  475. $isDeleted = $queryBuilder
  476. ->select('deleted')
  477. ->from('pages')
  478. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  479. ->execute()
  480. ->fetchColumn(0) == 1;
  481. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  482. if ($hard && !file_exists($confirm_file)) {
  483. throw new \RuntimeException(
  484. "You are going to completely delete the website with root uid " . $rootUid .
  485. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  486. $confirm_file . "', and launch this command again."
  487. );
  488. }
  489. // start transactions
  490. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  491. // keep track of renamed file for an eventual rollback
  492. $renamed = [];
  493. try {
  494. $repository = new OtPageRepository();
  495. $pages = $repository->getAllSubpagesForPage($rootUid);
  496. foreach($pages as $page) {
  497. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  498. $this->delete('pages', 'uid', $page['uid'], $hard);
  499. }
  500. $this->delete('tt_content', 'pid', $rootUid, $hard);
  501. $this->delete('pages', 'uid', $rootUid, $hard);
  502. $this->delete('sys_template', 'pid', $rootUid, $hard);
  503. if ($hard) {
  504. // there is no 'deleted' field in sys_domain
  505. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  506. }
  507. // remove filemounts
  508. $this->delete('sys_filemounts',
  509. 'path',
  510. "'/user_upload/" . $organizationId . "/images'",
  511. $hard);
  512. $this->delete('sys_filemounts',
  513. 'path',
  514. "'/user_upload/" . $organizationId . "/Forms'",
  515. $hard);
  516. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  517. // Look up for the config.yaml file of the website
  518. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  519. $configYamlFile = "";
  520. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  521. if (!$isDeleted) {
  522. $yamlFile = $subdir . '/config.yaml';
  523. } else {
  524. $yamlFile = $subdir . '/config.yaml.deleted';
  525. }
  526. if (is_file($yamlFile)) {
  527. $conf = Yaml::parseFile($yamlFile);
  528. if ($conf['rootPageId'] == $rootUid) {
  529. $configYamlFile = $yamlFile;
  530. break;
  531. }
  532. }
  533. }
  534. if (!$isDeleted) {
  535. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  536. } else {
  537. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  538. }
  539. // If hard deletion, verify that upload dirs are empty
  540. if ($hard && is_dir($uploadDir)) {
  541. foreach (scandir($uploadDir) as $subdir) {
  542. if ($subdir == '.' or $subdir == '..') {
  543. continue;
  544. }
  545. $subdir = $uploadDir . $subdir;
  546. if (!is_dir($subdir)) {
  547. throw new \RuntimeException(
  548. 'The directory ' . $uploadDir . ' contains non-directory files' .
  549. ', this humble script prefers not to take care of them automatically. Abort.');
  550. }
  551. if (is_readable($subdir) && count(scandir($subdir)) > 0) {
  552. throw new \RuntimeException(
  553. 'The directory ' . $subdir . ' is not empty, ' .
  554. 'this humble script prefers not to take care of them automatically. Abort.');
  555. }
  556. }
  557. }
  558. // If soft deletion, check that no deleted file or directory exist
  559. if (!$hard) {
  560. $toRename = [];
  561. if (!$hard) {
  562. if (is_file($configYamlFile)) {
  563. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  564. }
  565. if (is_dir($uploadDir)) {
  566. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  567. }
  568. }
  569. foreach ($toRename as $initialPath => $newPath) {
  570. if (is_file($newPath)) {
  571. throw new \RuntimeException(
  572. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  573. }
  574. }
  575. }
  576. // Delete or rename files and dirs
  577. if ($hard) {
  578. if (is_file($configYamlFile)) {
  579. unlink($configYamlFile);
  580. }
  581. if (is_dir(dirname($configYamlFile))) {
  582. rmdir(dirname($configYamlFile));
  583. }
  584. if (is_dir($uploadDir . 'images')) {
  585. rmdir($uploadDir . 'images');
  586. }
  587. if (is_dir($uploadDir . 'Forms')) {
  588. rmdir($uploadDir . 'Forms');
  589. }
  590. if (is_dir($uploadDir)) {
  591. rmdir($uploadDir);
  592. }
  593. } else {
  594. $renamed = [];
  595. foreach ($toRename as $initialPath => $newPath) {
  596. rename($initialPath, $newPath);
  597. $renamed[$initialPath] = $newPath;
  598. }
  599. }
  600. // Try to commit the result (before any eventual file deletion or renaming)
  601. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  602. if (!$commitSuccess) {
  603. throw new \RuntimeException('Something went wrong while commiting the result');
  604. }
  605. return $rootUid;
  606. } catch(\Exception $e) {
  607. // rollback
  608. $this->cnnPool->getConnectionByName('Default')->rollback();
  609. if (!$hard) {
  610. foreach ($renamed as $initialPath => $newPath) {
  611. rename($newPath, $initialPath);
  612. }
  613. }
  614. if (file_exists($confirm_file)) {
  615. unlink($confirm_file);
  616. }
  617. throw $e;
  618. }
  619. }
  620. /**
  621. * @param string $table
  622. * @param string $whereKey
  623. * @param $whereValue
  624. * @param int $hard
  625. */
  626. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  627. $queryBuilder = $this->cnnPool->getQueryBuilderForTable($table);
  628. if (!$hard) {
  629. $queryBuilder
  630. ->update($table)
  631. ->set('deleted', 1)
  632. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  633. ->execute();
  634. } else {
  635. $queryBuilder
  636. ->delete($table)
  637. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  638. ->execute();
  639. }
  640. }
  641. public function undeleteSiteAction(int $organizationId) {
  642. $rootUid = $this->findRootUidFor($organizationId);
  643. // start transactions
  644. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  645. // keep track of renamed file for an eventual rollback
  646. $renamed = [];
  647. try {
  648. $repository = new OtPageRepository();
  649. $pages = $repository->getAllSubpagesForPage($rootUid);
  650. foreach($pages as $page) {
  651. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  652. $queryBuilder
  653. ->update('tt_content')
  654. ->set('deleted', 0)
  655. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  656. ->execute();
  657. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  658. $queryBuilder
  659. ->update('pages')
  660. ->set('deleted', 0)
  661. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  662. ->execute();
  663. }
  664. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  665. $queryBuilder
  666. ->update('tt_content')
  667. ->set('deleted', 0)
  668. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  669. ->execute();
  670. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  671. $queryBuilder
  672. ->update('pages')
  673. ->set('deleted', 0)
  674. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  675. ->execute();
  676. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  677. $queryBuilder
  678. ->update('sys_template')
  679. ->set('deleted', 0)
  680. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  681. ->execute();
  682. // remove filemounts
  683. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  684. $queryBuilder
  685. ->update('sys_filemounts')
  686. ->set('deleted', 0)
  687. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  688. ->execute();
  689. $queryBuilder
  690. ->update('sys_filemounts')
  691. ->set('deleted', 0)
  692. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  693. ->execute();
  694. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  695. $queryBuilder
  696. ->update('be_users')
  697. ->set('deleted', 0)
  698. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  699. ->execute();
  700. // Look up for the config.yaml file of the website
  701. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  702. $configYamlFile = "";
  703. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  704. $yamlFile = $subdir . '/config.yaml.deleted';
  705. if (is_file($yamlFile)) {
  706. $conf = Yaml::parseFile($yamlFile);
  707. if ($conf['rootPageId'] == $rootUid) {
  708. $configYamlFile = $yamlFile;
  709. break;
  710. }
  711. }
  712. }
  713. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  714. $toRename = [];
  715. if (is_file($configYamlFile)) {
  716. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  717. }
  718. if (is_dir($uploadDir)) {
  719. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  720. }
  721. foreach ($toRename as $initialPath => $newPath) {
  722. if (is_file($newPath)) {
  723. throw new \RuntimeException(
  724. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  725. }
  726. }
  727. $renamed = [];
  728. foreach ($toRename as $initialPath => $newPath) {
  729. rename($initialPath, $newPath);
  730. $renamed[$initialPath] = $newPath;
  731. }
  732. // Try to commit the result
  733. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  734. if (!$commitSuccess) {
  735. throw new \RuntimeException('Something went wrong while commiting the result');
  736. }
  737. return $rootUid;
  738. } catch(\Exception $e) {
  739. // rollback
  740. $this->cnnPool->getConnectionByName('Default')->rollback();
  741. foreach ($renamed as $initialPath => $newPath) {
  742. rename($newPath, $initialPath);
  743. }
  744. throw $e;
  745. }
  746. }
  747. /**
  748. * Retrieve the Organization object from the repository and then,
  749. * from the Opentalent API
  750. * @param $organizationId
  751. * @return Organization
  752. */
  753. private function fetchOrganization($organizationId) {
  754. $manager = GeneralUtility::makeInstance(ObjectManager::class);
  755. $organizationRepository = GeneralUtility::makeInstance(
  756. OrganizationRepository::class,
  757. $manager
  758. );
  759. try {
  760. return $organizationRepository->findById($organizationId);
  761. } catch (ApiRequestException $e) {
  762. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  763. }
  764. }
  765. /**
  766. * Try to find the root page uid of the organization's website and return it.
  767. *
  768. * @param $organizationId
  769. * @return int
  770. */
  771. private function findRootUidFor($organizationId) {
  772. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  773. $queryBuilder->getRestrictions()->removeAll();
  774. $rootUid = $queryBuilder
  775. ->select('uid')
  776. ->from('pages')
  777. ->where('is_siteroot=1')
  778. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  779. ->execute()
  780. ->fetchColumn(0);
  781. if ($rootUid > 0) {
  782. return $rootUid;
  783. }
  784. $organization = $this->fetchOrganization($organizationId);
  785. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  786. $rootUid = $queryBuilder
  787. ->count('uid')
  788. ->from('pages')
  789. ->where('is_siteroot=1')
  790. ->andWhere($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($organization->getName())))
  791. ->andWhere('tx_opentalent_structure_id=null')
  792. ->execute()
  793. ->fetchColumn(0);
  794. if ($rootUid > 0) {
  795. return $rootUid;
  796. }
  797. throw new \RuntimeException("The website of this organization can not be found");
  798. }
  799. /**
  800. * Determine which folder-type Typo3 page should contain the new website
  801. * CREATES IT if needed, and return its uid
  802. *
  803. * @return int
  804. */
  805. private function getParentFolderUid() {
  806. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  807. $siteCount = $queryBuilder
  808. ->count('uid')
  809. ->from('pages')
  810. ->where('is_siteroot=1')
  811. ->execute()
  812. ->fetchColumn(0);
  813. $thousand = (int)(($siteCount + 1) / 1000);
  814. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  815. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  816. $uid = $queryBuilder
  817. ->select('uid')
  818. ->from('pages')
  819. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  820. ->andWhere('dokType=254')
  821. ->execute()
  822. ->fetchColumn(0);
  823. if ($uid == null) {
  824. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  825. $queryBuilder->insert('pages')
  826. ->values([
  827. 'pid' => 0,
  828. 'title' => $folderName,
  829. 'dokType' => 254,
  830. 'sorting' => 11264,
  831. 'perms_userid' => 1,
  832. 'perms_groupid' => 31,
  833. 'perms_group' => 27,
  834. ])
  835. ->execute();
  836. $uid = $queryBuilder->getConnection()->lastInsertId();
  837. }
  838. return $uid;
  839. }
  840. /**
  841. * Insert a new row in the 'pages' table of the Typo3 DB
  842. * and return its uid
  843. *
  844. * @param Organization $organization
  845. * @param int $pid
  846. * @param string $title
  847. * @param string $slug
  848. * @param string $template
  849. * @param array $moreValues
  850. * @return int
  851. */
  852. private function insertPage(Organization $organization,
  853. int $pid,
  854. string $title,
  855. string $slug,
  856. string $template = '',
  857. array $moreValues = []
  858. ) {
  859. $defaultValues = [
  860. 'pid' => $pid,
  861. 'perms_groupid' => 3,
  862. 'perms_user' => 27,
  863. 'cruser_id' => 1,
  864. 'dokType' => self::DOK_PAGE,
  865. 'title' => $title,
  866. 'slug' => $slug,
  867. 'backend_layout' => 'flux__grid',
  868. 'backend_layout_next_level' => 'flux__grid',
  869. 'tx_opentalent_structure_id' => $organization->getId()
  870. ];
  871. if ($template) {
  872. $defaultValues['tx_fed_page_controller_action'] = $template;
  873. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  874. }
  875. $values = array_merge($defaultValues, $moreValues);
  876. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  877. $queryBuilder->insert('pages')
  878. ->values($values)
  879. ->execute();
  880. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  881. $this->createdPagesIndex[$slug] = $uid;
  882. return $uid;
  883. }
  884. /**
  885. * Insert the root page of a new organization's website
  886. * and return its uid
  887. *
  888. * @param Organization $organization
  889. * @return int
  890. */
  891. private function insertRootPage(Organization $organization) {
  892. return $this->insertPage(
  893. $organization,
  894. $this->getParentFolderUid(),
  895. $organization->getName(),
  896. '/',
  897. self::TEMPLATE_HOME,
  898. [
  899. 'is_siteroot' => 1,
  900. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  901. 'tx_opentalent_template' => self::DEFAULT_THEME,
  902. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  903. ]
  904. );
  905. }
  906. /**
  907. * Insert a new row in the 'tt_content' table of the Typo3 DB
  908. *
  909. * @param int $pid
  910. * @param string $cType
  911. * @param string $bodyText
  912. * @param int $colPos
  913. * @param array $moreValues
  914. */
  915. private function insertContent(int $pid,
  916. string $cType=self::CTYPE_TEXT,
  917. string $bodyText = '',
  918. int $colPos=0,
  919. array $moreValues = []) {
  920. $defaultValues = [
  921. 'pid' => $pid,
  922. 'cruser_id' => 1,
  923. 'CType' => $cType,
  924. 'colPos' => $colPos,
  925. 'bodyText' => $bodyText
  926. ];
  927. $values = array_merge($defaultValues, $moreValues);
  928. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  929. $queryBuilder->insert('tt_content')
  930. ->values($values)
  931. ->execute();
  932. }
  933. private function fetchOrganizationExtraData(int $organizationId) {
  934. $cnn = new PDO(
  935. "mysql:host=prod-back;dbname=opentalent",
  936. 'dbcloner',
  937. 'wWZ4hYcrmHLW2mUK',
  938. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  939. );
  940. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  941. $stmt = $cnn->prepare(
  942. "SELECT o.id, o.name, o.facebook, o.twitter,
  943. o.category, o.logo_id, p.logoDonorsMove
  944. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  945. ON o.parameters_id = p.id
  946. WHERE o.id=" . $organizationId . ";"
  947. );
  948. $stmt->execute();
  949. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  950. $data = $stmt->fetch();
  951. $stmt = $cnn->prepare(
  952. "SELECT c.email
  953. FROM opentalent.ContactPoint c
  954. INNER JOIN opentalent.organization_contactpoint o
  955. ON o.contactPoint_id = c.id
  956. WHERE c.contactType = 'PRINCIPAL'
  957. AND o.organization_id = " . $organizationId . ";"
  958. );
  959. $stmt->execute();
  960. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  961. $data['email'] = $stmt->fetch()['email'];
  962. $stmt = $cnn->prepare(
  963. "SELECT n.name, n.logo, n.url
  964. FROM opentalent.Network n
  965. INNER JOIN
  966. (opentalent.NetworkOrganization l
  967. INNER JOIN opentalent.Organization o
  968. ON l.organization_id = o.id)
  969. ON l.network_id = n.id
  970. WHERE l.endDate is NULL
  971. AND o.id=" . $organizationId . ";"
  972. );
  973. $stmt->execute();
  974. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  975. $data['network'] = $stmt->fetch();
  976. $stmt = $cnn->prepare(
  977. "SELECT p.username, a.id, s.product
  978. FROM opentalent.Person p
  979. INNER JOIN Access a ON p.id = a.person_id
  980. INNER JOIN Settings s on a.organization_id = s.organization_id
  981. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  982. );
  983. $stmt->execute();
  984. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  985. $data['admin'] = $stmt->fetch();
  986. return $data;
  987. }
  988. /**
  989. * Return the content of `sys_template`.`constants` of
  990. * the website of the given organization
  991. *
  992. * @param int $organizationId
  993. * @param array $organizationExtraData
  994. * @return string
  995. */
  996. private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
  997. return "plugin.tx_ottemplating {\n" .
  998. " settings {\n" .
  999. " organization {\n" .
  1000. " id = " . $organizationId . "\n" .
  1001. " name = " . $organizationExtraData['name'] . "\n" .
  1002. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1003. " email = " . $organizationExtraData['email'] . "\n" .
  1004. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1005. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1006. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1007. " }\n" .
  1008. " network {\n" .
  1009. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1010. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1011. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1012. " }\n" .
  1013. " }\n" .
  1014. "}";
  1015. }
  1016. /**
  1017. * Create the given directory, give its property to the www-data group and
  1018. * record it as a newly created dir (for an eventual rollback)
  1019. *
  1020. * @param string $dirPath
  1021. */
  1022. private function mkDir(string $dirPath) {
  1023. mkdir($dirPath);
  1024. $this->createdDirs[] = $dirPath;
  1025. chgrp($dirPath, 'www-data');
  1026. }
  1027. /**
  1028. * Write the given file with content, give its property to the www-data group and
  1029. * record it as a newly created file (for an eventual rollback)
  1030. *
  1031. * @param string $path
  1032. * @param string $content
  1033. */
  1034. private function writeFile(string $path, string $content) {
  1035. $f = fopen($path, "w");
  1036. try
  1037. {
  1038. fwrite($f, $content);
  1039. $this->createdFiles[] = $path;
  1040. chgrp($path, 'www-data');
  1041. } finally {
  1042. fclose($f);
  1043. }
  1044. }
  1045. /**
  1046. * Write the .../sites/.../config.yml file of the given site
  1047. *
  1048. * @param int $organizationId
  1049. * @param int $rootUid
  1050. * @param string $domain
  1051. */
  1052. private function writeConfigFile(int $organizationId, int $rootUid, string $domain) {
  1053. $folder_id = explode('.', $domain)[0] . '_' . $organizationId;
  1054. $config_dir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $folder_id;
  1055. $config_filename = $config_dir . "/config.yaml";
  1056. if (file_exists($config_filename)) {
  1057. throw new \RuntimeException("A file " . $config_filename . " already exists. Abort.");
  1058. }
  1059. $config = ['base'=> 'https://' . $domain,
  1060. 'baseVariants'=>[],
  1061. 'errorHandling'=>[
  1062. ['errorCode'=>'404',
  1063. 'errorHandler'=>'PHP',
  1064. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1065. ['errorCode'=>'403',
  1066. 'errorHandler'=>'PHP',
  1067. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1068. ],
  1069. 'flux_content_types'=>'',
  1070. 'flux_page_templates'=>'',
  1071. 'languages'=>[[
  1072. 'title'=>'Fr',
  1073. 'enabled'=>True,
  1074. 'base'=>'/',
  1075. 'typo3Language'=>'fr',
  1076. 'locale'=>'fr_FR',
  1077. 'iso-639-1'=>'fr',
  1078. 'navigationTitle'=>'Fr',
  1079. 'hreflang'=>'fr-FR',
  1080. 'direction'=>'ltr',
  1081. 'flag'=>'fr',
  1082. 'languageId'=>'0',
  1083. ]],
  1084. 'rootPageId'=>$rootUid,
  1085. 'routes'=>[]
  1086. ];
  1087. $yamlConfig = Yaml::dump($config, 4);
  1088. if (!file_exists($config_dir)) {
  1089. $this->mkDir($config_dir);
  1090. }
  1091. $this->writeFile($config_filename, $yamlConfig);
  1092. }
  1093. /**
  1094. * Create the BE user for the website
  1095. * The user shall be already created in the Opentalent DB
  1096. *
  1097. * @param int $organizationId
  1098. * @param int $rootUid
  1099. * @param string $domain
  1100. * @param array $userData
  1101. * @return int
  1102. */
  1103. private function createBeUser(int $organizationId,
  1104. int $rootUid,
  1105. string $domain,
  1106. array $userData) {
  1107. if (!isset($userData['username'])) {
  1108. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1109. }
  1110. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1111. $randomStr = (new Random)->generateRandomHexString(20);
  1112. // get the existing filemounts
  1113. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  1114. $queryBuilder
  1115. ->select('uid')
  1116. ->from('sys_filemounts')
  1117. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1118. $statement = $queryBuilder->execute();
  1119. $rows = $statement->fetchAll(3) ?: [];
  1120. $files = [];
  1121. foreach ($rows as $row) {
  1122. $files[] = $row[0];
  1123. }
  1124. $values = [
  1125. 'username' => $userData['username'],
  1126. 'password' => $randomStr,
  1127. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1128. 'deleted' => 0,
  1129. 'lang' => 'fr',
  1130. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1131. 'db_mountpoints' => $rootUid,
  1132. 'file_mountPoints' => join(',', $files),
  1133. 'options' => 2,
  1134. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1135. 'tx_opentalent_opentalentId' => $userData['id'],
  1136. 'tx_opentalent_organizationId' => $organizationId,
  1137. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1138. ];
  1139. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  1140. $queryBuilder->insert('be_users')
  1141. ->values($values)
  1142. ->execute();
  1143. return $queryBuilder->getConnection()->lastInsertId();
  1144. }
  1145. /**
  1146. * Enable frontend editing for user
  1147. *
  1148. * @param int $adminUid
  1149. */
  1150. private function enableFeEditing(int $adminUid) {
  1151. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1152. $user = $BE_USER->getRawUserByUid($adminUid);
  1153. $BE_USER->user = $user;
  1154. $BE_USER->backendSetUC();
  1155. $BE_USER->uc['frontend_editing'] = 1;
  1156. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1157. $BE_USER->writeUC($BE_USER->uc);
  1158. }
  1159. }