SiteController.php 49 KB

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