SiteController.php 50 KB

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