SiteController.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use http\Exception\RuntimeException;
  4. use Opentalent\OtAdmin\Domain\Entity\SiteInfos;
  5. use Opentalent\OtAdmin\Domain\Entity\SiteStatus;
  6. use Opentalent\OtAdmin\Exception\NoSuchWebsiteException;
  7. use Opentalent\OtCore\Cache\OtCacheManager;
  8. use Opentalent\OtCore\Controller\ActionController;
  9. use Opentalent\OtCore\Domain\Model\Organization;
  10. use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
  11. use Opentalent\OtCore\Exception\ApiRequestException;
  12. use PDO;
  13. use Symfony\Component\Yaml\Yaml;
  14. use TYPO3\CMS\Core\Crypto\Random;
  15. use TYPO3\CMS\Core\Utility\GeneralUtility;
  16. use TYPO3\CMS\Extbase\Object\ObjectManager;
  17. /**
  18. * The SiteController implements some admin-only operations
  19. * on Typo3 websites, like creation or update.
  20. */
  21. class SiteController extends ActionController
  22. {
  23. // Templates names
  24. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  25. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  26. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  27. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  28. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  29. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  30. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  31. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  32. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  33. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  34. const TEMPLATE_LEGAL = "OpenTalent.OtTemplating->legal";
  35. // Pages dokType values
  36. const DOK_PAGE = 1;
  37. const DOK_SHORTCUT = 4;
  38. const DOK_FOLDER = 116;
  39. // Contents CTypes
  40. const CTYPE_TEXT = 'text';
  41. const CTYPE_IMAGE = 'image';
  42. const CTYPE_TEXTPIC = 'textpic';
  43. const CTYPE_TEXTMEDIA = 'textmedia';
  44. const CTYPE_HTML = 'html';
  45. const CTYPE_HEADER = 'header';
  46. const CTYPE_UPLOADS = 'uploads';
  47. const CTYPE_LIST = 'list';
  48. const CTYPE_SITEMAP = 'menu_sitemap';
  49. // Default values
  50. const DEFAULT_THEME = 'Classic';
  51. const DEFAULT_COLOR = 'light-blue';
  52. // BE rights
  53. const PRODUCT_MAPPING = [
  54. "school-standard" => 1, // Association writer basic
  55. "artist-standard" => 1, // Association writer basic
  56. "school-premium" => 3, // Association writer full
  57. "artist-premium" => 3, // Association writer full
  58. "manager" => 3, // Association writer full
  59. ];
  60. // Creation mode
  61. const MODE_PROD = 1;
  62. const MODE_DEV = 1;
  63. // Domain name validation
  64. const RX_DOMAIN = "/([a-z0-9A-Z]\.)*[a-z0-9-]+\.([a-z0-9]{2,24})+(\.co\.([a-z0-9]{2,24})|\.([a-z0-9]{2,24}))*\/?/";
  65. // Redirections creation status
  66. const REDIRECTION_UNKNOWN_STATUS = 0;
  67. const REDIRECTION_UPDATED = 1;
  68. const REDIRECTION_CREATED = 2;
  69. /**
  70. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  71. */
  72. private $connectionPool;
  73. public function injectConnectionPool(\TYPO3\CMS\Core\Database\ConnectionPool $connectionPool)
  74. {
  75. $this->connectionPool = $connectionPool;
  76. }
  77. /**
  78. * @var \TYPO3\CMS\Core\Cache\CacheManager
  79. */
  80. private $cacheManager;
  81. public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager $cacheManager)
  82. {
  83. $this->cacheManager = $cacheManager;
  84. }
  85. /**
  86. * Index of the pages created during the process
  87. * >> [slug => uid]
  88. * @var array
  89. */
  90. private array $createdPagesIndex;
  91. /**
  92. * List of the directories created in the process (for rollback purposes)
  93. * @var array
  94. */
  95. private array $createdDirs;
  96. /**
  97. * List of the files created in the process (for rollback purposes)
  98. * @var array
  99. */
  100. private array $createdFiles;
  101. public function __construct()
  102. {
  103. parent::__construct();
  104. $this->createdPagesIndex = [];
  105. $this->createdDirs = [];
  106. $this->createdFiles = [];
  107. }
  108. /**
  109. * Return the SiteInfos object for the organization's website
  110. *
  111. * @param int $organizationId
  112. * @return SiteInfos
  113. * @throws NoSuchWebsiteException
  114. */
  115. public function getSiteInfosAction(int $organizationId): SiteInfos
  116. {
  117. $rootUid = $this->findRootUidFor($organizationId);
  118. $config = $this->findConfigFor($organizationId, $rootUid);
  119. //$extraData = $this->fetchOrganizationExtraData($organizationId);
  120. $rootPage = $this->otPageRepository->getPage($rootUid);
  121. $site = new SiteInfos(
  122. $rootUid,
  123. $rootPage['title'],
  124. $config['base'],
  125. $rootPage['tx_opentalent_template'],
  126. $rootPage['tx_opentalent_template_preferences'],
  127. $rootPage['tx_opentalent_matomo_id'],
  128. (bool)$rootPage['deleted'],
  129. (bool)($rootPage['hidden'] || $rootPage['fe_group'] < 0)
  130. );
  131. // Owners
  132. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  133. $queryBuilder->getRestrictions()->removeAll();
  134. $beUsers = $queryBuilder
  135. ->select('uid', 'username')
  136. ->from('be_users')
  137. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  138. ->execute()
  139. ->fetchAll();
  140. foreach ($beUsers as $beUser) {
  141. $site->addMountedForBeUser($beUser);
  142. }
  143. return $site;
  144. }
  145. /**
  146. * Creates a new website for the given organization, and
  147. * returns the root page uid of the newly created site
  148. *
  149. * @param int $organizationId
  150. * @param int $mode Can be either MODE_PROD or MODE_DEV, MODE_PROD being the normal behaviour.
  151. * If MODE_DEV is used, sites urls will be of the form 'http://host/subdomain'
  152. * instead of 'http://subdomain/host'
  153. * @return int Uid of the root page of the newly created website
  154. * @throws \RuntimeException|\Exception
  155. */
  156. public function createSiteAction(int $organizationId, int $mode=self::MODE_PROD): int
  157. {
  158. $organization = $this->fetchOrganization($organizationId);
  159. // This extra-data can not be retrieved from the API for now, but
  160. // this shall be set up as soon as possible, to avoid requesting
  161. // the prod-back DB directly.
  162. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  163. $isNetwork = $organizationExtraData['category'] == 'NETWORK';
  164. // Is there already a website with this organization's id?
  165. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  166. $queryBuilder->getRestrictions()->removeAll();
  167. $statement = $queryBuilder
  168. ->select('uid')
  169. ->from('pages')
  170. ->where($queryBuilder->expr()->eq('tx_opentalent_structure_id', $queryBuilder->createNamedParameter($organization->getId())))
  171. ->andWhere('is_siteroot=1')
  172. ->execute();
  173. if ($statement->rowCount() > 0) {
  174. 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)");
  175. }
  176. // ** Create the new website
  177. // start transactions
  178. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  179. // keep tracks of the created folders and files to be able to remove them during a rollback
  180. try {
  181. // Create the site pages:
  182. // > Root page
  183. $rootUid = $this->insertRootPage($organization);
  184. // > 'Accueil' shortcut
  185. $this->insertPage(
  186. $organization,
  187. $rootUid,
  188. 'Accueil',
  189. '/accueil',
  190. '',
  191. [
  192. 'dokType' => self::DOK_SHORTCUT,
  193. 'shortcut' => $rootUid
  194. ]
  195. );
  196. // > 'Présentation' page
  197. $this->insertPage(
  198. $organization,
  199. $rootUid,
  200. 'Présentation',
  201. '/presentation'
  202. );
  203. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  204. $this->insertPage(
  205. $organization,
  206. $this->createdPagesIndex['/presentation'],
  207. 'Qui sommes nous?',
  208. '/qui-sommes-nous',
  209. '',
  210. ['hidden' => 1]
  211. );
  212. // > 'Présentation > Les adhérents' page
  213. $this->insertPage(
  214. $organization,
  215. $this->createdPagesIndex['/presentation'],
  216. 'Les adhérents',
  217. '/les-adherents',
  218. self::TEMPLATE_MEMBERS
  219. );
  220. // > 'Présentation > Les membres du CA' page
  221. $this->insertPage(
  222. $organization,
  223. $this->createdPagesIndex['/presentation'],
  224. 'Les membres du CA',
  225. '/les-membres-du-ca',
  226. self::TEMPLATE_MEMBERSCA
  227. );
  228. if ($isNetwork) {
  229. // > 'Présentation > Les sociétés adhérentes' page
  230. $this->insertPage(
  231. $organization,
  232. $this->createdPagesIndex['/presentation'],
  233. 'Les sociétés adhérentes',
  234. '/societes-adherentes',
  235. self::TEMPLATE_STRUCTURES
  236. );
  237. }
  238. // > 'Présentation > Historique' page (hidden by default)
  239. $this->insertPage(
  240. $organization,
  241. $this->createdPagesIndex['/presentation'],
  242. 'Historique',
  243. '/historique',
  244. '',
  245. ['hidden' => 1]
  246. );
  247. // ~ Contact shortcut will be created after the contact page
  248. // > 'Actualités' page (hidden by default)
  249. $this->insertPage(
  250. $organization,
  251. $rootUid,
  252. 'Actualités',
  253. '/actualites',
  254. self::TEMPLATE_NEWS,
  255. ['hidden' => 1]
  256. );
  257. // > 'Saison en cours' page
  258. $this->insertPage(
  259. $organization,
  260. $rootUid,
  261. 'Saison en cours',
  262. '/saison-en-cours'
  263. );
  264. // > 'Saison en cours > Les évènements' page
  265. $this->insertPage(
  266. $organization,
  267. $this->createdPagesIndex['/saison-en-cours'],
  268. 'Les évènements',
  269. '/les-evenements',
  270. self::TEMPLATE_EVENTS
  271. );
  272. if ($isNetwork) {
  273. // > 'Présentation > Les sociétés adhérentes' page
  274. $this->insertPage(
  275. $organization,
  276. $this->createdPagesIndex['/presentation'],
  277. 'Évènements des structures',
  278. '/evenements-des-structures',
  279. self::TEMPLATE_STRUCTURESEVENTS
  280. );
  281. }
  282. // > 'Vie interne' page (restricted, hidden by default)
  283. $this->insertPage(
  284. $organization,
  285. $rootUid,
  286. 'Vie interne',
  287. '/vie-interne',
  288. '',
  289. [
  290. 'hidden' => 1,
  291. 'fe_group' => -2
  292. ]
  293. );
  294. // > 'Footer' page (not in the menu)
  295. $this->insertPage(
  296. $organization,
  297. $rootUid,
  298. 'Footer',
  299. '/footer',
  300. '',
  301. [
  302. 'dokType' => self::DOK_FOLDER,
  303. 'nav_hide' => 1
  304. ]
  305. );
  306. // > 'Footer > Contact' page
  307. $this->insertPage(
  308. $organization,
  309. $this->createdPagesIndex['/footer'],
  310. 'Contact',
  311. '/contact',
  312. self::TEMPLATE_CONTACT
  313. );
  314. // > 'Footer > Plan du site' page
  315. $this->insertPage(
  316. $organization,
  317. $this->createdPagesIndex['/footer'],
  318. 'Plan du site',
  319. '/plan-du-site'
  320. );
  321. // > 'Footer > Mentions légales' page
  322. $this->insertPage(
  323. $organization,
  324. $this->createdPagesIndex['/footer'],
  325. 'Mentions légales',
  326. '/mentions-legales',
  327. self::TEMPLATE_LEGAL
  328. );
  329. // > 'Présentation > Contact' shortcut
  330. $this->insertPage(
  331. $organization,
  332. $this->createdPagesIndex['/presentation'],
  333. 'Contact',
  334. '/ecrivez-nous',
  335. '',
  336. [
  337. 'dokType' => self::DOK_SHORTCUT,
  338. 'shortcut' => $this->createdPagesIndex['/contact']
  339. ]
  340. );
  341. // > 'Page introuvable' page (not in the menu, read-only)
  342. $this->insertPage(
  343. $organization,
  344. $rootUid,
  345. 'Page introuvable',
  346. '/page-introuvable',
  347. '',
  348. [
  349. 'nav_hide' => 1,
  350. 'no_search' => 1
  351. ]
  352. );
  353. // Add content to these pages
  354. // >> root page content
  355. $this->insertContent(
  356. $rootUid,
  357. self::CTYPE_TEXTPIC,
  358. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  359. 0
  360. );
  361. // >> page 'qui sommes nous?'
  362. $this->insertContent(
  363. $this->createdPagesIndex['/qui-sommes-nous'],
  364. self::CTYPE_TEXT,
  365. 'Qui sommes nous ...',
  366. 0
  367. );
  368. // >> page 'historique'
  369. $this->insertContent(
  370. $this->createdPagesIndex['/historique'],
  371. self::CTYPE_TEXT,
  372. "Un peu d'histoire ...",
  373. 0
  374. );
  375. // >> page 'plan du site'
  376. $this->insertContent(
  377. $this->createdPagesIndex['/plan-du-site'],
  378. self::CTYPE_SITEMAP
  379. );
  380. // Build and update the domain
  381. if ($mode == self::MODE_PROD) {
  382. $domain = $organization->getSubDomain() . '.opentalent.fr';
  383. } elseif ($mode == self::MODE_DEV) {
  384. $domain = $organization->getSubDomain() . '/';
  385. } else {
  386. throw new RuntimeException('Unknown value for $mode: ' . $mode);
  387. }
  388. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_domain');
  389. $queryBuilder->insert('sys_domain')
  390. ->values([
  391. 'pid' => $rootUid,
  392. 'domainName' => $domain
  393. ])
  394. ->execute();
  395. // update sys_template
  396. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  397. $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
  398. $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
  399. $include .= ",EXT:form/Configuration/TypoScript/";
  400. $include .= ",EXT:news/Configuration/TypoScript";
  401. $include .= ",EXT:frontend_editing/Configuration/TypoScript";
  402. $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
  403. $include .= ",EXT:ot_templating/Configuration/TypoScript";
  404. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  405. $queryBuilder->insert('sys_template')
  406. ->values([
  407. 'pid' => $rootUid,
  408. 'title' => $organization->getName(),
  409. 'sitetitle' => $organization->getName(),
  410. 'root' => 1,
  411. 'clear' => 3,
  412. 'config' => "config.frontend_editing = 1",
  413. 'include_static_file' => $include,
  414. 'constants' => $constants
  415. ])
  416. ->execute();
  417. // Create the site config.yaml file
  418. $this->writeConfigFile($organizationId, $rootUid, $domain, true);
  419. // Create the user_upload directory and update the sys_filemounts table
  420. $uploadRelPath = "/user_upload/" . $organizationId;
  421. $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
  422. if (file_exists($uploadDir)) {
  423. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  424. }
  425. $defaultUploadDir = $uploadDir . '/images';
  426. $formsDir = $uploadDir . '/Forms';
  427. $this->mkDir($uploadDir);
  428. $this->mkDir($defaultUploadDir);
  429. $this->mkDir($formsDir);
  430. // Insert the filemounts points (sys_filemounts)
  431. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  432. $queryBuilder->insert('sys_filemounts')
  433. ->values([
  434. 'title' => 'Documents',
  435. 'path' => $defaultUploadDir,
  436. 'base' => 1
  437. ])
  438. ->execute();
  439. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  440. $queryBuilder->insert('sys_filemounts')
  441. ->values([
  442. 'title' => 'Forms_' . $organizationId,
  443. 'path' => $formsDir,
  444. 'base' => 1
  445. ])
  446. ->execute();
  447. // Create the BE User
  448. // -- NB: this user will then be auto-updated by the ot_connect extension --
  449. $beUserUid = $this->createBeUser(
  450. $organizationId,
  451. $rootUid,
  452. $domain,
  453. $organizationExtraData['admin']
  454. );
  455. // Update the user TsConfig
  456. $tsconfig = "options.uploadFieldsInTopOfEB = 1\n" .
  457. "options.defaultUploadFolder=1:" . $defaultUploadDir . "\n";
  458. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  459. $queryBuilder
  460. ->update('be_users')
  461. ->where($queryBuilder->expr()->eq('uid', $beUserUid))
  462. ->set('TSconfig', $tsconfig)
  463. ->execute();
  464. // Give the keys of the website to this user (makes him the owner)
  465. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  466. foreach($this->createdPagesIndex as $slug => $uid) {
  467. $queryBuilder
  468. ->update('pages')
  469. ->where($queryBuilder->expr()->eq('uid', $uid))
  470. ->set('perms_userid', $beUserUid)
  471. ->execute();
  472. }
  473. // Try to commit the result
  474. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  475. if (!$commitSuccess) {
  476. throw new \RuntimeException('Something went wrong while commiting the result');
  477. }
  478. } catch(\Exception $e) {
  479. // rollback
  480. $this->connectionPool->getConnectionByName('Default')->rollback();
  481. // remove created files and dirs
  482. foreach (array_reverse($this->createdFiles) as $filename) {
  483. unlink($filename);
  484. }
  485. $this->createdFiles = [];
  486. foreach (array_reverse($this->createdDirs) as $dirname) {
  487. rmdir($dirname);
  488. }
  489. $this->createdDirs = [];
  490. throw $e;
  491. }
  492. // Extra steps that do not need any rollback:
  493. $this->enableFeEditing($beUserUid);
  494. return $rootUid;
  495. }
  496. /**
  497. * Update the `sys_template`.`constants` field of the given
  498. * organization's website with the data fetched from the opentalent DB.
  499. *
  500. * @param int $organizationId
  501. * @return int
  502. * @throws NoSuchWebsiteException
  503. */
  504. public function updateSiteConstantsAction(int $organizationId): int
  505. {
  506. $rootUid = $this->findRootUidFor($organizationId);
  507. // This extra-data can not be retrieved from the API for now, but
  508. // this shall be set up as soon as possible, to avoid requesting
  509. // the prod-back DB directly.
  510. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  511. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  512. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  513. $queryBuilder
  514. ->update('sys_template')
  515. ->set('constants', $constants)
  516. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  517. ->execute();
  518. OtCacheManager::clearSiteCache($rootUid, true);
  519. return $rootUid;
  520. }
  521. /**
  522. * Delete the website with all its pages, contents and related records
  523. *
  524. * If the hard parameter is false, the records' `deleted` field will be set to true and
  525. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  526. *
  527. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  528. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  529. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  530. *
  531. * $redirectTo is the optional organization id to whom requests will be redirected
  532. *
  533. * @param int $organizationId
  534. * @param bool $hard
  535. * @param int|null $redirectTo
  536. * @return int
  537. * @throws NoSuchWebsiteException
  538. * @throws \Doctrine\DBAL\ConnectionException
  539. * @throws \Doctrine\DBAL\DBALException
  540. */
  541. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null) {
  542. $rootUid = $this->findRootUidFor($organizationId);
  543. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  544. $isDeleted = $queryBuilder
  545. ->select('deleted')
  546. ->from('pages')
  547. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  548. ->execute()
  549. ->fetchColumn(0) == 1;
  550. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  551. if ($hard && !file_exists($confirm_file)) {
  552. throw new \RuntimeException(
  553. "You are going to completely delete the website with root uid " . $rootUid .
  554. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  555. $confirm_file . "', and launch this command again."
  556. );
  557. }
  558. // Prepare the redirection
  559. if ($redirectTo) {
  560. if ($redirectTo == $organizationId) {
  561. throw new \InvalidArgumentException('redirectTo value has to be different from the organizationId');
  562. }
  563. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  564. $targetUrl = $this->getSiteInfosAction($redirectTo)->getBaseUrl();
  565. }
  566. // start transactions
  567. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  568. // keep track of renamed file for an eventual rollback
  569. $renamed = [];
  570. try {
  571. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  572. foreach($pages as $page) {
  573. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  574. $this->delete('pages', 'uid', $page['uid'], $hard);
  575. }
  576. $this->delete('tt_content', 'pid', $rootUid, $hard);
  577. $this->delete('pages', 'uid', $rootUid, $hard);
  578. $this->delete('sys_template', 'pid', $rootUid, $hard);
  579. if ($hard) {
  580. // there is no 'deleted' field in sys_domain
  581. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  582. }
  583. // remove filemounts
  584. $this->delete('sys_filemounts',
  585. 'path',
  586. "'/user_upload/" . $organizationId . "/images'",
  587. $hard);
  588. $this->delete('sys_filemounts',
  589. 'path',
  590. "'/user_upload/" . $organizationId . "/Forms'",
  591. $hard);
  592. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  593. // Look up for the config.yaml file of the website
  594. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  595. $configYamlFile = "";
  596. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  597. if (!$isDeleted) {
  598. $yamlFile = $subdir . '/config.yaml';
  599. } else {
  600. $yamlFile = $subdir . '/config.yaml.deleted';
  601. }
  602. if (is_file($yamlFile)) {
  603. $conf = Yaml::parseFile($yamlFile);
  604. if ($conf['rootPageId'] == $rootUid) {
  605. $configYamlFile = $yamlFile;
  606. break;
  607. }
  608. }
  609. }
  610. if (!$isDeleted) {
  611. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  612. } else {
  613. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  614. }
  615. // If hard deletion, verify that upload dirs are empty
  616. if ($hard && is_dir($uploadDir)) {
  617. foreach (scandir($uploadDir) as $subdir) {
  618. if ($subdir == '.' or $subdir == '..') {
  619. continue;
  620. }
  621. $subdir = $uploadDir . $subdir;
  622. if (!is_dir($subdir)) {
  623. throw new \RuntimeException(
  624. 'The directory ' . $uploadDir . ' contains non-directory files' .
  625. ', this humble script prefers not to take care of them automatically. Abort.');
  626. }
  627. if (is_readable($subdir)) {
  628. foreach (scandir($subdir) as $filename) {
  629. if ($filename != '.' && $filename != '..') {
  630. throw new \RuntimeException(
  631. 'The directory ' . $subdir . ' is not empty, ' .
  632. 'this humble script prefers not to take care of them automatically. Abort.');
  633. }
  634. }
  635. }
  636. }
  637. }
  638. // If soft deletion, check that no deleted file or directory exist
  639. if (!$hard) {
  640. $toRename = [];
  641. if (!$hard) {
  642. if (is_file($configYamlFile)) {
  643. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  644. }
  645. if (is_dir($uploadDir)) {
  646. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  647. }
  648. }
  649. foreach ($toRename as $initialPath => $newPath) {
  650. if (is_file($newPath)) {
  651. throw new \RuntimeException(
  652. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  653. }
  654. }
  655. }
  656. // Delete or rename files and dirs
  657. if ($hard) {
  658. if (is_file($configYamlFile)) {
  659. unlink($configYamlFile);
  660. }
  661. if (is_dir(dirname($configYamlFile))) {
  662. rmdir(dirname($configYamlFile));
  663. }
  664. if (is_dir($uploadDir . 'images')) {
  665. rmdir($uploadDir . 'images');
  666. }
  667. if (is_dir($uploadDir . 'Forms')) {
  668. rmdir($uploadDir . 'Forms');
  669. }
  670. if (is_dir($uploadDir)) {
  671. rmdir($uploadDir);
  672. }
  673. } else {
  674. $renamed = [];
  675. foreach ($toRename as $initialPath => $newPath) {
  676. rename($initialPath, $newPath);
  677. $renamed[$initialPath] = $newPath;
  678. }
  679. }
  680. // Add the redirection
  681. if ($redirectTo) {
  682. $this->addRedirection($originUrl, $targetUrl);
  683. }
  684. // Try to commit the result
  685. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  686. if (!$commitSuccess) {
  687. throw new \RuntimeException('Something went wrong while commiting the result');
  688. }
  689. return $rootUid;
  690. } catch(\Exception $e) {
  691. // rollback
  692. $this->connectionPool->getConnectionByName('Default')->rollback();
  693. if (!$hard) {
  694. foreach ($renamed as $initialPath => $newPath) {
  695. rename($newPath, $initialPath);
  696. }
  697. }
  698. if (file_exists($confirm_file)) {
  699. unlink($confirm_file);
  700. }
  701. throw $e;
  702. }
  703. }
  704. /**
  705. * Delete a record from the typo3 db.
  706. * If $hard is true, the record is permanently deleted.
  707. * Else, it's just marked as deleted.
  708. *
  709. * @param string $table
  710. * @param string $whereKey
  711. * @param $whereValue
  712. * @param int $hard
  713. */
  714. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  715. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  716. if (!$hard) {
  717. $queryBuilder
  718. ->update($table)
  719. ->set('deleted', 1)
  720. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  721. ->execute();
  722. } else {
  723. $queryBuilder
  724. ->delete($table)
  725. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  726. ->execute();
  727. }
  728. }
  729. /**
  730. * Undo a soft-deletion performed using deleteSiteAction()
  731. *
  732. * @param int $organizationId
  733. * @return int
  734. * @throws NoSuchWebsiteException
  735. * @throws \Doctrine\DBAL\ConnectionException
  736. * @throws \Doctrine\DBAL\DBALException
  737. */
  738. public function undeleteSiteAction(int $organizationId) {
  739. $rootUid = $this->findRootUidFor($organizationId);
  740. // start transactions
  741. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  742. // keep track of renamed file for an eventual rollback
  743. $renamed = [];
  744. try {
  745. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  746. foreach($pages as $page) {
  747. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  748. $queryBuilder
  749. ->update('tt_content')
  750. ->set('deleted', 0)
  751. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  752. ->execute();
  753. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  754. $queryBuilder
  755. ->update('pages')
  756. ->set('deleted', 0)
  757. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  758. ->execute();
  759. }
  760. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  761. $queryBuilder
  762. ->update('tt_content')
  763. ->set('deleted', 0)
  764. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  765. ->execute();
  766. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  767. $queryBuilder
  768. ->update('pages')
  769. ->set('deleted', 0)
  770. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  771. ->execute();
  772. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  773. $queryBuilder
  774. ->update('sys_template')
  775. ->set('deleted', 0)
  776. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  777. ->execute();
  778. // remove filemounts
  779. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  780. $queryBuilder
  781. ->update('sys_filemounts')
  782. ->set('deleted', 0)
  783. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  784. ->execute();
  785. $queryBuilder
  786. ->update('sys_filemounts')
  787. ->set('deleted', 0)
  788. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  789. ->execute();
  790. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  791. $queryBuilder
  792. ->update('be_users')
  793. ->set('deleted', 0)
  794. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  795. ->execute();
  796. // Look up for the config.yaml file of the website
  797. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  798. $configYamlFile = "";
  799. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  800. $yamlFile = $subdir . '/config.yaml.deleted';
  801. if (is_file($yamlFile)) {
  802. $conf = Yaml::parseFile($yamlFile);
  803. if ($conf['rootPageId'] == $rootUid) {
  804. $configYamlFile = $yamlFile;
  805. break;
  806. }
  807. }
  808. }
  809. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  810. $toRename = [];
  811. if (is_file($configYamlFile)) {
  812. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  813. }
  814. if (is_dir($uploadDir)) {
  815. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  816. }
  817. foreach ($toRename as $initialPath => $newPath) {
  818. if (is_file($newPath)) {
  819. throw new \RuntimeException(
  820. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  821. }
  822. }
  823. $renamed = [];
  824. foreach ($toRename as $initialPath => $newPath) {
  825. rename($initialPath, $newPath);
  826. $renamed[$initialPath] = $newPath;
  827. }
  828. // remove eventual redirection from this site to another
  829. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  830. $this->removeRedirectionsFrom($originUrl);
  831. // Try to commit the result
  832. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  833. if (!$commitSuccess) {
  834. throw new \RuntimeException('Something went wrong while commiting the result');
  835. }
  836. return $rootUid;
  837. } catch(\Exception $e) {
  838. // rollback
  839. $this->connectionPool->getConnectionByName('Default')->rollback();
  840. foreach ($renamed as $initialPath => $newPath) {
  841. rename($newPath, $initialPath);
  842. }
  843. throw $e;
  844. }
  845. }
  846. /**
  847. * Clear the cache of the organization's website
  848. *
  849. * @param int $organizationId the organization's id whom site cache should be cleared
  850. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  851. * @return int
  852. * @throws NoSuchWebsiteException
  853. */
  854. public function clearSiteCacheAction(int $organizationId, $clearAll=false): int
  855. {
  856. $rootUid = $this->findRootUidFor($organizationId);
  857. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  858. return $rootUid;
  859. }
  860. /**
  861. * Perform a full scan of the website and returns a list of warnings
  862. *
  863. * @param int $organizationId
  864. * @param int $rootUid
  865. * @return array
  866. */
  867. private function scanSite(int $organizationId, int $rootUid) {
  868. $warnings = [];
  869. // fetch pages and root page
  870. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  871. $rootPage = null;
  872. $pageIndex = [];
  873. foreach ($pages as $page) {
  874. $pageIndex[$page['uid']] = $page;
  875. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  876. }
  877. // fetch organization and extradata
  878. $organization = $this->fetchOrganization($organizationId);
  879. $extraData = $this->fetchOrganizationExtraData($organizationId);
  880. // load site's settings (uncomment if needed)
  881. // $config = $this->findConfigFor($organizationId, $rootUid);
  882. // Check site's title
  883. if (trim($rootPage['title']) != trim($organization->getName())) {
  884. $warnings[] = "Site's title does not match the organization name";
  885. }
  886. // Who is the expected owner among the be_users? there should be only one.
  887. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  888. $queryBuilder->getRestrictions()->removeAll();
  889. $beUsers = $queryBuilder
  890. ->select('uid', 'username')
  891. ->from('be_users')
  892. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  893. ->execute()
  894. ->fetchAll();
  895. $owner = null;
  896. if (count($beUsers) > 1) {
  897. $warnings[] = 'Website is mounted on more than one be_user: ' .
  898. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  899. } elseif (count($beUsers) == 0) {
  900. $warnings[] = 'Website is not mounted on any be_user';
  901. } else {
  902. $owner = $beUsers[0];
  903. }
  904. // are template constants up to date?
  905. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  906. $actual_constants = $queryBuilder
  907. ->select('constants')
  908. ->from('sys_template')
  909. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  910. ->execute()
  911. ->fetchColumn(0);
  912. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  913. $norm = function ($s) {
  914. return strtolower(preg_replace('/\s/', '', $s));
  915. };
  916. if ($norm($expected_constants) != $norm($actual_constants)) {
  917. $warnings[] = 'Template constants need an update';
  918. }
  919. $expected_templates = [
  920. "OpenTalent.OtTemplating->home" => 0,
  921. "OpenTalent.OtTemplating->legal" => 0,
  922. "OpenTalent.OtTemplating->contact" => 0
  923. ];
  924. foreach ($pages as $page) {
  925. if ($page['deleted']) {
  926. continue;
  927. }
  928. // Is it the correct owner?
  929. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  930. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  931. }
  932. if (!$page['is_siteroot']) {
  933. // is the parent page state (deleted, hidden, restricted) the same as this page?
  934. $parent = $pageIndex[$page['pid']];
  935. if ($parent['deleted']) {
  936. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  937. }
  938. if ($parent['hidden'] && !$page['hidden']) {
  939. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  940. }
  941. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  942. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  943. }
  944. }
  945. // an expected template was found, remove it from the list of expected
  946. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  947. !$page['deleted'] && !$page['hidden']) {
  948. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  949. }
  950. }
  951. foreach ($expected_templates as $template => $_) {
  952. $warnings[] = 'No page with template ' . $template;
  953. }
  954. return $warnings;
  955. }
  956. /**
  957. * Get the current status and informations of the organization's website
  958. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  959. *
  960. * The status is among:
  961. *
  962. * - STATUS_NO_SUCH_WEBSITE
  963. * - STATUS_EXISTING
  964. * - STATUS_EXISTING_DELETED
  965. * - STATUS_EXISTING_HIDDEN
  966. * - STATUS_EXISTING_WITH_WARNINGS
  967. *
  968. * @param int $organizationId the organization's id whom site cache should be cleared
  969. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  970. * the website pages will be performed.
  971. * @return SiteStatus
  972. */
  973. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  974. {
  975. try {
  976. $siteInfos = $this->getSiteInfosAction($organizationId);
  977. } catch (NoSuchWebsiteException $e) {
  978. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  979. }
  980. if ($siteInfos->isDeleted()) {
  981. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  982. }
  983. if ($siteInfos->isHiddenOrRestricted()) {
  984. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  985. }
  986. $warnings = null;
  987. if ($fullScan) {
  988. // ** Look for potential issues
  989. $warnings = $this->scanSite($organizationId, $siteInfos->getRootUid());
  990. }
  991. return new SiteStatus(
  992. $organizationId,
  993. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  994. $siteInfos,
  995. $warnings
  996. );
  997. }
  998. /**
  999. * Set a new domain for the website.
  1000. * If $redirect is true, also add a redirection from the former domain to the new one
  1001. *
  1002. * @param int $organizationId
  1003. * @param string $newDomain
  1004. * @param bool $redirect
  1005. * @return int
  1006. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1007. * @throws NoSuchWebsiteException
  1008. */
  1009. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1010. {
  1011. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1012. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1013. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1014. }
  1015. $infos = $this->getSiteInfosAction($organizationId);
  1016. $originUrl = $infos->getBaseUrl();
  1017. $rootUid = $infos->getRootUid();
  1018. if (preg_replace('/https?:\/\//', '', $originUrl) == preg_replace('/https?:\/\//', '', $newDomain) ) {
  1019. throw new \RuntimeException('The new domain should be different of the current one');
  1020. }
  1021. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1022. if ($redirect) {
  1023. // Add the redirection
  1024. $this->addRedirection($originUrl, $newDomain);
  1025. }
  1026. return $rootUid;
  1027. }
  1028. /**
  1029. * Return all of the redirections from the given domain name,
  1030. * even if they have been marked as deleted.
  1031. *
  1032. * @param $domain string Domain name, without the http(s):// part
  1033. * @return array Rows from the sys_redirect table
  1034. */
  1035. protected function getRedirectionsFrom(string $domain): array
  1036. {
  1037. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1038. $queryBuilder->getRestrictions()->removeAll();
  1039. return $queryBuilder
  1040. ->select('*')
  1041. ->from('sys_redirect')
  1042. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1043. ->execute()
  1044. ->fetchAll();
  1045. }
  1046. /**
  1047. * Return all of the redirections to the given domain name,
  1048. * even if they have been marked as deleted.
  1049. *
  1050. * @param $domain string Domain name, without the http(s):// part
  1051. * @return array Rows from the sys_redirect table
  1052. */
  1053. protected function getRedirectionsTo(string $domain): array
  1054. {
  1055. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1056. $queryBuilder->getRestrictions()->removeAll();
  1057. return $queryBuilder
  1058. ->select('*')
  1059. ->from('sys_redirect')
  1060. ->where(
  1061. $queryBuilder->expr()->in(
  1062. 'target',
  1063. [
  1064. 'http://' . $queryBuilder->expr()->literal($domain),
  1065. 'https://' . $queryBuilder->expr()->literal($domain)
  1066. ]
  1067. )
  1068. )
  1069. ->execute()
  1070. ->fetchAll();
  1071. }
  1072. /**
  1073. * Add a new redirection from $fromDomain to $toDomain.
  1074. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1075. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1076. *
  1077. * @param $fromDomain
  1078. * @param $toDomain
  1079. * @return int Status of the operation
  1080. */
  1081. public function addRedirection($fromDomain, $toDomain): int
  1082. {
  1083. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1084. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1085. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1086. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1087. }
  1088. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1089. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1090. }
  1091. $existing = $this->getRedirectionsFrom($fromDomain);
  1092. $toUpdate = null;
  1093. foreach ($existing as $redirection) {
  1094. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1095. // a redirection from this domain already exists, and it is not deleted nor disabled
  1096. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1097. // the target is not the same domain
  1098. throw new \RuntimeException(
  1099. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1100. );
  1101. } else {
  1102. // else, target is already the same domain, it will be updated
  1103. $toUpdate = $redirection;
  1104. break;
  1105. }
  1106. } else {
  1107. // a redirection from this domain already exists, but it is deleted or disabled
  1108. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1109. // the target is the same domain, we'll reactivate this record
  1110. $toUpdate = $redirection;
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1116. $data = [
  1117. 'deleted' => 0,
  1118. 'disabled' => 0,
  1119. 'source_host' => $fromDomain,
  1120. 'source_path' => '/.*/',
  1121. 'is_regexp' => 1,
  1122. 'force_https' => 0,
  1123. 'respect_query_parameters' => 0,
  1124. 'keep_query_parameters' => 1,
  1125. 'target' => 'https://' . $toDomain,
  1126. 'target_statuscode' => 301
  1127. ];
  1128. if ($toUpdate !== null) {
  1129. $q = $queryBuilder
  1130. ->update('sys_redirect')
  1131. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1132. foreach ($data as $k => $v) {
  1133. $q->set($k, $v);
  1134. }
  1135. $q->execute();
  1136. return self::REDIRECTION_UPDATED;
  1137. } else {
  1138. $queryBuilder
  1139. ->insert('sys_redirect')
  1140. ->values($data)
  1141. ->execute();
  1142. return self::REDIRECTION_CREATED;
  1143. }
  1144. }
  1145. /**
  1146. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1147. * If $hard is true, delete it completely.
  1148. *
  1149. * @param $fromDomain
  1150. * @param bool $hard
  1151. * @return int Number of affected rows
  1152. */
  1153. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1154. {
  1155. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1156. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1157. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1158. }
  1159. $existing = $this->getRedirectionsFrom($fromDomain);
  1160. $deleted = 0;
  1161. foreach ($existing as $redirection) {
  1162. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1163. $deleted += 1;
  1164. }
  1165. return $deleted;
  1166. }
  1167. /**
  1168. * Retrieve the Organization object from the repository and then,
  1169. * from the Opentalent API
  1170. *
  1171. * @param $organizationId
  1172. * @return Organization
  1173. */
  1174. private function fetchOrganization($organizationId): Organization
  1175. {
  1176. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1177. try {
  1178. return $organizationRepository->findById($organizationId);
  1179. } catch (ApiRequestException $e) {
  1180. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1181. }
  1182. }
  1183. /**
  1184. * Try to find the root page uid of the organization's website and return it.
  1185. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1186. *
  1187. * @param $organizationId
  1188. * @return int
  1189. * @throws NoSuchWebsiteException
  1190. */
  1191. private function findRootUidFor($organizationId): int
  1192. {
  1193. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1194. $queryBuilder->getRestrictions()->removeAll();
  1195. $rootUid = $queryBuilder
  1196. ->select('uid')
  1197. ->from('pages')
  1198. ->where('is_siteroot=1')
  1199. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1200. ->execute()
  1201. ->fetchColumn(0);
  1202. if ($rootUid > 0) {
  1203. return $rootUid;
  1204. }
  1205. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1206. }
  1207. /**
  1208. * Determine which folder-type Typo3 page should contain the new website
  1209. * CREATES IT if needed, and return its uid
  1210. *
  1211. * @return int
  1212. */
  1213. private function getParentFolderUid(): int
  1214. {
  1215. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1216. $siteCount = $queryBuilder
  1217. ->count('uid')
  1218. ->from('pages')
  1219. ->where('is_siteroot=1')
  1220. ->execute()
  1221. ->fetchColumn(0);
  1222. $thousand = (int)(($siteCount + 1) / 1000);
  1223. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1224. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1225. $uid = $queryBuilder
  1226. ->select('uid')
  1227. ->from('pages')
  1228. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1229. ->andWhere('dokType=254')
  1230. ->execute()
  1231. ->fetchColumn(0);
  1232. if ($uid == null) {
  1233. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1234. $queryBuilder->insert('pages')
  1235. ->values([
  1236. 'pid' => 0,
  1237. 'title' => $folderName,
  1238. 'dokType' => 254,
  1239. 'sorting' => 11264,
  1240. 'perms_userid' => 1,
  1241. 'perms_groupid' => 31,
  1242. 'perms_group' => 27,
  1243. ])
  1244. ->execute();
  1245. $uid = $queryBuilder->getConnection()->lastInsertId();
  1246. }
  1247. return $uid;
  1248. }
  1249. /**
  1250. * Insert a new row in the 'pages' table of the Typo3 DB
  1251. * and return its uid
  1252. *
  1253. * @param Organization $organization
  1254. * @param int $pid
  1255. * @param string $title
  1256. * @param string $slug
  1257. * @param string $template
  1258. * @param array $moreValues
  1259. * @return int
  1260. */
  1261. private function insertPage(Organization $organization,
  1262. int $pid,
  1263. string $title,
  1264. string $slug,
  1265. string $template = '',
  1266. array $moreValues = []
  1267. ): int
  1268. {
  1269. $defaultValues = [
  1270. 'pid' => $pid,
  1271. 'perms_groupid' => 3,
  1272. 'perms_user' => 27,
  1273. 'cruser_id' => 1,
  1274. 'dokType' => self::DOK_PAGE,
  1275. 'title' => $title,
  1276. 'slug' => $slug,
  1277. 'backend_layout' => 'flux__grid',
  1278. 'backend_layout_next_level' => 'flux__grid',
  1279. 'tx_opentalent_structure_id' => $organization->getId()
  1280. ];
  1281. if ($template) {
  1282. $defaultValues['tx_fed_page_controller_action'] = $template;
  1283. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1284. }
  1285. $values = array_merge($defaultValues, $moreValues);
  1286. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1287. $queryBuilder->insert('pages')
  1288. ->values($values)
  1289. ->execute();
  1290. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1291. $this->createdPagesIndex[$slug] = $uid;
  1292. return $uid;
  1293. }
  1294. /**
  1295. * Insert the root page of a new organization's website
  1296. * and return its uid
  1297. *
  1298. * @param Organization $organization
  1299. * @return int
  1300. */
  1301. private function insertRootPage(Organization $organization): int
  1302. {
  1303. return $this->insertPage(
  1304. $organization,
  1305. $this->getParentFolderUid(),
  1306. $organization->getName(),
  1307. '/',
  1308. self::TEMPLATE_HOME,
  1309. [
  1310. 'is_siteroot' => 1,
  1311. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1312. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1313. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1314. ]
  1315. );
  1316. }
  1317. /**
  1318. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1319. *
  1320. * @param int $pid
  1321. * @param string $cType
  1322. * @param string $bodyText
  1323. * @param int $colPos
  1324. * @param array $moreValues
  1325. */
  1326. private function insertContent(int $pid,
  1327. string $cType=self::CTYPE_TEXT,
  1328. string $bodyText = '',
  1329. int $colPos=0,
  1330. array $moreValues = []) {
  1331. $defaultValues = [
  1332. 'pid' => $pid,
  1333. 'cruser_id' => 1,
  1334. 'CType' => $cType,
  1335. 'colPos' => $colPos,
  1336. 'bodyText' => $bodyText
  1337. ];
  1338. $values = array_merge($defaultValues, $moreValues);
  1339. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1340. $queryBuilder->insert('tt_content')
  1341. ->values($values)
  1342. ->execute();
  1343. }
  1344. private function fetchOrganizationExtraData(int $organizationId) {
  1345. $cnn = new PDO(
  1346. "mysql:host=prod-back;dbname=opentalent",
  1347. 'dbcloner',
  1348. 'wWZ4hYcrmHLW2mUK',
  1349. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1350. );
  1351. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1352. $stmt = $cnn->prepare(
  1353. "SELECT o.id, o.name, o.facebook, o.twitter,
  1354. o.category, o.logo_id, p.logoDonorsMove
  1355. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1356. ON o.parameters_id = p.id
  1357. WHERE o.id=" . $organizationId . ";"
  1358. );
  1359. $stmt->execute();
  1360. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1361. $data = $stmt->fetch();
  1362. $stmt = $cnn->prepare(
  1363. "SELECT c.email
  1364. FROM opentalent.ContactPoint c
  1365. INNER JOIN opentalent.organization_contactpoint o
  1366. ON o.contactPoint_id = c.id
  1367. WHERE c.contactType = 'PRINCIPAL'
  1368. AND o.organization_id = " . $organizationId . ";"
  1369. );
  1370. $stmt->execute();
  1371. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1372. $data['email'] = $stmt->fetch()['email'];
  1373. $stmt = $cnn->prepare(
  1374. "SELECT n.name, n.logo, n.url
  1375. FROM opentalent.Network n
  1376. INNER JOIN
  1377. (opentalent.NetworkOrganization l
  1378. INNER JOIN opentalent.Organization o
  1379. ON l.organization_id = o.id)
  1380. ON l.network_id = n.id
  1381. WHERE l.endDate is NULL
  1382. AND o.id=" . $organizationId . ";"
  1383. );
  1384. $stmt->execute();
  1385. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1386. $data['network'] = $stmt->fetch();
  1387. $stmt = $cnn->prepare(
  1388. "SELECT p.username, a.id, s.product
  1389. FROM opentalent.Person p
  1390. INNER JOIN Access a ON p.id = a.person_id
  1391. INNER JOIN Settings s on a.organization_id = s.organization_id
  1392. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1393. );
  1394. $stmt->execute();
  1395. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1396. $data['admin'] = $stmt->fetch();
  1397. return $data;
  1398. }
  1399. /**
  1400. * Return the content of `sys_template`.`constants` of
  1401. * the website of the given organization
  1402. *
  1403. * @param int $organizationId
  1404. * @param array $organizationExtraData
  1405. * @return string
  1406. */
  1407. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1408. {
  1409. return "plugin.tx_ottemplating {\n" .
  1410. " settings {\n" .
  1411. " organization {\n" .
  1412. " id = " . $organizationId . "\n" .
  1413. " name = " . $organizationExtraData['name'] . "\n" .
  1414. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1415. " email = " . $organizationExtraData['email'] . "\n" .
  1416. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1417. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1418. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1419. " }\n" .
  1420. " network {\n" .
  1421. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1422. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1423. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1424. " }\n" .
  1425. " }\n" .
  1426. "}";
  1427. }
  1428. /**
  1429. * Create the given directory, give its property to the www-data group and
  1430. * record it as a newly created dir (for an eventual rollback)
  1431. *
  1432. * @param string $dirPath
  1433. */
  1434. private function mkDir(string $dirPath) {
  1435. mkdir($dirPath);
  1436. $this->createdDirs[] = $dirPath;
  1437. chgrp($dirPath, 'www-data');
  1438. }
  1439. /**
  1440. * Write the given file with content, give its property to the www-data group and
  1441. * record it as a newly created file (for an eventual rollback)
  1442. *
  1443. * @param string $path
  1444. * @param string $content
  1445. */
  1446. private function writeFile(string $path, string $content) {
  1447. $f = fopen($path, "w");
  1448. try
  1449. {
  1450. fwrite($f, $content);
  1451. $this->createdFiles[] = $path;
  1452. chgrp($path, 'www-data');
  1453. } finally {
  1454. fclose($f);
  1455. }
  1456. }
  1457. /**
  1458. * Try to find the config file of the website in the less resource-consuming way
  1459. * and parse it.
  1460. *
  1461. * @param int $organizationId
  1462. * @param int $rootUid
  1463. * @return array Path of the configuration file and parsed configuration of the website
  1464. */
  1465. protected function findConfigFileAndContentFor(int $organizationId, int $rootUid): array
  1466. {
  1467. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1468. $candidates = scandir($configs_directory);
  1469. // try to filter by directory name
  1470. foreach ($candidates as $subdir) {
  1471. if (preg_match('/\.*_' . $rootUid . '$/', $subdir)) {
  1472. $filename = $configs_directory . $subdir . '/config.yaml';
  1473. $yamlConfig = Yaml::parseFile($filename);
  1474. if ($yamlConfig['rootPageId'] === $rootUid) {
  1475. return [$filename, $yamlConfig];
  1476. }
  1477. }
  1478. }
  1479. // it wasn't found the easy way, let's look to each file... :(
  1480. foreach ($candidates as $subdir) {
  1481. $filename = $configs_directory . $subdir . '/config.yaml';
  1482. $yamlConfig = Yaml::parseFile($filename);
  1483. if ($yamlConfig['rootPageId'] === $rootUid) {
  1484. return [$filename, $yamlConfig];
  1485. }
  1486. }
  1487. return [null, []];
  1488. }
  1489. /**
  1490. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1491. * @param int $organizationId
  1492. * @param int $rootUid
  1493. * @return array Configuration of the website
  1494. */
  1495. protected function findConfigFor(int $organizationId, int $rootUid): array
  1496. {
  1497. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1498. return $pathAndConfig[1];
  1499. }
  1500. /**
  1501. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1502. * @param int $organizationId
  1503. * @param int $rootUid
  1504. * @return string Path of the config file of the given website
  1505. */
  1506. protected function findConfigFilePathFor(int $organizationId, int $rootUid): string
  1507. {
  1508. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1509. return $pathAndConfig[0];
  1510. }
  1511. /**
  1512. * Create or update the .../sites/.../config.yaml file of the given site
  1513. *
  1514. * @param int $organizationId
  1515. * @param int $rootUid
  1516. * @param string $domain
  1517. * @param bool $forceRecreate
  1518. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1519. */
  1520. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false) {
  1521. $existing = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1522. $configFilename = $existing[0];
  1523. $config = $existing[1];
  1524. $subdomain = explode('.', $domain)[0];
  1525. if (!$configFilename) {
  1526. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1527. $configFilename = $configDir . "/config.yaml";
  1528. $isNew = true;
  1529. if (file_exists($configFilename)) {
  1530. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1531. }
  1532. } else {
  1533. $configDir = dirname($configFilename);
  1534. $config['base'] = 'https://' . $domain;
  1535. $isNew = false;
  1536. }
  1537. if ($isNew || $forceRecreate) {
  1538. $config = ['base' => 'https://' . $domain,
  1539. 'baseVariants' => [
  1540. ['base' => $subdomain . '/',
  1541. 'condition' => 'applicationContext == "Development"']
  1542. ],
  1543. 'errorHandling' => [
  1544. ['errorCode' => '404',
  1545. 'errorHandler' => 'PHP',
  1546. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1547. ['errorCode' => '403',
  1548. 'errorHandler' => 'PHP',
  1549. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1550. ],
  1551. 'flux_content_types' => '',
  1552. 'flux_page_templates' => '',
  1553. 'languages' => [[
  1554. 'title' => 'Fr',
  1555. 'enabled' => True,
  1556. 'base' => '/',
  1557. 'typo3Language' => 'fr',
  1558. 'locale' => 'fr_FR',
  1559. 'iso-639-1' => 'fr',
  1560. 'navigationTitle' => 'Fr',
  1561. 'hreflang' => 'fr-FR',
  1562. 'direction' => 'ltr',
  1563. 'flag' => 'fr',
  1564. 'languageId' => '0',
  1565. ]],
  1566. 'rootPageId' => $rootUid,
  1567. 'routes' => []
  1568. ];
  1569. }
  1570. $yamlConfig = Yaml::dump($config, 99, 2);
  1571. if (!file_exists($configDir)) {
  1572. $this->mkDir($configDir);
  1573. }
  1574. GeneralUtility::writeFile($configFilename, $yamlConfig);
  1575. // Set the owner and mods, in case www-data is not the one who run this command
  1576. // @see https://www.php.net/manual/fr/function.stat.php
  1577. try {
  1578. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1579. chown($configFilename, $stats['4']);
  1580. chgrp($configFilename, $stats['5']);
  1581. chmod($configFilename, $stats['2']);
  1582. } catch (\TYPO3\CMS\Core\Error\Exception $e) {
  1583. }
  1584. // Flush cache:
  1585. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1586. $cacheSystem->remove('site-configuration');
  1587. $cacheSystem->remove('pseudo-sites');
  1588. }
  1589. /**
  1590. * Create the BE user for the website
  1591. * The user shall be already created in the Opentalent DB
  1592. *
  1593. * @param int $organizationId
  1594. * @param int $rootUid
  1595. * @param string $domain
  1596. * @param array $userData
  1597. * @return int The uid of the created be_user
  1598. */
  1599. private function createBeUser(int $organizationId,
  1600. int $rootUid,
  1601. string $domain,
  1602. array $userData): int
  1603. {
  1604. if (!isset($userData['username'])) {
  1605. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1606. }
  1607. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1608. $randomStr = (new Random)->generateRandomHexString(20);
  1609. // get the existing filemounts
  1610. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1611. $queryBuilder
  1612. ->select('uid')
  1613. ->from('sys_filemounts')
  1614. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1615. $statement = $queryBuilder->execute();
  1616. $rows = $statement->fetchAll(3) ?: [];
  1617. $files = [];
  1618. foreach ($rows as $row) {
  1619. $files[] = $row[0];
  1620. }
  1621. $values = [
  1622. 'username' => $userData['username'],
  1623. 'password' => $randomStr,
  1624. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1625. 'deleted' => 0,
  1626. 'lang' => 'fr',
  1627. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1628. 'db_mountpoints' => $rootUid,
  1629. 'userMods' => 'file_FilelistList',
  1630. 'file_mountPoints' => join(',', $files),
  1631. 'options' => 2,
  1632. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1633. 'tx_opentalent_opentalentId' => $userData['id'],
  1634. 'tx_opentalent_organizationId' => $organizationId,
  1635. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1636. ];
  1637. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1638. $queryBuilder->insert('be_users')
  1639. ->values($values)
  1640. ->execute();
  1641. return $queryBuilder->getConnection()->lastInsertId();
  1642. }
  1643. /**
  1644. * Enable frontend editing for user
  1645. *
  1646. * @param int $adminUid
  1647. */
  1648. private function enableFeEditing(int $adminUid) {
  1649. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1650. $user = $BE_USER->getRawUserByUid($adminUid);
  1651. $BE_USER->user = $user;
  1652. $BE_USER->backendSetUC();
  1653. $BE_USER->uc['frontend_editing'] = 1;
  1654. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1655. $BE_USER->writeUC($BE_USER->uc);
  1656. }
  1657. }