SiteController.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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. $defaultUploadDir = $uploadDir . '/images';
  389. $formsDir = $uploadDir . '/Forms';
  390. $this->mkDir($uploadDir);
  391. $this->mkDir($defaultUploadDir);
  392. $this->mkDir($formsDir);
  393. // Insert the filemounts points (sys_filemounts)
  394. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  395. $queryBuilder->insert('sys_filemounts')
  396. ->values([
  397. 'title' => 'Documents',
  398. 'path' => $defaultUploadDir,
  399. 'base' => 1
  400. ])
  401. ->execute();
  402. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  403. $queryBuilder->insert('sys_filemounts')
  404. ->values([
  405. 'title' => 'Forms_' . $organizationId,
  406. 'path' => $formsDir,
  407. 'base' => 1
  408. ])
  409. ->execute();
  410. // Create the BE User
  411. // -- NB: this user will then be auto-updated by the ot_connect extension --
  412. $beUserUid = $this->createBeUser(
  413. $organizationId,
  414. $rootUid,
  415. $domain,
  416. $organizationExtraData['admin']
  417. );
  418. // Update the user TsConfig
  419. $tsconfig = "options.uploadFieldsInTopOfEB = 1\n" .
  420. "options.defaultUploadFolder=1:" . $defaultUploadDir . "\n";
  421. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  422. $queryBuilder
  423. ->update('be_users')
  424. ->where($queryBuilder->expr()->eq('uid', $beUserUid))
  425. ->set('TSconfig', $tsconfig)
  426. ->execute();
  427. // Give the keys of the website to this user (makes him the owner)
  428. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  429. foreach($this->createdPagesIndex as $slug => $uid) {
  430. $queryBuilder
  431. ->update('pages')
  432. ->where($queryBuilder->expr()->eq('uid', $uid))
  433. ->set('perms_userid', $beUserUid)
  434. ->execute();
  435. }
  436. // Try to commit the result
  437. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  438. if (!$commitSuccess) {
  439. throw new \RuntimeException('Something went wrong while commiting the result');
  440. }
  441. } catch(\Exception $e) {
  442. // rollback
  443. $this->cnnPool->getConnectionByName('Default')->rollback();
  444. // remove created files and dirs
  445. foreach (array_reverse($this->createdFiles) as $filename) {
  446. unlink($filename);
  447. }
  448. $this->createdFiles = [];
  449. foreach (array_reverse($this->createdDirs) as $dirname) {
  450. rmdir($dirname);
  451. }
  452. $this->createdDirs = [];
  453. throw $e;
  454. }
  455. // Extra steps that do not need any rollback:
  456. $this->enableFeEditing($beUserUid);
  457. return $rootUid;
  458. }
  459. /**
  460. * Update the `sys_template`.`constants` field of the given
  461. * organization's website with the data fetched from the opentalent DB.
  462. *
  463. * @param int $organizationId
  464. * @return int
  465. */
  466. public function updateSiteConstantsAction(int $organizationId) {
  467. $rootUid = $this->findRootUidFor($organizationId);
  468. // This extra-data can not be retrieved from the API for now, but
  469. // this shall be set up as soon as possible, to avoid requesting
  470. // the prod-back DB directly.
  471. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  472. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  473. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  474. $queryBuilder
  475. ->update('sys_template')
  476. ->set('constants', $constants)
  477. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  478. ->execute();
  479. return $rootUid;
  480. }
  481. /**
  482. * Delete the website with all its pages, contents and related records
  483. *
  484. * If the hard parameter is false, the records' `deleted` field will be set to true and
  485. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  486. *
  487. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  488. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  489. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  490. *
  491. * @param int $organizationId
  492. * @param bool $hard
  493. * @return int
  494. * @throws \Exception
  495. */
  496. public function deleteSiteAction(int $organizationId, bool $hard=false) {
  497. $rootUid = $this->findRootUidFor($organizationId);
  498. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  499. $isDeleted = $queryBuilder
  500. ->select('deleted')
  501. ->from('pages')
  502. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  503. ->execute()
  504. ->fetchColumn(0) == 1;
  505. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  506. if ($hard && !file_exists($confirm_file)) {
  507. throw new \RuntimeException(
  508. "You are going to completely delete the website with root uid " . $rootUid .
  509. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  510. $confirm_file . "', and launch this command again."
  511. );
  512. }
  513. // start transactions
  514. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  515. // keep track of renamed file for an eventual rollback
  516. $renamed = [];
  517. try {
  518. $repository = new OtPageRepository();
  519. $pages = $repository->getAllSubpagesForPage($rootUid);
  520. foreach($pages as $page) {
  521. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  522. $this->delete('pages', 'uid', $page['uid'], $hard);
  523. }
  524. $this->delete('tt_content', 'pid', $rootUid, $hard);
  525. $this->delete('pages', 'uid', $rootUid, $hard);
  526. $this->delete('sys_template', 'pid', $rootUid, $hard);
  527. if ($hard) {
  528. // there is no 'deleted' field in sys_domain
  529. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  530. }
  531. // remove filemounts
  532. $this->delete('sys_filemounts',
  533. 'path',
  534. "'/user_upload/" . $organizationId . "/images'",
  535. $hard);
  536. $this->delete('sys_filemounts',
  537. 'path',
  538. "'/user_upload/" . $organizationId . "/Forms'",
  539. $hard);
  540. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  541. // Look up for the config.yaml file of the website
  542. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  543. $configYamlFile = "";
  544. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  545. if (!$isDeleted) {
  546. $yamlFile = $subdir . '/config.yaml';
  547. } else {
  548. $yamlFile = $subdir . '/config.yaml.deleted';
  549. }
  550. if (is_file($yamlFile)) {
  551. $conf = Yaml::parseFile($yamlFile);
  552. if ($conf['rootPageId'] == $rootUid) {
  553. $configYamlFile = $yamlFile;
  554. break;
  555. }
  556. }
  557. }
  558. if (!$isDeleted) {
  559. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  560. } else {
  561. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  562. }
  563. // If hard deletion, verify that upload dirs are empty
  564. if ($hard && is_dir($uploadDir)) {
  565. foreach (scandir($uploadDir) as $subdir) {
  566. if ($subdir == '.' or $subdir == '..') {
  567. continue;
  568. }
  569. $subdir = $uploadDir . $subdir;
  570. if (!is_dir($subdir)) {
  571. throw new \RuntimeException(
  572. 'The directory ' . $uploadDir . ' contains non-directory files' .
  573. ', this humble script prefers not to take care of them automatically. Abort.');
  574. }
  575. if (is_readable($subdir)) {
  576. foreach (scandir($subdir) as $filename) {
  577. if ($filename != '.' && $filename != '..') {
  578. throw new \RuntimeException(
  579. 'The directory ' . $subdir . ' is not empty, ' .
  580. 'this humble script prefers not to take care of them automatically. Abort.');
  581. }
  582. }
  583. }
  584. }
  585. }
  586. // If soft deletion, check that no deleted file or directory exist
  587. if (!$hard) {
  588. $toRename = [];
  589. if (!$hard) {
  590. if (is_file($configYamlFile)) {
  591. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  592. }
  593. if (is_dir($uploadDir)) {
  594. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  595. }
  596. }
  597. foreach ($toRename as $initialPath => $newPath) {
  598. if (is_file($newPath)) {
  599. throw new \RuntimeException(
  600. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  601. }
  602. }
  603. }
  604. // Delete or rename files and dirs
  605. if ($hard) {
  606. if (is_file($configYamlFile)) {
  607. unlink($configYamlFile);
  608. }
  609. if (is_dir(dirname($configYamlFile))) {
  610. rmdir(dirname($configYamlFile));
  611. }
  612. if (is_dir($uploadDir . 'images')) {
  613. rmdir($uploadDir . 'images');
  614. }
  615. if (is_dir($uploadDir . 'Forms')) {
  616. rmdir($uploadDir . 'Forms');
  617. }
  618. if (is_dir($uploadDir)) {
  619. rmdir($uploadDir);
  620. }
  621. } else {
  622. $renamed = [];
  623. foreach ($toRename as $initialPath => $newPath) {
  624. rename($initialPath, $newPath);
  625. $renamed[$initialPath] = $newPath;
  626. }
  627. }
  628. // Try to commit the result (before any eventual file deletion or renaming)
  629. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  630. if (!$commitSuccess) {
  631. throw new \RuntimeException('Something went wrong while commiting the result');
  632. }
  633. return $rootUid;
  634. } catch(\Exception $e) {
  635. // rollback
  636. $this->cnnPool->getConnectionByName('Default')->rollback();
  637. if (!$hard) {
  638. foreach ($renamed as $initialPath => $newPath) {
  639. rename($newPath, $initialPath);
  640. }
  641. }
  642. if (file_exists($confirm_file)) {
  643. unlink($confirm_file);
  644. }
  645. throw $e;
  646. }
  647. }
  648. /**
  649. * @param string $table
  650. * @param string $whereKey
  651. * @param $whereValue
  652. * @param int $hard
  653. */
  654. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  655. $queryBuilder = $this->cnnPool->getQueryBuilderForTable($table);
  656. if (!$hard) {
  657. $queryBuilder
  658. ->update($table)
  659. ->set('deleted', 1)
  660. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  661. ->execute();
  662. } else {
  663. $queryBuilder
  664. ->delete($table)
  665. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  666. ->execute();
  667. }
  668. }
  669. public function undeleteSiteAction(int $organizationId) {
  670. $rootUid = $this->findRootUidFor($organizationId);
  671. // start transactions
  672. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  673. // keep track of renamed file for an eventual rollback
  674. $renamed = [];
  675. try {
  676. $repository = new OtPageRepository();
  677. $pages = $repository->getAllSubpagesForPage($rootUid);
  678. foreach($pages as $page) {
  679. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  680. $queryBuilder
  681. ->update('tt_content')
  682. ->set('deleted', 0)
  683. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  684. ->execute();
  685. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  686. $queryBuilder
  687. ->update('pages')
  688. ->set('deleted', 0)
  689. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  690. ->execute();
  691. }
  692. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  693. $queryBuilder
  694. ->update('tt_content')
  695. ->set('deleted', 0)
  696. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  697. ->execute();
  698. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  699. $queryBuilder
  700. ->update('pages')
  701. ->set('deleted', 0)
  702. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  703. ->execute();
  704. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  705. $queryBuilder
  706. ->update('sys_template')
  707. ->set('deleted', 0)
  708. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  709. ->execute();
  710. // remove filemounts
  711. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  712. $queryBuilder
  713. ->update('sys_filemounts')
  714. ->set('deleted', 0)
  715. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  716. ->execute();
  717. $queryBuilder
  718. ->update('sys_filemounts')
  719. ->set('deleted', 0)
  720. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  721. ->execute();
  722. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  723. $queryBuilder
  724. ->update('be_users')
  725. ->set('deleted', 0)
  726. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  727. ->execute();
  728. // Look up for the config.yaml file of the website
  729. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  730. $configYamlFile = "";
  731. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  732. $yamlFile = $subdir . '/config.yaml.deleted';
  733. if (is_file($yamlFile)) {
  734. $conf = Yaml::parseFile($yamlFile);
  735. if ($conf['rootPageId'] == $rootUid) {
  736. $configYamlFile = $yamlFile;
  737. break;
  738. }
  739. }
  740. }
  741. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  742. $toRename = [];
  743. if (is_file($configYamlFile)) {
  744. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  745. }
  746. if (is_dir($uploadDir)) {
  747. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  748. }
  749. foreach ($toRename as $initialPath => $newPath) {
  750. if (is_file($newPath)) {
  751. throw new \RuntimeException(
  752. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  753. }
  754. }
  755. $renamed = [];
  756. foreach ($toRename as $initialPath => $newPath) {
  757. rename($initialPath, $newPath);
  758. $renamed[$initialPath] = $newPath;
  759. }
  760. // Try to commit the result
  761. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  762. if (!$commitSuccess) {
  763. throw new \RuntimeException('Something went wrong while commiting the result');
  764. }
  765. return $rootUid;
  766. } catch(\Exception $e) {
  767. // rollback
  768. $this->cnnPool->getConnectionByName('Default')->rollback();
  769. foreach ($renamed as $initialPath => $newPath) {
  770. rename($newPath, $initialPath);
  771. }
  772. throw $e;
  773. }
  774. }
  775. /**
  776. * Retrieve the Organization object from the repository and then,
  777. * from the Opentalent API
  778. * @param $organizationId
  779. * @return Organization
  780. */
  781. private function fetchOrganization($organizationId) {
  782. $manager = GeneralUtility::makeInstance(ObjectManager::class);
  783. $organizationRepository = GeneralUtility::makeInstance(
  784. OrganizationRepository::class,
  785. $manager
  786. );
  787. try {
  788. return $organizationRepository->findById($organizationId);
  789. } catch (ApiRequestException $e) {
  790. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  791. }
  792. }
  793. /**
  794. * Try to find the root page uid of the organization's website and return it.
  795. *
  796. * @param $organizationId
  797. * @return int
  798. */
  799. private function findRootUidFor($organizationId) {
  800. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  801. $queryBuilder->getRestrictions()->removeAll();
  802. $rootUid = $queryBuilder
  803. ->select('uid')
  804. ->from('pages')
  805. ->where('is_siteroot=1')
  806. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  807. ->execute()
  808. ->fetchColumn(0);
  809. if ($rootUid > 0) {
  810. return $rootUid;
  811. }
  812. $organization = $this->fetchOrganization($organizationId);
  813. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  814. $rootUid = $queryBuilder
  815. ->count('uid')
  816. ->from('pages')
  817. ->where('is_siteroot=1')
  818. ->andWhere($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($organization->getName())))
  819. ->andWhere('tx_opentalent_structure_id=null')
  820. ->execute()
  821. ->fetchColumn(0);
  822. if ($rootUid > 0) {
  823. return $rootUid;
  824. }
  825. throw new \RuntimeException("The website of this organization can not be found");
  826. }
  827. /**
  828. * Determine which folder-type Typo3 page should contain the new website
  829. * CREATES IT if needed, and return its uid
  830. *
  831. * @return int
  832. */
  833. private function getParentFolderUid() {
  834. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  835. $siteCount = $queryBuilder
  836. ->count('uid')
  837. ->from('pages')
  838. ->where('is_siteroot=1')
  839. ->execute()
  840. ->fetchColumn(0);
  841. $thousand = (int)(($siteCount + 1) / 1000);
  842. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  843. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  844. $uid = $queryBuilder
  845. ->select('uid')
  846. ->from('pages')
  847. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  848. ->andWhere('dokType=254')
  849. ->execute()
  850. ->fetchColumn(0);
  851. if ($uid == null) {
  852. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  853. $queryBuilder->insert('pages')
  854. ->values([
  855. 'pid' => 0,
  856. 'title' => $folderName,
  857. 'dokType' => 254,
  858. 'sorting' => 11264,
  859. 'perms_userid' => 1,
  860. 'perms_groupid' => 31,
  861. 'perms_group' => 27,
  862. ])
  863. ->execute();
  864. $uid = $queryBuilder->getConnection()->lastInsertId();
  865. }
  866. return $uid;
  867. }
  868. /**
  869. * Insert a new row in the 'pages' table of the Typo3 DB
  870. * and return its uid
  871. *
  872. * @param Organization $organization
  873. * @param int $pid
  874. * @param string $title
  875. * @param string $slug
  876. * @param string $template
  877. * @param array $moreValues
  878. * @return int
  879. */
  880. private function insertPage(Organization $organization,
  881. int $pid,
  882. string $title,
  883. string $slug,
  884. string $template = '',
  885. array $moreValues = []
  886. ) {
  887. $defaultValues = [
  888. 'pid' => $pid,
  889. 'perms_groupid' => 3,
  890. 'perms_user' => 27,
  891. 'cruser_id' => 1,
  892. 'dokType' => self::DOK_PAGE,
  893. 'title' => $title,
  894. 'slug' => $slug,
  895. 'backend_layout' => 'flux__grid',
  896. 'backend_layout_next_level' => 'flux__grid',
  897. 'tx_opentalent_structure_id' => $organization->getId()
  898. ];
  899. if ($template) {
  900. $defaultValues['tx_fed_page_controller_action'] = $template;
  901. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  902. }
  903. $values = array_merge($defaultValues, $moreValues);
  904. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  905. $queryBuilder->insert('pages')
  906. ->values($values)
  907. ->execute();
  908. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  909. $this->createdPagesIndex[$slug] = $uid;
  910. return $uid;
  911. }
  912. /**
  913. * Insert the root page of a new organization's website
  914. * and return its uid
  915. *
  916. * @param Organization $organization
  917. * @return int
  918. */
  919. private function insertRootPage(Organization $organization) {
  920. return $this->insertPage(
  921. $organization,
  922. $this->getParentFolderUid(),
  923. $organization->getName(),
  924. '/',
  925. self::TEMPLATE_HOME,
  926. [
  927. 'is_siteroot' => 1,
  928. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  929. 'tx_opentalent_template' => self::DEFAULT_THEME,
  930. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  931. ]
  932. );
  933. }
  934. /**
  935. * Insert a new row in the 'tt_content' table of the Typo3 DB
  936. *
  937. * @param int $pid
  938. * @param string $cType
  939. * @param string $bodyText
  940. * @param int $colPos
  941. * @param array $moreValues
  942. */
  943. private function insertContent(int $pid,
  944. string $cType=self::CTYPE_TEXT,
  945. string $bodyText = '',
  946. int $colPos=0,
  947. array $moreValues = []) {
  948. $defaultValues = [
  949. 'pid' => $pid,
  950. 'cruser_id' => 1,
  951. 'CType' => $cType,
  952. 'colPos' => $colPos,
  953. 'bodyText' => $bodyText
  954. ];
  955. $values = array_merge($defaultValues, $moreValues);
  956. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  957. $queryBuilder->insert('tt_content')
  958. ->values($values)
  959. ->execute();
  960. }
  961. private function fetchOrganizationExtraData(int $organizationId) {
  962. $cnn = new PDO(
  963. "mysql:host=prod-back;dbname=opentalent",
  964. 'dbcloner',
  965. 'wWZ4hYcrmHLW2mUK',
  966. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  967. );
  968. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  969. $stmt = $cnn->prepare(
  970. "SELECT o.id, o.name, o.facebook, o.twitter,
  971. o.category, o.logo_id, p.logoDonorsMove
  972. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  973. ON o.parameters_id = p.id
  974. WHERE o.id=" . $organizationId . ";"
  975. );
  976. $stmt->execute();
  977. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  978. $data = $stmt->fetch();
  979. $stmt = $cnn->prepare(
  980. "SELECT c.email
  981. FROM opentalent.ContactPoint c
  982. INNER JOIN opentalent.organization_contactpoint o
  983. ON o.contactPoint_id = c.id
  984. WHERE c.contactType = 'PRINCIPAL'
  985. AND o.organization_id = " . $organizationId . ";"
  986. );
  987. $stmt->execute();
  988. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  989. $data['email'] = $stmt->fetch()['email'];
  990. $stmt = $cnn->prepare(
  991. "SELECT n.name, n.logo, n.url
  992. FROM opentalent.Network n
  993. INNER JOIN
  994. (opentalent.NetworkOrganization l
  995. INNER JOIN opentalent.Organization o
  996. ON l.organization_id = o.id)
  997. ON l.network_id = n.id
  998. WHERE l.endDate is NULL
  999. AND o.id=" . $organizationId . ";"
  1000. );
  1001. $stmt->execute();
  1002. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1003. $data['network'] = $stmt->fetch();
  1004. $stmt = $cnn->prepare(
  1005. "SELECT p.username, a.id, s.product
  1006. FROM opentalent.Person p
  1007. INNER JOIN Access a ON p.id = a.person_id
  1008. INNER JOIN Settings s on a.organization_id = s.organization_id
  1009. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1010. );
  1011. $stmt->execute();
  1012. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1013. $data['admin'] = $stmt->fetch();
  1014. return $data;
  1015. }
  1016. /**
  1017. * Return the content of `sys_template`.`constants` of
  1018. * the website of the given organization
  1019. *
  1020. * @param int $organizationId
  1021. * @param array $organizationExtraData
  1022. * @return string
  1023. */
  1024. private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
  1025. return "plugin.tx_ottemplating {\n" .
  1026. " settings {\n" .
  1027. " organization {\n" .
  1028. " id = " . $organizationId . "\n" .
  1029. " name = " . $organizationExtraData['name'] . "\n" .
  1030. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1031. " email = " . $organizationExtraData['email'] . "\n" .
  1032. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1033. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1034. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1035. " }\n" .
  1036. " network {\n" .
  1037. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1038. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1039. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1040. " }\n" .
  1041. " }\n" .
  1042. "}";
  1043. }
  1044. /**
  1045. * Create the given directory, give its property to the www-data group and
  1046. * record it as a newly created dir (for an eventual rollback)
  1047. *
  1048. * @param string $dirPath
  1049. */
  1050. private function mkDir(string $dirPath) {
  1051. mkdir($dirPath);
  1052. $this->createdDirs[] = $dirPath;
  1053. chgrp($dirPath, 'www-data');
  1054. }
  1055. /**
  1056. * Write the given file with content, give its property to the www-data group and
  1057. * record it as a newly created file (for an eventual rollback)
  1058. *
  1059. * @param string $path
  1060. * @param string $content
  1061. */
  1062. private function writeFile(string $path, string $content) {
  1063. $f = fopen($path, "w");
  1064. try
  1065. {
  1066. fwrite($f, $content);
  1067. $this->createdFiles[] = $path;
  1068. chgrp($path, 'www-data');
  1069. } finally {
  1070. fclose($f);
  1071. }
  1072. }
  1073. /**
  1074. * Write the .../sites/.../config.yml file of the given site
  1075. *
  1076. * @param int $organizationId
  1077. * @param int $rootUid
  1078. * @param string $domain
  1079. */
  1080. private function writeConfigFile(int $organizationId, int $rootUid, string $domain) {
  1081. $folder_id = explode('.', $domain)[0] . '_' . $organizationId;
  1082. $config_dir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $folder_id;
  1083. $config_filename = $config_dir . "/config.yaml";
  1084. if (file_exists($config_filename)) {
  1085. throw new \RuntimeException("A file " . $config_filename . " already exists. Abort.");
  1086. }
  1087. $config = ['base'=> 'https://' . $domain,
  1088. 'baseVariants'=>[],
  1089. 'errorHandling'=>[
  1090. ['errorCode'=>'404',
  1091. 'errorHandler'=>'PHP',
  1092. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1093. ['errorCode'=>'403',
  1094. 'errorHandler'=>'PHP',
  1095. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1096. ],
  1097. 'flux_content_types'=>'',
  1098. 'flux_page_templates'=>'',
  1099. 'languages'=>[[
  1100. 'title'=>'Fr',
  1101. 'enabled'=>True,
  1102. 'base'=>'/',
  1103. 'typo3Language'=>'fr',
  1104. 'locale'=>'fr_FR',
  1105. 'iso-639-1'=>'fr',
  1106. 'navigationTitle'=>'Fr',
  1107. 'hreflang'=>'fr-FR',
  1108. 'direction'=>'ltr',
  1109. 'flag'=>'fr',
  1110. 'languageId'=>'0',
  1111. ]],
  1112. 'rootPageId'=>$rootUid,
  1113. 'routes'=>[]
  1114. ];
  1115. $yamlConfig = Yaml::dump($config, 99, 2);
  1116. if (!file_exists($config_dir)) {
  1117. $this->mkDir($config_dir);
  1118. }
  1119. GeneralUtility::writeFile($config_filename, $yamlConfig);
  1120. // Set the owner and mods, in case www-data is not the one who run this command
  1121. // @see https://www.php.net/manual/fr/function.stat.php
  1122. try {
  1123. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1124. chown($config_filename, $stats['4']);
  1125. chgrp($config_filename, $stats['5']);
  1126. chmod($config_filename, $stats['2']);
  1127. } catch (\TYPO3\CMS\Core\Error\Exception $e) {
  1128. }
  1129. // Flush cache:
  1130. $cacheSystem = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_core');
  1131. $cacheSystem->remove('site-configuration');
  1132. $cacheSystem->remove('pseudo-sites');
  1133. }
  1134. /**
  1135. * Create the BE user for the website
  1136. * The user shall be already created in the Opentalent DB
  1137. *
  1138. * @param int $organizationId
  1139. * @param int $rootUid
  1140. * @param string $domain
  1141. * @param array $userData
  1142. * @return int
  1143. */
  1144. private function createBeUser(int $organizationId,
  1145. int $rootUid,
  1146. string $domain,
  1147. array $userData) {
  1148. if (!isset($userData['username'])) {
  1149. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1150. }
  1151. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1152. $randomStr = (new Random)->generateRandomHexString(20);
  1153. // get the existing filemounts
  1154. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  1155. $queryBuilder
  1156. ->select('uid')
  1157. ->from('sys_filemounts')
  1158. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1159. $statement = $queryBuilder->execute();
  1160. $rows = $statement->fetchAll(3) ?: [];
  1161. $files = [];
  1162. foreach ($rows as $row) {
  1163. $files[] = $row[0];
  1164. }
  1165. $values = [
  1166. 'username' => $userData['username'],
  1167. 'password' => $randomStr,
  1168. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1169. 'deleted' => 0,
  1170. 'lang' => 'fr',
  1171. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1172. 'db_mountpoints' => $rootUid,
  1173. 'userMods' => 'file_FilelistList',
  1174. 'file_mountPoints' => join(',', $files),
  1175. 'options' => 2,
  1176. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1177. 'tx_opentalent_opentalentId' => $userData['id'],
  1178. 'tx_opentalent_organizationId' => $organizationId,
  1179. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1180. ];
  1181. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  1182. $queryBuilder->insert('be_users')
  1183. ->values($values)
  1184. ->execute();
  1185. return $queryBuilder->getConnection()->lastInsertId();
  1186. }
  1187. /**
  1188. * Enable frontend editing for user
  1189. *
  1190. * @param int $adminUid
  1191. */
  1192. private function enableFeEditing(int $adminUid) {
  1193. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1194. $user = $BE_USER->getRawUserByUid($adminUid);
  1195. $BE_USER->user = $user;
  1196. $BE_USER->backendSetUC();
  1197. $BE_USER->uc['frontend_editing'] = 1;
  1198. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1199. $BE_USER->writeUC($BE_USER->uc);
  1200. }
  1201. }