SiteController.php 51 KB

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