SiteController.php 58 KB

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