SiteController.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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. // Is it the correct owner?
  909. if ($owner !== null && $page['perms_userid'] != $owner['uid']) {
  910. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  911. }
  912. if (!$page['is_siteroot']) {
  913. // is the parent page state (deleted, hidden, restricted) the same as this page?
  914. $parent = $pageIndex[$page['pid']];
  915. if ($parent['deleted'] && !$page['deleted']) {
  916. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  917. }
  918. if ($parent['hidden'] && !$page['hidden']) {
  919. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  920. }
  921. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  922. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  923. }
  924. }
  925. // an expected template was found, remove it from the list of expected
  926. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  927. !$page['deleted'] && !$page['hidden']) {
  928. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  929. }
  930. }
  931. foreach ($expected_templates as $template => $_) {
  932. $warnings[] = 'No page with template ' . $template;
  933. }
  934. return $warnings;
  935. }
  936. /**
  937. * Get the current status of the organization's website
  938. *
  939. * The result is an array of the form:
  940. *
  941. * [
  942. * 'organization_id' => int,
  943. * 'code' => int,
  944. * 'status' => int,
  945. * 'message' => string,
  946. * 'root_uid' => ?int,
  947. * 'site_title' => ?string,
  948. * ('warnings' => array)
  949. * ]
  950. *
  951. * If $statusOnly is true, the warnings entry won't be added
  952. *
  953. * The code value is among:
  954. *
  955. * - STATUS_NO_SUCH_WEBSITE
  956. * - STATUS_EXISTING
  957. * - STATUS_EXISTING_DELETED
  958. * - STATUS_EXISTING_HIDDEN
  959. * - STATUS_EXISTING_WITH_WARNINGS
  960. *
  961. * @param int $organizationId the organization's id whom site cache should be cleared
  962. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  963. * the website pages will be performed.
  964. * @return array
  965. */
  966. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): array
  967. {
  968. try {
  969. $rootUid = $this->findRootUidFor($organizationId);
  970. } catch (NoSuchWebsiteException $e) {
  971. return $this->buildStatusResult($organizationId, self::STATUS_NO_SUCH_WEBSITE);
  972. }
  973. if ($rootUid['deleted']) {
  974. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_DELETED, $rootUid);
  975. }
  976. if ($rootUid['hidden'] || ($rootUid['fe_group'] < 0)) {
  977. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_HIDDEN, $rootUid);
  978. }
  979. $warnings = null;
  980. if ($fullScan) {
  981. // ** Look for potential issues
  982. $warnings = $this->scanSite($organizationId, $rootUid);
  983. }
  984. return $this->buildStatusResult(
  985. $organizationId,
  986. $warnings ? self::STATUS_EXISTING_WITH_WARNINGS : self::STATUS_EXISTING,
  987. $rootUid,
  988. $warnings);
  989. }
  990. /**
  991. * Retrieve the Organization object from the repository and then,
  992. * from the Opentalent API
  993. * @param $organizationId
  994. * @return Organization
  995. */
  996. private function fetchOrganization($organizationId) {
  997. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  998. try {
  999. return $organizationRepository->findById($organizationId);
  1000. } catch (ApiRequestException $e) {
  1001. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1002. }
  1003. }
  1004. /**
  1005. * Try to find the root page uid of the organization's website and return it.
  1006. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1007. *
  1008. * @param $organizationId
  1009. * @return int
  1010. * @throws NoSuchWebsiteException
  1011. */
  1012. private function findRootUidFor($organizationId) {
  1013. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1014. $queryBuilder->getRestrictions()->removeAll();
  1015. $rootUid = $queryBuilder
  1016. ->select('uid')
  1017. ->from('pages')
  1018. ->where('is_siteroot=1')
  1019. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1020. ->execute()
  1021. ->fetchColumn(0);
  1022. if ($rootUid > 0) {
  1023. return $rootUid;
  1024. }
  1025. throw new NoSuchWebsiteException("The website of this organization can not be found");
  1026. }
  1027. /**
  1028. * Determine which folder-type Typo3 page should contain the new website
  1029. * CREATES IT if needed, and return its uid
  1030. *
  1031. * @return int
  1032. */
  1033. private function getParentFolderUid() {
  1034. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1035. $siteCount = $queryBuilder
  1036. ->count('uid')
  1037. ->from('pages')
  1038. ->where('is_siteroot=1')
  1039. ->execute()
  1040. ->fetchColumn(0);
  1041. $thousand = (int)(($siteCount + 1) / 1000);
  1042. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1043. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1044. $uid = $queryBuilder
  1045. ->select('uid')
  1046. ->from('pages')
  1047. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1048. ->andWhere('dokType=254')
  1049. ->execute()
  1050. ->fetchColumn(0);
  1051. if ($uid == null) {
  1052. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1053. $queryBuilder->insert('pages')
  1054. ->values([
  1055. 'pid' => 0,
  1056. 'title' => $folderName,
  1057. 'dokType' => 254,
  1058. 'sorting' => 11264,
  1059. 'perms_userid' => 1,
  1060. 'perms_groupid' => 31,
  1061. 'perms_group' => 27,
  1062. ])
  1063. ->execute();
  1064. $uid = $queryBuilder->getConnection()->lastInsertId();
  1065. }
  1066. return $uid;
  1067. }
  1068. /**
  1069. * Insert a new row in the 'pages' table of the Typo3 DB
  1070. * and return its uid
  1071. *
  1072. * @param Organization $organization
  1073. * @param int $pid
  1074. * @param string $title
  1075. * @param string $slug
  1076. * @param string $template
  1077. * @param array $moreValues
  1078. * @return int
  1079. */
  1080. private function insertPage(Organization $organization,
  1081. int $pid,
  1082. string $title,
  1083. string $slug,
  1084. string $template = '',
  1085. array $moreValues = []
  1086. ) {
  1087. $defaultValues = [
  1088. 'pid' => $pid,
  1089. 'perms_groupid' => 3,
  1090. 'perms_user' => 27,
  1091. 'cruser_id' => 1,
  1092. 'dokType' => self::DOK_PAGE,
  1093. 'title' => $title,
  1094. 'slug' => $slug,
  1095. 'backend_layout' => 'flux__grid',
  1096. 'backend_layout_next_level' => 'flux__grid',
  1097. 'tx_opentalent_structure_id' => $organization->getId()
  1098. ];
  1099. if ($template) {
  1100. $defaultValues['tx_fed_page_controller_action'] = $template;
  1101. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1102. }
  1103. $values = array_merge($defaultValues, $moreValues);
  1104. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1105. $queryBuilder->insert('pages')
  1106. ->values($values)
  1107. ->execute();
  1108. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1109. $this->createdPagesIndex[$slug] = $uid;
  1110. return $uid;
  1111. }
  1112. /**
  1113. * Insert the root page of a new organization's website
  1114. * and return its uid
  1115. *
  1116. * @param Organization $organization
  1117. * @return int
  1118. */
  1119. private function insertRootPage(Organization $organization) {
  1120. return $this->insertPage(
  1121. $organization,
  1122. $this->getParentFolderUid(),
  1123. $organization->getName(),
  1124. '/',
  1125. self::TEMPLATE_HOME,
  1126. [
  1127. 'is_siteroot' => 1,
  1128. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1129. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1130. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1131. ]
  1132. );
  1133. }
  1134. /**
  1135. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1136. *
  1137. * @param int $pid
  1138. * @param string $cType
  1139. * @param string $bodyText
  1140. * @param int $colPos
  1141. * @param array $moreValues
  1142. */
  1143. private function insertContent(int $pid,
  1144. string $cType=self::CTYPE_TEXT,
  1145. string $bodyText = '',
  1146. int $colPos=0,
  1147. array $moreValues = []) {
  1148. $defaultValues = [
  1149. 'pid' => $pid,
  1150. 'cruser_id' => 1,
  1151. 'CType' => $cType,
  1152. 'colPos' => $colPos,
  1153. 'bodyText' => $bodyText
  1154. ];
  1155. $values = array_merge($defaultValues, $moreValues);
  1156. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1157. $queryBuilder->insert('tt_content')
  1158. ->values($values)
  1159. ->execute();
  1160. }
  1161. private function fetchOrganizationExtraData(int $organizationId) {
  1162. $cnn = new PDO(
  1163. "mysql:host=prod-back;dbname=opentalent",
  1164. 'dbcloner',
  1165. 'wWZ4hYcrmHLW2mUK',
  1166. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1167. );
  1168. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1169. $stmt = $cnn->prepare(
  1170. "SELECT o.id, o.name, o.facebook, o.twitter,
  1171. o.category, o.logo_id, p.logoDonorsMove
  1172. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1173. ON o.parameters_id = p.id
  1174. WHERE o.id=" . $organizationId . ";"
  1175. );
  1176. $stmt->execute();
  1177. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1178. $data = $stmt->fetch();
  1179. $stmt = $cnn->prepare(
  1180. "SELECT c.email
  1181. FROM opentalent.ContactPoint c
  1182. INNER JOIN opentalent.organization_contactpoint o
  1183. ON o.contactPoint_id = c.id
  1184. WHERE c.contactType = 'PRINCIPAL'
  1185. AND o.organization_id = " . $organizationId . ";"
  1186. );
  1187. $stmt->execute();
  1188. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1189. $data['email'] = $stmt->fetch()['email'];
  1190. $stmt = $cnn->prepare(
  1191. "SELECT n.name, n.logo, n.url
  1192. FROM opentalent.Network n
  1193. INNER JOIN
  1194. (opentalent.NetworkOrganization l
  1195. INNER JOIN opentalent.Organization o
  1196. ON l.organization_id = o.id)
  1197. ON l.network_id = n.id
  1198. WHERE l.endDate is NULL
  1199. AND o.id=" . $organizationId . ";"
  1200. );
  1201. $stmt->execute();
  1202. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1203. $data['network'] = $stmt->fetch();
  1204. $stmt = $cnn->prepare(
  1205. "SELECT p.username, a.id, s.product
  1206. FROM opentalent.Person p
  1207. INNER JOIN Access a ON p.id = a.person_id
  1208. INNER JOIN Settings s on a.organization_id = s.organization_id
  1209. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1210. );
  1211. $stmt->execute();
  1212. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1213. $data['admin'] = $stmt->fetch();
  1214. return $data;
  1215. }
  1216. /**
  1217. * Return the content of `sys_template`.`constants` of
  1218. * the website of the given organization
  1219. *
  1220. * @param int $organizationId
  1221. * @param array $organizationExtraData
  1222. * @return string
  1223. */
  1224. private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
  1225. return "plugin.tx_ottemplating {\n" .
  1226. " settings {\n" .
  1227. " organization {\n" .
  1228. " id = " . $organizationId . "\n" .
  1229. " name = " . $organizationExtraData['name'] . "\n" .
  1230. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1231. " email = " . $organizationExtraData['email'] . "\n" .
  1232. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1233. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1234. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1235. " }\n" .
  1236. " network {\n" .
  1237. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1238. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1239. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1240. " }\n" .
  1241. " }\n" .
  1242. "}";
  1243. }
  1244. /**
  1245. * Create the given directory, give its property to the www-data group and
  1246. * record it as a newly created dir (for an eventual rollback)
  1247. *
  1248. * @param string $dirPath
  1249. */
  1250. private function mkDir(string $dirPath) {
  1251. mkdir($dirPath);
  1252. $this->createdDirs[] = $dirPath;
  1253. chgrp($dirPath, 'www-data');
  1254. }
  1255. /**
  1256. * Write the given file with content, give its property to the www-data group and
  1257. * record it as a newly created file (for an eventual rollback)
  1258. *
  1259. * @param string $path
  1260. * @param string $content
  1261. */
  1262. private function writeFile(string $path, string $content) {
  1263. $f = fopen($path, "w");
  1264. try
  1265. {
  1266. fwrite($f, $content);
  1267. $this->createdFiles[] = $path;
  1268. chgrp($path, 'www-data');
  1269. } finally {
  1270. fclose($f);
  1271. }
  1272. }
  1273. /**
  1274. * Write the .../sites/.../config.yml file of the given site
  1275. *
  1276. * @param int $organizationId
  1277. * @param int $rootUid
  1278. * @param string $domain
  1279. */
  1280. private function writeConfigFile(int $organizationId, int $rootUid, string $domain) {
  1281. $subdomain = explode('.', $domain)[0];
  1282. $config_dir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1283. $config_filename = $config_dir . "/config.yaml";
  1284. if (file_exists($config_filename)) {
  1285. throw new \RuntimeException("A file named " . $config_filename . " already exists. Abort.");
  1286. }
  1287. $config = ['base' => 'https://' . $domain,
  1288. 'baseVariants'=>[
  1289. ['base' => $subdomain . '/',
  1290. 'condition' => 'applicationContext == "Development"']
  1291. ],
  1292. 'errorHandling'=>[
  1293. ['errorCode'=>'404',
  1294. 'errorHandler'=>'PHP',
  1295. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1296. ['errorCode'=>'403',
  1297. 'errorHandler'=>'PHP',
  1298. 'errorPhpClassFQCN'=>'Opentalent\OtTemplating\Page\ErrorHandler'],
  1299. ],
  1300. 'flux_content_types'=>'',
  1301. 'flux_page_templates'=>'',
  1302. 'languages'=>[[
  1303. 'title'=>'Fr',
  1304. 'enabled'=>True,
  1305. 'base'=>'/',
  1306. 'typo3Language'=>'fr',
  1307. 'locale'=>'fr_FR',
  1308. 'iso-639-1'=>'fr',
  1309. 'navigationTitle'=>'Fr',
  1310. 'hreflang'=>'fr-FR',
  1311. 'direction'=>'ltr',
  1312. 'flag'=>'fr',
  1313. 'languageId'=>'0',
  1314. ]],
  1315. 'rootPageId'=>$rootUid,
  1316. 'routes'=>[]
  1317. ];
  1318. $yamlConfig = Yaml::dump($config, 99, 2);
  1319. if (!file_exists($config_dir)) {
  1320. $this->mkDir($config_dir);
  1321. }
  1322. GeneralUtility::writeFile($config_filename, $yamlConfig);
  1323. // Set the owner and mods, in case www-data is not the one who run this command
  1324. // @see https://www.php.net/manual/fr/function.stat.php
  1325. try {
  1326. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1327. chown($config_filename, $stats['4']);
  1328. chgrp($config_filename, $stats['5']);
  1329. chmod($config_filename, $stats['2']);
  1330. } catch (\TYPO3\CMS\Core\Error\Exception $e) {
  1331. }
  1332. // Flush cache:
  1333. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1334. $cacheSystem->remove('site-configuration');
  1335. $cacheSystem->remove('pseudo-sites');
  1336. }
  1337. /**
  1338. * Create the BE user for the website
  1339. * The user shall be already created in the Opentalent DB
  1340. *
  1341. * @param int $organizationId
  1342. * @param int $rootUid
  1343. * @param string $domain
  1344. * @param array $userData
  1345. * @return int
  1346. */
  1347. private function createBeUser(int $organizationId,
  1348. int $rootUid,
  1349. string $domain,
  1350. array $userData) {
  1351. if (!isset($userData['username'])) {
  1352. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1353. }
  1354. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1355. $randomStr = (new Random)->generateRandomHexString(20);
  1356. // get the existing filemounts
  1357. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1358. $queryBuilder
  1359. ->select('uid')
  1360. ->from('sys_filemounts')
  1361. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1362. $statement = $queryBuilder->execute();
  1363. $rows = $statement->fetchAll(3) ?: [];
  1364. $files = [];
  1365. foreach ($rows as $row) {
  1366. $files[] = $row[0];
  1367. }
  1368. $values = [
  1369. 'username' => $userData['username'],
  1370. 'password' => $randomStr,
  1371. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1372. 'deleted' => 0,
  1373. 'lang' => 'fr',
  1374. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1375. 'db_mountpoints' => $rootUid,
  1376. 'userMods' => 'file_FilelistList',
  1377. 'file_mountPoints' => join(',', $files),
  1378. 'options' => 2,
  1379. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1380. 'tx_opentalent_opentalentId' => $userData['id'],
  1381. 'tx_opentalent_organizationId' => $organizationId,
  1382. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1383. ];
  1384. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1385. $queryBuilder->insert('be_users')
  1386. ->values($values)
  1387. ->execute();
  1388. return $queryBuilder->getConnection()->lastInsertId();
  1389. }
  1390. /**
  1391. * Enable frontend editing for user
  1392. *
  1393. * @param int $adminUid
  1394. */
  1395. private function enableFeEditing(int $adminUid) {
  1396. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1397. $user = $BE_USER->getRawUserByUid($adminUid);
  1398. $BE_USER->user = $user;
  1399. $BE_USER->backendSetUC();
  1400. $BE_USER->uc['frontend_editing'] = 1;
  1401. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1402. $BE_USER->writeUC($BE_USER->uc);
  1403. }
  1404. }