SiteController.php 69 KB

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