SiteController.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  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. * $redirectTo is the optional organization id to whom requests will be redirected
  545. *
  546. * @param int $organizationId
  547. * @param bool $hard
  548. * @param int|null $redirectTo
  549. * @return int
  550. * @throws NoSuchWebsiteException
  551. * @throws \Doctrine\DBAL\ConnectionException
  552. * @throws \Doctrine\DBAL\DBALException
  553. */
  554. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null) {
  555. $rootUid = $this->findRootUidFor($organizationId);
  556. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  557. $isDeleted = $queryBuilder
  558. ->select('deleted')
  559. ->from('pages')
  560. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  561. ->execute()
  562. ->fetchColumn(0) == 1;
  563. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  564. if ($hard && !file_exists($confirm_file)) {
  565. throw new \RuntimeException(
  566. "You are going to completely delete the website with root uid " . $rootUid .
  567. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  568. $confirm_file . "', and launch this command again."
  569. );
  570. }
  571. // Prepare the redirection
  572. if ($redirectTo) {
  573. if ($redirectTo == $organizationId) {
  574. throw new \InvalidArgumentException('redirectTo value has to be different from the organizationId');
  575. }
  576. $originUrl = $this->getSiteInfosAction($organizationId)['baseUrl'];
  577. $targetUrl = $this->getSiteInfosAction($redirectTo)['baseUrl'];
  578. }
  579. // start transactions
  580. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  581. // keep track of renamed file for an eventual rollback
  582. $renamed = [];
  583. try {
  584. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  585. foreach($pages as $page) {
  586. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  587. $this->delete('pages', 'uid', $page['uid'], $hard);
  588. }
  589. $this->delete('tt_content', 'pid', $rootUid, $hard);
  590. $this->delete('pages', 'uid', $rootUid, $hard);
  591. $this->delete('sys_template', 'pid', $rootUid, $hard);
  592. if ($hard) {
  593. // there is no 'deleted' field in sys_domain
  594. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  595. }
  596. // remove filemounts
  597. $this->delete('sys_filemounts',
  598. 'path',
  599. "'/user_upload/" . $organizationId . "/images'",
  600. $hard);
  601. $this->delete('sys_filemounts',
  602. 'path',
  603. "'/user_upload/" . $organizationId . "/Forms'",
  604. $hard);
  605. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  606. // Look up for the config.yaml file of the website
  607. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  608. $configYamlFile = "";
  609. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  610. if (!$isDeleted) {
  611. $yamlFile = $subdir . '/config.yaml';
  612. } else {
  613. $yamlFile = $subdir . '/config.yaml.deleted';
  614. }
  615. if (is_file($yamlFile)) {
  616. $conf = Yaml::parseFile($yamlFile);
  617. if ($conf['rootPageId'] == $rootUid) {
  618. $configYamlFile = $yamlFile;
  619. break;
  620. }
  621. }
  622. }
  623. if (!$isDeleted) {
  624. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  625. } else {
  626. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  627. }
  628. // If hard deletion, verify that upload dirs are empty
  629. if ($hard && is_dir($uploadDir)) {
  630. foreach (scandir($uploadDir) as $subdir) {
  631. if ($subdir == '.' or $subdir == '..') {
  632. continue;
  633. }
  634. $subdir = $uploadDir . $subdir;
  635. if (!is_dir($subdir)) {
  636. throw new \RuntimeException(
  637. 'The directory ' . $uploadDir . ' contains non-directory files' .
  638. ', this humble script prefers not to take care of them automatically. Abort.');
  639. }
  640. if (is_readable($subdir)) {
  641. foreach (scandir($subdir) as $filename) {
  642. if ($filename != '.' && $filename != '..') {
  643. throw new \RuntimeException(
  644. 'The directory ' . $subdir . ' is not empty, ' .
  645. 'this humble script prefers not to take care of them automatically. Abort.');
  646. }
  647. }
  648. }
  649. }
  650. }
  651. // If soft deletion, check that no deleted file or directory exist
  652. if (!$hard) {
  653. $toRename = [];
  654. if (!$hard) {
  655. if (is_file($configYamlFile)) {
  656. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  657. }
  658. if (is_dir($uploadDir)) {
  659. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  660. }
  661. }
  662. foreach ($toRename as $initialPath => $newPath) {
  663. if (is_file($newPath)) {
  664. throw new \RuntimeException(
  665. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  666. }
  667. }
  668. }
  669. // Delete or rename files and dirs
  670. if ($hard) {
  671. if (is_file($configYamlFile)) {
  672. unlink($configYamlFile);
  673. }
  674. if (is_dir(dirname($configYamlFile))) {
  675. rmdir(dirname($configYamlFile));
  676. }
  677. if (is_dir($uploadDir . 'images')) {
  678. rmdir($uploadDir . 'images');
  679. }
  680. if (is_dir($uploadDir . 'Forms')) {
  681. rmdir($uploadDir . 'Forms');
  682. }
  683. if (is_dir($uploadDir)) {
  684. rmdir($uploadDir);
  685. }
  686. } else {
  687. $renamed = [];
  688. foreach ($toRename as $initialPath => $newPath) {
  689. rename($initialPath, $newPath);
  690. $renamed[$initialPath] = $newPath;
  691. }
  692. }
  693. // Add the redirection
  694. if ($redirectTo) {
  695. $this->addRedirection($originUrl, $targetUrl);
  696. }
  697. // Try to commit the result
  698. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  699. if (!$commitSuccess) {
  700. throw new \RuntimeException('Something went wrong while commiting the result');
  701. }
  702. return $rootUid;
  703. } catch(\Exception $e) {
  704. // rollback
  705. $this->connectionPool->getConnectionByName('Default')->rollback();
  706. if (!$hard) {
  707. foreach ($renamed as $initialPath => $newPath) {
  708. rename($newPath, $initialPath);
  709. }
  710. }
  711. if (file_exists($confirm_file)) {
  712. unlink($confirm_file);
  713. }
  714. throw $e;
  715. }
  716. }
  717. /**
  718. * @param string $table
  719. * @param string $whereKey
  720. * @param $whereValue
  721. * @param int $hard
  722. */
  723. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  724. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  725. if (!$hard) {
  726. $queryBuilder
  727. ->update($table)
  728. ->set('deleted', 1)
  729. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  730. ->execute();
  731. } else {
  732. $queryBuilder
  733. ->delete($table)
  734. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  735. ->execute();
  736. }
  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)['baseUrl'];
  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. * Pack the status informations into an array for the getSiteStatusAction method
  862. *
  863. * @param int $organizationId
  864. * @param int $code
  865. * @param int|null $rootUid
  866. * @param array|null $warnings
  867. * @return array
  868. */
  869. private function buildStatusResult(
  870. int $organizationId,
  871. int $code,
  872. ?int $rootUid = null,
  873. ?array $warnings = null): array
  874. {
  875. $message = "";
  876. if($code == self::STATUS_NO_SUCH_WEBSITE) {
  877. $message = 'No website were found for organization ' . $organizationId;
  878. } elseif ($code == self::STATUS_EXISTING) {
  879. $message = 'A website exists for organization ' . $organizationId;
  880. }
  881. elseif ($code == self::STATUS_EXISTING_DELETED) {
  882. $message = 'A website exists for organization ' . $organizationId . ', but has been deleted';
  883. }
  884. elseif ($code == self::STATUS_EXISTING_HIDDEN) {
  885. $message = 'A website exists for organization ' . $organizationId . ', but is hidden or has a restricted access';
  886. } elseif ($code == self::STATUS_EXISTING_WITH_WARNINGS) {
  887. $message = 'A website exists for organization ' . $organizationId . ', but warnings were raised';
  888. }
  889. $title = '';
  890. if ($rootUid !== null) {
  891. $title = $this->otPageRepository->getPage($rootUid)['title'];
  892. }
  893. $status = [
  894. 'organization_id' => $organizationId,
  895. 'code' => $code,
  896. 'status' => self::STATUS_LBL[$code],
  897. 'message' => $message,
  898. 'root_uid' => $rootUid,
  899. 'title' => $title
  900. ];
  901. if ($warnings !== null) {
  902. $status['warnings'] = $warnings;
  903. }
  904. return $status;
  905. }
  906. /**
  907. * Perform a full scan of the website and returns a list of warnings
  908. *
  909. * @param int $organizationId
  910. * @param int $rootUid
  911. * @return array
  912. */
  913. private function scanSite(int $organizationId, int $rootUid) {
  914. $warnings = [];
  915. // fetch pages and root page
  916. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  917. $rootPage = null;
  918. $pageIndex = [];
  919. foreach ($pages as $page) {
  920. $pageIndex[$page['uid']] = $page;
  921. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  922. }
  923. // fetch organization and extradata
  924. $organization = $this->fetchOrganization($organizationId);
  925. $extraData = $this->fetchOrganizationExtraData($organizationId);
  926. // load site's settings (uncomment if needed)
  927. // $config = $this->findConfigFor($organizationId, $rootUid);
  928. // Check site's title
  929. if (trim($rootPage['title']) != trim($organization->getName())) {
  930. $warnings[] = "Site's title does not match the organization name";
  931. }
  932. // Who is the expected owner among the be_users? there should be only one.
  933. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  934. $queryBuilder->getRestrictions()->removeAll();
  935. $beUsers = $queryBuilder
  936. ->select('uid', 'username')
  937. ->from('be_users')
  938. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  939. ->execute()
  940. ->fetchAll();
  941. $owner = null;
  942. if (count($beUsers) > 1) {
  943. $warnings[] = 'Website is mounted on more than one be_user: ' .
  944. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  945. } elseif (count($beUsers) == 0) {
  946. $warnings[] = 'Website is not mounted on any be_user';
  947. } else {
  948. $owner = $beUsers[0];
  949. }
  950. // are template constants up to date?
  951. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  952. $actual_constants = $queryBuilder
  953. ->select('constants')
  954. ->from('sys_template')
  955. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  956. ->execute()
  957. ->fetchColumn(0);
  958. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  959. $norm = function ($s) {
  960. return strtolower(preg_replace('/\s/', '', $s));
  961. };
  962. if ($norm($expected_constants) != $norm($actual_constants)) {
  963. $warnings[] = 'Template constants need an update';
  964. }
  965. $expected_templates = [
  966. "OpenTalent.OtTemplating->home" => 0,
  967. "OpenTalent.OtTemplating->legal" => 0,
  968. "OpenTalent.OtTemplating->contact" => 0
  969. ];
  970. foreach ($pages as $page) {
  971. if ($page['deleted']) {
  972. continue;
  973. }
  974. // Is it the correct owner?
  975. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  976. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  977. }
  978. if (!$page['is_siteroot']) {
  979. // is the parent page state (deleted, hidden, restricted) the same as this page?
  980. $parent = $pageIndex[$page['pid']];
  981. if ($parent['deleted']) {
  982. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  983. }
  984. if ($parent['hidden'] && !$page['hidden']) {
  985. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  986. }
  987. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  988. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  989. }
  990. }
  991. // an expected template was found, remove it from the list of expected
  992. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  993. !$page['deleted'] && !$page['hidden']) {
  994. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  995. }
  996. }
  997. foreach ($expected_templates as $template => $_) {
  998. $warnings[] = 'No page with template ' . $template;
  999. }
  1000. return $warnings;
  1001. }
  1002. /**
  1003. * Get the current status of the organization's website
  1004. *
  1005. * The result is an array of the form:
  1006. *
  1007. * [
  1008. * 'organization_id' => int,
  1009. * 'code' => int,
  1010. * 'status' => int,
  1011. * 'message' => string,
  1012. * 'root_uid' => ?int,
  1013. * 'site_title' => ?string,
  1014. * ('warnings' => array)
  1015. * ]
  1016. *
  1017. * If $statusOnly is true, the warnings entry won't be added
  1018. *
  1019. * The code value is among:
  1020. *
  1021. * - STATUS_NO_SUCH_WEBSITE
  1022. * - STATUS_EXISTING
  1023. * - STATUS_EXISTING_DELETED
  1024. * - STATUS_EXISTING_HIDDEN
  1025. * - STATUS_EXISTING_WITH_WARNINGS
  1026. *
  1027. * @param int $organizationId the organization's id whom site cache should be cleared
  1028. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1029. * the website pages will be performed.
  1030. * @return array
  1031. */
  1032. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): array
  1033. {
  1034. try {
  1035. $rootUid = $this->findRootUidFor($organizationId);
  1036. } catch (NoSuchWebsiteException $e) {
  1037. return $this->buildStatusResult($organizationId, self::STATUS_NO_SUCH_WEBSITE);
  1038. }
  1039. if ($rootUid['deleted']) {
  1040. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_DELETED, $rootUid);
  1041. }
  1042. if ($rootUid['hidden'] || ($rootUid['fe_group'] < 0)) {
  1043. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_HIDDEN, $rootUid);
  1044. }
  1045. $warnings = null;
  1046. if ($fullScan) {
  1047. // ** Look for potential issues
  1048. $warnings = $this->scanSite($organizationId, $rootUid);
  1049. }
  1050. return $this->buildStatusResult(
  1051. $organizationId,
  1052. $warnings ? self::STATUS_EXISTING_WITH_WARNINGS : self::STATUS_EXISTING,
  1053. $rootUid,
  1054. $warnings);
  1055. }
  1056. /**
  1057. * Set a new domain for the website.
  1058. * If $redirect is true, also add a redirection from the former domain to the new one
  1059. *
  1060. * @param int $organizationId
  1061. * @param string $newDomain
  1062. * @param bool $redirect
  1063. * @return int
  1064. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1065. * @throws NoSuchWebsiteException
  1066. */
  1067. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1068. {
  1069. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1070. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1071. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1072. }
  1073. $infos = $this->getSiteInfosAction($organizationId);
  1074. $originUrl = $infos['baseUrl'];
  1075. $rootUid = $infos['rootUid'];
  1076. if (preg_replace('/https?:\/\//', '', $originUrl) == preg_replace('/https?:\/\//', '', $newDomain) ) {
  1077. throw new \RuntimeException('The new domain should be different of the current one');
  1078. }
  1079. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1080. if ($redirect) {
  1081. // Add the redirection
  1082. $this->addRedirection($originUrl, $newDomain);
  1083. }
  1084. return $rootUid;
  1085. }
  1086. /**
  1087. * Return all of the redirections from the given domain name,
  1088. * even if they have been marked as deleted.
  1089. *
  1090. * @param $domain string Domain name, without the http(s):// part
  1091. * @return array Rows from the sys_redirect table
  1092. */
  1093. protected function getRedirectionsFrom(string $domain): array
  1094. {
  1095. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1096. $queryBuilder->getRestrictions()->removeAll();
  1097. return $queryBuilder
  1098. ->select('*')
  1099. ->from('sys_redirect')
  1100. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1101. ->execute()
  1102. ->fetchAll();
  1103. }
  1104. /**
  1105. * Return all of the redirections to the given domain name,
  1106. * even if they have been marked as deleted.
  1107. *
  1108. * @param $domain string Domain name, without the http(s):// part
  1109. * @return array Rows from the sys_redirect table
  1110. */
  1111. protected function getRedirectionsTo(string $domain): array
  1112. {
  1113. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1114. $queryBuilder->getRestrictions()->removeAll();
  1115. return $queryBuilder
  1116. ->select('*')
  1117. ->from('sys_redirect')
  1118. ->where(
  1119. $queryBuilder->expr()->in(
  1120. 'target',
  1121. [
  1122. 'http://' . $queryBuilder->expr()->literal($domain),
  1123. 'https://' . $queryBuilder->expr()->literal($domain)
  1124. ]
  1125. )
  1126. )
  1127. ->execute()
  1128. ->fetchAll();
  1129. }
  1130. /**
  1131. * Add a new redirection from $fromDomain to $toDomain.
  1132. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1133. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1134. *
  1135. * @param $fromDomain
  1136. * @param $toDomain
  1137. * @return int Status of the operation
  1138. */
  1139. public function addRedirection($fromDomain, $toDomain): int
  1140. {
  1141. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1142. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1143. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1144. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1145. }
  1146. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1147. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1148. }
  1149. $existing = $this->getRedirectionsFrom($fromDomain);
  1150. $toUpdate = null;
  1151. foreach ($existing as $redirection) {
  1152. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1153. // a redirection from this domain already exists, and it is not deleted nor disabled
  1154. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1155. // the target is not the same domain
  1156. throw new \RuntimeException(
  1157. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1158. );
  1159. } else {
  1160. // else, target is already the same domain, it will be updated
  1161. $toUpdate = $redirection;
  1162. break;
  1163. }
  1164. } else {
  1165. // a redirection from this domain already exists, but it is deleted or disabled
  1166. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1167. // the target is the same domain, we'll reactivate this record
  1168. $toUpdate = $redirection;
  1169. break;
  1170. }
  1171. }
  1172. }
  1173. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1174. $data = [
  1175. 'deleted' => 0,
  1176. 'disabled' => 0,
  1177. 'source_host' => $fromDomain,
  1178. 'source_path' => '/.*/',
  1179. 'is_regexp' => 1,
  1180. 'force_https' => 0,
  1181. 'respect_query_parameters' => 0,
  1182. 'keep_query_parameters' => 1,
  1183. 'target' => 'https://' . $toDomain,
  1184. 'target_statuscode' => 301
  1185. ];
  1186. if ($toUpdate !== null) {
  1187. $q = $queryBuilder
  1188. ->update('sys_redirect')
  1189. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1190. foreach ($data as $k => $v) {
  1191. $q->set($k, $v);
  1192. }
  1193. $q->execute();
  1194. return self::REDIRECTION_UPDATED;
  1195. } else {
  1196. $queryBuilder
  1197. ->insert('sys_redirect')
  1198. ->values($data)
  1199. ->execute();
  1200. return self::REDIRECTION_CREATED;
  1201. }
  1202. }
  1203. /**
  1204. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1205. * If $hard is true, delete it completely.
  1206. *
  1207. * @param $fromDomain
  1208. * @param bool $hard
  1209. * @return int Number of affected rows
  1210. */
  1211. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1212. {
  1213. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1214. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1215. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1216. }
  1217. $existing = $this->getRedirectionsFrom($fromDomain);
  1218. $deleted = 0;
  1219. foreach ($existing as $redirection) {
  1220. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1221. $deleted += 1;
  1222. }
  1223. return $deleted;
  1224. }
  1225. /**
  1226. * Retrieve the Organization object from the repository and then,
  1227. * from the Opentalent API
  1228. * @param $organizationId
  1229. * @return Organization
  1230. */
  1231. private function fetchOrganization($organizationId) {
  1232. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1233. try {
  1234. return $organizationRepository->findById($organizationId);
  1235. } catch (ApiRequestException $e) {
  1236. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1237. }
  1238. }
  1239. /**
  1240. * Try to find the root page uid of the organization's website and return it.
  1241. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1242. *
  1243. * @param $organizationId
  1244. * @return int
  1245. * @throws NoSuchWebsiteException
  1246. */
  1247. private function findRootUidFor($organizationId) {
  1248. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1249. $queryBuilder->getRestrictions()->removeAll();
  1250. $rootUid = $queryBuilder
  1251. ->select('uid')
  1252. ->from('pages')
  1253. ->where('is_siteroot=1')
  1254. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1255. ->execute()
  1256. ->fetchColumn(0);
  1257. if ($rootUid > 0) {
  1258. return $rootUid;
  1259. }
  1260. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1261. }
  1262. /**
  1263. * Determine which folder-type Typo3 page should contain the new website
  1264. * CREATES IT if needed, and return its uid
  1265. *
  1266. * @return int
  1267. */
  1268. private function getParentFolderUid() {
  1269. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1270. $siteCount = $queryBuilder
  1271. ->count('uid')
  1272. ->from('pages')
  1273. ->where('is_siteroot=1')
  1274. ->execute()
  1275. ->fetchColumn(0);
  1276. $thousand = (int)(($siteCount + 1) / 1000);
  1277. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1278. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1279. $uid = $queryBuilder
  1280. ->select('uid')
  1281. ->from('pages')
  1282. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1283. ->andWhere('dokType=254')
  1284. ->execute()
  1285. ->fetchColumn(0);
  1286. if ($uid == null) {
  1287. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1288. $queryBuilder->insert('pages')
  1289. ->values([
  1290. 'pid' => 0,
  1291. 'title' => $folderName,
  1292. 'dokType' => 254,
  1293. 'sorting' => 11264,
  1294. 'perms_userid' => 1,
  1295. 'perms_groupid' => 31,
  1296. 'perms_group' => 27,
  1297. ])
  1298. ->execute();
  1299. $uid = $queryBuilder->getConnection()->lastInsertId();
  1300. }
  1301. return $uid;
  1302. }
  1303. /**
  1304. * Insert a new row in the 'pages' table of the Typo3 DB
  1305. * and return its uid
  1306. *
  1307. * @param Organization $organization
  1308. * @param int $pid
  1309. * @param string $title
  1310. * @param string $slug
  1311. * @param string $template
  1312. * @param array $moreValues
  1313. * @return int
  1314. */
  1315. private function insertPage(Organization $organization,
  1316. int $pid,
  1317. string $title,
  1318. string $slug,
  1319. string $template = '',
  1320. array $moreValues = []
  1321. ) {
  1322. $defaultValues = [
  1323. 'pid' => $pid,
  1324. 'perms_groupid' => 3,
  1325. 'perms_user' => 27,
  1326. 'cruser_id' => 1,
  1327. 'dokType' => self::DOK_PAGE,
  1328. 'title' => $title,
  1329. 'slug' => $slug,
  1330. 'backend_layout' => 'flux__grid',
  1331. 'backend_layout_next_level' => 'flux__grid',
  1332. 'tx_opentalent_structure_id' => $organization->getId()
  1333. ];
  1334. if ($template) {
  1335. $defaultValues['tx_fed_page_controller_action'] = $template;
  1336. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1337. }
  1338. $values = array_merge($defaultValues, $moreValues);
  1339. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1340. $queryBuilder->insert('pages')
  1341. ->values($values)
  1342. ->execute();
  1343. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1344. $this->createdPagesIndex[$slug] = $uid;
  1345. return $uid;
  1346. }
  1347. /**
  1348. * Insert the root page of a new organization's website
  1349. * and return its uid
  1350. *
  1351. * @param Organization $organization
  1352. * @return int
  1353. */
  1354. private function insertRootPage(Organization $organization) {
  1355. return $this->insertPage(
  1356. $organization,
  1357. $this->getParentFolderUid(),
  1358. $organization->getName(),
  1359. '/',
  1360. self::TEMPLATE_HOME,
  1361. [
  1362. 'is_siteroot' => 1,
  1363. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1364. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1365. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1366. ]
  1367. );
  1368. }
  1369. /**
  1370. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1371. *
  1372. * @param int $pid
  1373. * @param string $cType
  1374. * @param string $bodyText
  1375. * @param int $colPos
  1376. * @param array $moreValues
  1377. */
  1378. private function insertContent(int $pid,
  1379. string $cType=self::CTYPE_TEXT,
  1380. string $bodyText = '',
  1381. int $colPos=0,
  1382. array $moreValues = []) {
  1383. $defaultValues = [
  1384. 'pid' => $pid,
  1385. 'cruser_id' => 1,
  1386. 'CType' => $cType,
  1387. 'colPos' => $colPos,
  1388. 'bodyText' => $bodyText
  1389. ];
  1390. $values = array_merge($defaultValues, $moreValues);
  1391. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1392. $queryBuilder->insert('tt_content')
  1393. ->values($values)
  1394. ->execute();
  1395. }
  1396. private function fetchOrganizationExtraData(int $organizationId) {
  1397. $cnn = new PDO(
  1398. "mysql:host=prod-back;dbname=opentalent",
  1399. 'dbcloner',
  1400. 'wWZ4hYcrmHLW2mUK',
  1401. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1402. );
  1403. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1404. $stmt = $cnn->prepare(
  1405. "SELECT o.id, o.name, o.facebook, o.twitter,
  1406. o.category, o.logo_id, p.logoDonorsMove
  1407. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1408. ON o.parameters_id = p.id
  1409. WHERE o.id=" . $organizationId . ";"
  1410. );
  1411. $stmt->execute();
  1412. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1413. $data = $stmt->fetch();
  1414. $stmt = $cnn->prepare(
  1415. "SELECT c.email
  1416. FROM opentalent.ContactPoint c
  1417. INNER JOIN opentalent.organization_contactpoint o
  1418. ON o.contactPoint_id = c.id
  1419. WHERE c.contactType = 'PRINCIPAL'
  1420. AND o.organization_id = " . $organizationId . ";"
  1421. );
  1422. $stmt->execute();
  1423. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1424. $data['email'] = $stmt->fetch()['email'];
  1425. $stmt = $cnn->prepare(
  1426. "SELECT n.name, n.logo, n.url
  1427. FROM opentalent.Network n
  1428. INNER JOIN
  1429. (opentalent.NetworkOrganization l
  1430. INNER JOIN opentalent.Organization o
  1431. ON l.organization_id = o.id)
  1432. ON l.network_id = n.id
  1433. WHERE l.endDate is NULL
  1434. AND o.id=" . $organizationId . ";"
  1435. );
  1436. $stmt->execute();
  1437. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1438. $data['network'] = $stmt->fetch();
  1439. $stmt = $cnn->prepare(
  1440. "SELECT p.username, a.id, s.product
  1441. FROM opentalent.Person p
  1442. INNER JOIN Access a ON p.id = a.person_id
  1443. INNER JOIN Settings s on a.organization_id = s.organization_id
  1444. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1445. );
  1446. $stmt->execute();
  1447. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1448. $data['admin'] = $stmt->fetch();
  1449. return $data;
  1450. }
  1451. /**
  1452. * Return the content of `sys_template`.`constants` of
  1453. * the website of the given organization
  1454. *
  1455. * @param int $organizationId
  1456. * @param array $organizationExtraData
  1457. * @return string
  1458. */
  1459. private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
  1460. return "plugin.tx_ottemplating {\n" .
  1461. " settings {\n" .
  1462. " organization {\n" .
  1463. " id = " . $organizationId . "\n" .
  1464. " name = " . $organizationExtraData['name'] . "\n" .
  1465. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1466. " email = " . $organizationExtraData['email'] . "\n" .
  1467. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1468. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1469. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1470. " }\n" .
  1471. " network {\n" .
  1472. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1473. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1474. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1475. " }\n" .
  1476. " }\n" .
  1477. "}";
  1478. }
  1479. /**
  1480. * Create the given directory, give its property to the www-data group and
  1481. * record it as a newly created dir (for an eventual rollback)
  1482. *
  1483. * @param string $dirPath
  1484. */
  1485. private function mkDir(string $dirPath) {
  1486. mkdir($dirPath);
  1487. $this->createdDirs[] = $dirPath;
  1488. chgrp($dirPath, 'www-data');
  1489. }
  1490. /**
  1491. * Write the given file with content, give its property to the www-data group and
  1492. * record it as a newly created file (for an eventual rollback)
  1493. *
  1494. * @param string $path
  1495. * @param string $content
  1496. */
  1497. private function writeFile(string $path, string $content) {
  1498. $f = fopen($path, "w");
  1499. try
  1500. {
  1501. fwrite($f, $content);
  1502. $this->createdFiles[] = $path;
  1503. chgrp($path, 'www-data');
  1504. } finally {
  1505. fclose($f);
  1506. }
  1507. }
  1508. /**
  1509. * Try to find the config file of the website in the less resource-consuming way
  1510. * and parse it.
  1511. *
  1512. * @param int $organizationId
  1513. * @param int $rootUid
  1514. * @return array Path of the configuration file and parsed configuration of the website
  1515. */
  1516. protected function findConfigFileAndContentFor(int $organizationId, int $rootUid) {
  1517. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1518. $candidates = scandir($configs_directory);
  1519. // try to filter by directory name
  1520. foreach ($candidates as $subdir) {
  1521. if (preg_match('/\.*_' . $organizationId . '$/', $subdir)) {
  1522. $filename = $configs_directory . $subdir . '/config.yaml';
  1523. $yamlConfig = Yaml::parseFile($filename);
  1524. if ($yamlConfig['rootPageId'] === $rootUid) {
  1525. return [$filename, $yamlConfig];
  1526. }
  1527. }
  1528. }
  1529. // it wasn't found the easy way, let's look to each file... :(
  1530. foreach ($candidates as $subdir) {
  1531. $yamlConfig = Yaml::parseFile($filename);
  1532. if ($yamlConfig['rootPageId'] === $rootUid) {
  1533. return [$filename, $yamlConfig];
  1534. }
  1535. }
  1536. return [null, []];
  1537. }
  1538. /**
  1539. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1540. * @param int $organizationId
  1541. * @param int $rootUid
  1542. * @return array Configuration of the website
  1543. */
  1544. protected function findConfigFor(int $organizationId, int $rootUid) {
  1545. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1546. return $pathAndConfig[1];
  1547. }
  1548. /**
  1549. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1550. * @param int $organizationId
  1551. * @param int $rootUid
  1552. * @return string Path of the config file of the given website
  1553. */
  1554. protected function findConfigFilePathFor(int $organizationId, int $rootUid) {
  1555. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1556. return $pathAndConfig[0];
  1557. }
  1558. /**
  1559. * Create or update the .../sites/.../config.yaml file of the given site
  1560. *
  1561. * @param int $organizationId
  1562. * @param int $rootUid
  1563. * @param string $domain
  1564. * @param bool $forceRecreate
  1565. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1566. */
  1567. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false) {
  1568. $existing = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1569. $configFilename = $existing[0];
  1570. $config = $existing[1];
  1571. $subdomain = explode('.', $domain)[0];
  1572. if (!$configFilename) {
  1573. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1574. $configFilename = $configDir . "/config.yaml";
  1575. $isNew = true;
  1576. if (file_exists($configFilename)) {
  1577. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1578. }
  1579. } else {
  1580. $configDir = dirname($configFilename);
  1581. $config['base'] = 'https://' . $domain;
  1582. $isNew = false;
  1583. }
  1584. if ($isNew || $forceRecreate) {
  1585. $config = ['base' => 'https://' . $domain,
  1586. 'baseVariants' => [
  1587. ['base' => $subdomain . '/',
  1588. 'condition' => 'applicationContext == "Development"']
  1589. ],
  1590. 'errorHandling' => [
  1591. ['errorCode' => '404',
  1592. 'errorHandler' => 'PHP',
  1593. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1594. ['errorCode' => '403',
  1595. 'errorHandler' => 'PHP',
  1596. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1597. ],
  1598. 'flux_content_types' => '',
  1599. 'flux_page_templates' => '',
  1600. 'languages' => [[
  1601. 'title' => 'Fr',
  1602. 'enabled' => True,
  1603. 'base' => '/',
  1604. 'typo3Language' => 'fr',
  1605. 'locale' => 'fr_FR',
  1606. 'iso-639-1' => 'fr',
  1607. 'navigationTitle' => 'Fr',
  1608. 'hreflang' => 'fr-FR',
  1609. 'direction' => 'ltr',
  1610. 'flag' => 'fr',
  1611. 'languageId' => '0',
  1612. ]],
  1613. 'rootPageId' => $rootUid,
  1614. 'routes' => []
  1615. ];
  1616. }
  1617. $yamlConfig = Yaml::dump($config, 99, 2);
  1618. if (!file_exists($configDir)) {
  1619. $this->mkDir($configDir);
  1620. }
  1621. GeneralUtility::writeFile($configFilename, $yamlConfig);
  1622. // Set the owner and mods, in case www-data is not the one who run this command
  1623. // @see https://www.php.net/manual/fr/function.stat.php
  1624. try {
  1625. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1626. chown($configFilename, $stats['4']);
  1627. chgrp($configFilename, $stats['5']);
  1628. chmod($configFilename, $stats['2']);
  1629. } catch (\TYPO3\CMS\Core\Error\Exception $e) {
  1630. }
  1631. // Flush cache:
  1632. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1633. $cacheSystem->remove('site-configuration');
  1634. $cacheSystem->remove('pseudo-sites');
  1635. }
  1636. /**
  1637. * Create the BE user for the website
  1638. * The user shall be already created in the Opentalent DB
  1639. *
  1640. * @param int $organizationId
  1641. * @param int $rootUid
  1642. * @param string $domain
  1643. * @param array $userData
  1644. * @return int
  1645. */
  1646. private function createBeUser(int $organizationId,
  1647. int $rootUid,
  1648. string $domain,
  1649. array $userData) {
  1650. if (!isset($userData['username'])) {
  1651. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1652. }
  1653. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1654. $randomStr = (new Random)->generateRandomHexString(20);
  1655. // get the existing filemounts
  1656. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1657. $queryBuilder
  1658. ->select('uid')
  1659. ->from('sys_filemounts')
  1660. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1661. $statement = $queryBuilder->execute();
  1662. $rows = $statement->fetchAll(3) ?: [];
  1663. $files = [];
  1664. foreach ($rows as $row) {
  1665. $files[] = $row[0];
  1666. }
  1667. $values = [
  1668. 'username' => $userData['username'],
  1669. 'password' => $randomStr,
  1670. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1671. 'deleted' => 0,
  1672. 'lang' => 'fr',
  1673. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1674. 'db_mountpoints' => $rootUid,
  1675. 'userMods' => 'file_FilelistList',
  1676. 'file_mountPoints' => join(',', $files),
  1677. 'options' => 2,
  1678. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1679. 'tx_opentalent_opentalentId' => $userData['id'],
  1680. 'tx_opentalent_organizationId' => $organizationId,
  1681. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1682. ];
  1683. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1684. $queryBuilder->insert('be_users')
  1685. ->values($values)
  1686. ->execute();
  1687. return $queryBuilder->getConnection()->lastInsertId();
  1688. }
  1689. /**
  1690. * Enable frontend editing for user
  1691. *
  1692. * @param int $adminUid
  1693. */
  1694. private function enableFeEditing(int $adminUid) {
  1695. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1696. $user = $BE_USER->getRawUserByUid($adminUid);
  1697. $BE_USER->user = $user;
  1698. $BE_USER->backendSetUC();
  1699. $BE_USER->uc['frontend_editing'] = 1;
  1700. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1701. $BE_USER->writeUC($BE_USER->uc);
  1702. }
  1703. }