SiteController.php 48 KB

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