SiteController.php 50 KB

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