SiteController.php 63 KB

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