SiteController.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use Opentalent\OtTemplating\Domain\Model\Organization;
  4. use Opentalent\OtTemplating\Domain\Repository\OrganizationRepository;
  5. use Opentalent\OtTemplating\Exception\ApiRequestException;
  6. use Opentalent\OtTemplating\Page\OtPageRepository;
  7. use PDO;
  8. use Psr\Log\LoggerAwareInterface;
  9. use Symfony\Component\Yaml\Yaml;
  10. use TYPO3\CMS\Core\Crypto\Random;
  11. use TYPO3\CMS\Core\Database\ConnectionPool;
  12. use TYPO3\CMS\Core\Utility\GeneralUtility;
  13. use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
  14. use TYPO3\CMS\Extbase\Object\ObjectManager;
  15. /**
  16. * The SiteController implements some admin-only operations
  17. * on Typo3 websites, like creation or update.
  18. */
  19. class SiteController extends ActionController
  20. {
  21. // Templates names
  22. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  23. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  24. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  25. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  26. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  27. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  28. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  29. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  30. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  31. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  32. const TEMPLATE_E404 = "OpenTalent.OtTemplating->e404";
  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. /**
  59. * Doctrine connection pool
  60. * @var object|LoggerAwareInterface|\TYPO3\CMS\Core\SingletonInterface
  61. */
  62. private $cnnPool;
  63. /**
  64. * Index of the pages created during the process
  65. * >> [slug => uid]
  66. * @var array
  67. */
  68. private $createdPagesIndex;
  69. /**
  70. * List of the directories created in the process (for rollback purposes)
  71. * @var array
  72. */
  73. private $createdDirs;
  74. /**
  75. * List of the files created in the process (for rollback purposes)
  76. * @var array
  77. */
  78. private $createdFiles;
  79. public function __construct()
  80. {
  81. parent::__construct();
  82. $this->cnnPool = GeneralUtility::makeInstance(ConnectionPool::class);
  83. $this->createdPagesIndex = [];
  84. $this->createdDirs = [];
  85. $this->createdFiles = [];
  86. }
  87. /**
  88. * Creates a new website for the given organization, and
  89. * returns the root page uid of the newly created site
  90. *
  91. * @param int $organizationId
  92. * @return int Uid of the root page of the newly created website
  93. * @throws \RuntimeException|\Exception
  94. */
  95. public function createSiteAction(int $organizationId) {
  96. $organization = $this->fetchOrganization($organizationId);
  97. // ** Test the existence of a website with this name and or organization id
  98. // Is there a site with this organization's name?
  99. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  100. $queryBuilder
  101. ->select('uid')
  102. ->from('pages')
  103. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($organization->getName())))
  104. ->andWhere('is_siteroot=1');
  105. $statement = $queryBuilder->execute();
  106. if ($statement->rowCount() > 0) {
  107. throw new \RuntimeException('A website with this name already exists: ' . $organization->getName());
  108. }
  109. // Is there a site with this organization's id?
  110. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  111. $statement = $queryBuilder
  112. ->select('uid')
  113. ->from('pages')
  114. ->where($queryBuilder->expr()->eq('tx_opentalent_structure_id', $queryBuilder->createNamedParameter($organization->getId())))
  115. ->andWhere('is_siteroot=1')
  116. ->execute();
  117. if ($statement->rowCount() > 0) {
  118. throw new \RuntimeException("A website with this organization's id already exists: " . $organization->getName());
  119. }
  120. // ** Create the new website
  121. // start transactions
  122. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  123. // keep tracks of the created folders and files to be able to remove them during a rollback
  124. try {
  125. // Create the site pages:
  126. // > Root page
  127. $rootUid = $this->insertRootPage($organization);
  128. // > 'Accueil' shortcut
  129. $this->insertPage(
  130. $organization,
  131. $rootUid,
  132. 'Accueil',
  133. '/accueil',
  134. '',
  135. [
  136. 'dokType' => self::DOK_SHORTCUT,
  137. 'shortcut' => $rootUid
  138. ]
  139. );
  140. // > 'Présentation' page
  141. $this->insertPage(
  142. $organization,
  143. $rootUid,
  144. 'Présentation',
  145. '/presentation'
  146. );
  147. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  148. $this->insertPage(
  149. $organization,
  150. $this->createdPagesIndex['/presentation'],
  151. 'Qui sommes nous?',
  152. '/qui-sommes-nous',
  153. '',
  154. ['hidden' => 1]
  155. );
  156. // > 'Présentation > Les adhérents' page
  157. $this->insertPage(
  158. $organization,
  159. $this->createdPagesIndex['/presentation'],
  160. 'Les adhérents',
  161. '/les-adherents',
  162. self::TEMPLATE_MEMBERS
  163. );
  164. // > 'Présentation > Les membres du CA' page
  165. $this->insertPage(
  166. $organization,
  167. $this->createdPagesIndex['/presentation'],
  168. 'Les membres du CA',
  169. '/les-membres-du-ca',
  170. self::TEMPLATE_MEMBERSCA
  171. );
  172. // > 'Présentation > Historique' page (hidden by default)
  173. $this->insertPage(
  174. $organization,
  175. $this->createdPagesIndex['/presentation'],
  176. 'Historique',
  177. '/historique',
  178. '',
  179. ['hidden' => 1]
  180. );
  181. // > 'Actualités' page (hidden by default)
  182. $this->insertPage(
  183. $organization,
  184. $rootUid,
  185. 'Actualités',
  186. '/actualites',
  187. self::TEMPLATE_NEWS
  188. );
  189. // > 'Saison en cours' page
  190. $this->insertPage(
  191. $organization,
  192. $rootUid,
  193. 'Saison en cours',
  194. '/saison-en-cours'
  195. );
  196. // > 'Saison en cours > Les évènements' page
  197. $this->insertPage(
  198. $organization,
  199. $this->createdPagesIndex['/saison-en-cours'],
  200. 'Les évènements',
  201. '/les-evenements',
  202. self::TEMPLATE_EVENTS
  203. );
  204. // > 'Vie interne' page (restricted, hidden by default)
  205. $this->insertPage(
  206. $organization,
  207. $rootUid,
  208. 'Vie interne',
  209. '/vie-interne',
  210. '',
  211. [
  212. 'hidden' => 1,
  213. 'fe_group' => -2
  214. ]
  215. );
  216. // > 'Footer' page (not in the menu)
  217. $this->insertPage(
  218. $organization,
  219. $rootUid,
  220. 'Footer',
  221. '/footer',
  222. '',
  223. [
  224. 'dokType' => self::DOK_FOLDER,
  225. 'nav_hide' => 1
  226. ]
  227. );
  228. // > 'Footer > Contact' page
  229. $this->insertPage(
  230. $organization,
  231. $this->createdPagesIndex['/footer'],
  232. 'Contact',
  233. '/contact',
  234. self::TEMPLATE_CONTACT
  235. );
  236. // > 'Footer > Plan du site' page
  237. $this->insertPage(
  238. $organization,
  239. $this->createdPagesIndex['/footer'],
  240. 'Plan du site',
  241. '/plan-du-site'
  242. );
  243. // > 'Footer > Mentions légales' page
  244. $this->insertPage(
  245. $organization,
  246. $this->createdPagesIndex['/footer'],
  247. 'Mentions légales',
  248. '/mentions-legales'
  249. );
  250. // > 'Page introuvable' page (not in the menu, read-only)
  251. $this->insertPage(
  252. $organization,
  253. $rootUid,
  254. 'Page introuvable',
  255. '/page-introuvable',
  256. self::TEMPLATE_E404,
  257. [
  258. 'nav_hide' => 1,
  259. 'no_search' => 1
  260. ]
  261. );
  262. // Add content to these pages
  263. // >> root page content
  264. $this->insertContent(
  265. $rootUid,
  266. self::CTYPE_TEXTPIC,
  267. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  268. 0
  269. );
  270. // >> page 'qui sommes nous?'
  271. $this->insertContent(
  272. $this->createdPagesIndex['/qui-sommes-nous'],
  273. self::CTYPE_TEXT,
  274. 'Qui sommes nous ...',
  275. 0
  276. );
  277. // >> page 'historique'
  278. $this->insertContent(
  279. $this->createdPagesIndex['/historique'],
  280. self::CTYPE_TEXT,
  281. "Un peu d'histoire ...",
  282. 0
  283. );
  284. // >> page 'plan du site'
  285. $this->insertContent(
  286. $this->createdPagesIndex['/plan-du-site'],
  287. self::CTYPE_SITEMAP
  288. );
  289. // >> page 'mentions légales'
  290. $this->insertContent(
  291. $this->createdPagesIndex['/mentions-legales'],
  292. self::CTYPE_TEXT,
  293. '<p style="margin-bottom: 0"><b>Mentions Légales</b></p>',
  294. 0
  295. );
  296. // Build and update the domain
  297. $domain = $organization->getSubDomain() . '.opentalent.fr';
  298. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_domain');
  299. $queryBuilder->insert('sys_domain')
  300. ->values([
  301. 'pid' => $rootUid,
  302. 'domainName' => $domain
  303. ])
  304. ->execute();
  305. // update sys_template
  306. $constants = $this->genTemplateConstants($organizationId);
  307. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  308. $queryBuilder->insert('sys_template')
  309. ->values([
  310. 'pid' => $rootUid,
  311. 'title' => $organization->getName(),
  312. 'sitetitle' => $organization->getName(),
  313. 'root' => 1,
  314. 'clear' => 3,
  315. 'config' => "config = 'config.frontend_editing = 1",
  316. 'include_static_file' => 'EXT:fluid_styled_content/Configuration/TypoScript/,EXT:fluid_styled_content/Configuration/TypoScript/Styling/,EXT:form/Configuration/TypoScript/,EXT:news/Configuration/TypoScript,EXT:frontend_editing/Configuration/TypoScript,EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9,EXT:ot_templating/Configuration/TypoScript',
  317. 'constants' => $constants
  318. ])
  319. ->execute();
  320. // Create the site config.yaml file
  321. $this->writeConfigFile($organizationId, $rootUid, $domain);
  322. // Create the BE user
  323. // -- BE user will be auto-updated by the ot_connect extension --
  324. // Create the user_upload directory and update the sys_filemounts table
  325. $uploadRelPath = "/user_upload/" . $organizationId;
  326. $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
  327. if (file_exists($uploadDir)) {
  328. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  329. }
  330. $this->mkDir($uploadDir);
  331. $this->mkDir($uploadDir . '/images');
  332. $this->mkDir($uploadDir . '/Forms');
  333. // Insert the filemounts points (sys_filemounts)
  334. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  335. $queryBuilder->insert('sys_filemounts')
  336. ->values([
  337. 'title' => 'Documents',
  338. 'path' => $uploadRelPath . '/images',
  339. 'base' => 1
  340. ])
  341. ->execute();
  342. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  343. $queryBuilder->insert('sys_filemounts')
  344. ->values([
  345. 'title' => 'Forms_' . $organizationId,
  346. 'path' => $uploadRelPath . '/Forms',
  347. 'base' => 1
  348. ])
  349. ->execute();
  350. // Create the BE User
  351. $beUid = $this->createBeUser($organizationId, $rootUid, $domain);
  352. // Give the keys of the website to this user (makes him the owner)
  353. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  354. foreach($this->createdPagesIndex as $slug => $uid) {
  355. $queryBuilder
  356. ->update('pages')
  357. ->where($queryBuilder->expr()->eq('uid', $uid))
  358. ->set('perms_userid', $beUid)
  359. ->execute();
  360. }
  361. // Try to commit the result
  362. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  363. if (!$commitSuccess) {
  364. throw new \RuntimeException('Something went wrong while commiting the result');
  365. }
  366. return $rootUid;
  367. } catch(\Exception $e) {
  368. // rollback
  369. $this->cnnPool->getConnectionByName('Default')->rollback();
  370. // remove created files and dirs
  371. foreach (array_reverse($this->createdFiles) as $filename) {
  372. unlink($filename);
  373. }
  374. $this->createdFiles = [];
  375. foreach (array_reverse($this->createdDirs) as $dirname) {
  376. rmdir($dirname);
  377. }
  378. $this->createdDirs = [];
  379. throw $e;
  380. }
  381. }
  382. /**
  383. * Update the `sys_template`.`constants` field of the given
  384. * organization's website with the data fetched from the opentalent DB.
  385. *
  386. * @param int $organizationId
  387. * @return int
  388. */
  389. public function updateSiteConstantsAction(int $organizationId) {
  390. $rootUid = $this->findRootUidFor($organizationId);
  391. $constants = $this->genTemplateConstants($organizationId);
  392. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  393. $queryBuilder
  394. ->update('sys_template')
  395. ->set('constants', $constants)
  396. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  397. ->execute();
  398. return $rootUid;
  399. }
  400. /**
  401. * Delete the website with all its pages, contents and related records
  402. *
  403. * If the hard parameter is false, the records' `deleted` field will be set to true and
  404. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  405. *
  406. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  407. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  408. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  409. *
  410. * @param int $organizationId
  411. * @param bool $hard
  412. * @return int
  413. * @throws \Exception
  414. */
  415. public function deleteSiteAction(int $organizationId, bool $hard=false) {
  416. $rootUid = $this->findRootUidFor($organizationId);
  417. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  418. $isDeleted = $queryBuilder
  419. ->select('deleted')
  420. ->from('pages')
  421. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  422. ->execute()
  423. ->fetchColumn(0) == 1;
  424. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  425. if ($hard && !file_exists($confirm_file)) {
  426. throw new \RuntimeException(
  427. "You are going to completely delete the website with root uid " . $rootUid .
  428. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  429. $confirm_file . "', and launch this command again."
  430. );
  431. }
  432. // start transactions
  433. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  434. // keep track of renamed file for an eventual rollback
  435. $renamed = [];
  436. try {
  437. $repository = new OtPageRepository();
  438. $pages = $repository->getAllSubpagesForPage($rootUid);
  439. foreach($pages as $page) {
  440. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  441. $this->delete('pages', 'uid', $page['uid'], $hard);
  442. }
  443. $this->delete('tt_content', 'pid', $rootUid, $hard);
  444. $this->delete('pages', 'uid', $rootUid, $hard);
  445. $this->delete('sys_template', 'pid', $rootUid, $hard);
  446. // remove filemounts
  447. $this->delete('sys_filemounts',
  448. 'path',
  449. "'/user_upload/" . $organizationId . "/images'",
  450. $hard);
  451. $this->delete('sys_filemounts',
  452. 'path',
  453. "'/user_upload/" . $organizationId . "/Forms'",
  454. $hard);
  455. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  456. // Look up for the config.yaml file of the website
  457. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  458. $configYamlFile = "";
  459. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  460. if (!$isDeleted) {
  461. $yamlFile = $subdir . '/config.yaml';
  462. } else {
  463. $yamlFile = $subdir . '/config.yaml.deleted';
  464. }
  465. if (is_file($yamlFile)) {
  466. $conf = Yaml::parseFile($yamlFile);
  467. if ($conf['rootPageId'] == $rootUid) {
  468. $configYamlFile = $yamlFile;
  469. break;
  470. }
  471. }
  472. }
  473. if (!$isDeleted) {
  474. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  475. } else {
  476. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  477. }
  478. // If hard deletion, verify that upload dirs are empty
  479. if ($hard && is_file($uploadDir)) {
  480. foreach (scandir($uploadDir) as $subdir) {
  481. if (!is_dir($subdir)) {
  482. throw new \RuntimeException(
  483. 'The directory ' . $uploadDir . ' contains non-directory files' .
  484. ', this humble script prefers not to take care of them automatically. Cancel.');
  485. }
  486. if (is_readable($subdir) && count(scandir($subdir)) > 0) {
  487. throw new \RuntimeException(
  488. 'The directory ' . $subdir . ' is not empty, ' .
  489. 'this humble script prefers not to take care of them automatically. Cancel.');
  490. }
  491. }
  492. }
  493. // If soft deletion, check that no deleted file or directory exist
  494. if (!$hard) {
  495. $toRename = [];
  496. if (!$hard) {
  497. if (is_file($configYamlFile)) {
  498. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  499. }
  500. if (is_dir($uploadDir)) {
  501. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  502. }
  503. }
  504. foreach ($toRename as $initialPath => $newPath) {
  505. if (is_file($newPath)) {
  506. throw new \RuntimeException(
  507. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  508. }
  509. }
  510. }
  511. // Delete or rename files and dirs
  512. if ($hard) {
  513. if (is_file($configYamlFile)) {
  514. unlink($configYamlFile);
  515. }
  516. if (is_dir(dirname($configYamlFile))) {
  517. rmdir(dirname($configYamlFile));
  518. }
  519. if (is_dir(dirname($uploadDir . 'images'))) {
  520. rmdir($uploadDir . 'images');
  521. }
  522. if (is_dir(dirname($uploadDir . 'Forms'))) {
  523. rmdir($uploadDir . 'Forms');
  524. }
  525. if (is_dir(dirname($uploadDir))) {
  526. rmdir($uploadDir);
  527. }
  528. } else {
  529. $renamed = [];
  530. foreach ($toRename as $initialPath => $newPath) {
  531. rename($initialPath, $newPath);
  532. $renamed[$initialPath] = $newPath;
  533. }
  534. }
  535. // Try to commit the result (before any eventual file deletion or renaming)
  536. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  537. if (!$commitSuccess) {
  538. throw new \RuntimeException('Something went wrong while commiting the result');
  539. }
  540. return $rootUid;
  541. } catch(\Exception $e) {
  542. // rollback
  543. $this->cnnPool->getConnectionByName('Default')->rollback();
  544. if ($hard) {
  545. foreach ($renamed as $initialPath => $newPath) {
  546. rename($newPath, $initialPath);
  547. }
  548. }
  549. if (file_exists($confirm_file)) {
  550. unlink($confirm_file);
  551. }
  552. throw $e;
  553. }
  554. }
  555. /**
  556. * @param string $table
  557. * @param string $whereKey
  558. * @param $whereValue
  559. * @param int $hard
  560. */
  561. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  562. $queryBuilder = $this->cnnPool->getQueryBuilderForTable($table);
  563. if (!$hard) {
  564. $queryBuilder
  565. ->update($table)
  566. ->set('deleted', 1)
  567. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  568. ->execute();
  569. } else {
  570. $queryBuilder
  571. ->delete($table)
  572. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  573. ->execute();
  574. }
  575. }
  576. public function undeleteSiteAction(int $organizationId) {
  577. $rootUid = $this->findRootUidFor($organizationId);
  578. // start transactions
  579. $this->cnnPool->getConnectionByName('Default')->beginTransaction();
  580. // keep track of renamed file for an eventual rollback
  581. $renamed = [];
  582. try {
  583. $repository = new OtPageRepository();
  584. $pages = $repository->getAllSubpagesForPage($rootUid);
  585. foreach($pages as $page) {
  586. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  587. $queryBuilder
  588. ->update('tt_content')
  589. ->set('deleted', 0)
  590. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  591. ->execute();
  592. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  593. $queryBuilder
  594. ->update('pages')
  595. ->set('deleted', 0)
  596. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  597. ->execute();
  598. }
  599. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  600. $queryBuilder
  601. ->update('tt_content')
  602. ->set('deleted', 0)
  603. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  604. ->execute();
  605. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  606. $queryBuilder
  607. ->update('pages')
  608. ->set('deleted', 0)
  609. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  610. ->execute();
  611. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_template');
  612. $queryBuilder
  613. ->update('sys_template')
  614. ->set('deleted', 0)
  615. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  616. ->execute();
  617. // remove filemounts
  618. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  619. $queryBuilder
  620. ->update('sys_filemounts')
  621. ->set('deleted', 0)
  622. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  623. ->execute();
  624. $queryBuilder
  625. ->update('sys_filemounts')
  626. ->set('deleted', 0)
  627. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  628. ->execute();
  629. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  630. $queryBuilder
  631. ->update('be_users')
  632. ->set('deleted', 0)
  633. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  634. ->execute();
  635. // Look up for the config.yaml file of the website
  636. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  637. $configYamlFile = "";
  638. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  639. $yamlFile = $subdir . '/config.yaml.deleted';
  640. if (is_file($yamlFile)) {
  641. $conf = Yaml::parseFile($yamlFile);
  642. if ($conf['rootPageId'] == $rootUid) {
  643. $configYamlFile = $yamlFile;
  644. break;
  645. }
  646. }
  647. }
  648. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  649. $toRename = [];
  650. if (is_file($configYamlFile)) {
  651. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  652. }
  653. if (is_dir($uploadDir)) {
  654. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  655. }
  656. foreach ($toRename as $initialPath => $newPath) {
  657. if (is_file($newPath)) {
  658. throw new \RuntimeException(
  659. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  660. }
  661. }
  662. $renamed = [];
  663. foreach ($toRename as $initialPath => $newPath) {
  664. rename($initialPath, $newPath);
  665. $renamed[$initialPath] = $newPath;
  666. }
  667. // Try to commit the result
  668. $commitSuccess = $this->cnnPool->getConnectionByName('Default')->commit();
  669. if (!$commitSuccess) {
  670. throw new \RuntimeException('Something went wrong while commiting the result');
  671. }
  672. return $rootUid;
  673. } catch(\Exception $e) {
  674. // rollback
  675. $this->cnnPool->getConnectionByName('Default')->rollback();
  676. foreach ($renamed as $initialPath => $newPath) {
  677. rename($newPath, $initialPath);
  678. }
  679. throw $e;
  680. }
  681. }
  682. /**
  683. * Retrieve the Organization object from the repository and then,
  684. * from the Opentalent API
  685. * @param $organizationId
  686. * @return Organization
  687. */
  688. private function fetchOrganization($organizationId) {
  689. $manager = GeneralUtility::makeInstance(ObjectManager::class);
  690. $organizationRepository = GeneralUtility::makeInstance(
  691. OrganizationRepository::class,
  692. $manager
  693. );
  694. try {
  695. return $organizationRepository->findById($organizationId);
  696. } catch (ApiRequestException $e) {
  697. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  698. }
  699. }
  700. /**
  701. * Try to find the root page uid of the organization's website and return it.
  702. *
  703. * @param $organizationId
  704. * @return int
  705. */
  706. private function findRootUidFor($organizationId) {
  707. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  708. $queryBuilder->getRestrictions()->removeAll();
  709. $rootUid = $queryBuilder
  710. ->select('uid')
  711. ->from('pages')
  712. ->where('is_siteroot=1')
  713. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  714. ->execute()
  715. ->fetchColumn(0);
  716. if ($rootUid > 0) {
  717. return $rootUid;
  718. }
  719. $organization = $this->fetchOrganization($organizationId);
  720. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  721. $rootUid = $queryBuilder
  722. ->count('uid')
  723. ->from('pages')
  724. ->where('is_siteroot=1')
  725. ->andWhere($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($organization->getName())))
  726. ->andWhere('tx_opentalent_structure_id=null')
  727. ->execute()
  728. ->fetchColumn(0);
  729. if ($rootUid > 0) {
  730. return $rootUid;
  731. }
  732. throw new \RuntimeException("The website of this organization can not be found");
  733. }
  734. /**
  735. * Determine which folder-type Typo3 page should contain the new website
  736. * CREATES IT if needed, and return its uid
  737. *
  738. * @return int
  739. */
  740. private function getParentFolderUid() {
  741. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  742. $siteCount = $queryBuilder
  743. ->count('uid')
  744. ->from('pages')
  745. ->where('is_siteroot=1')
  746. ->execute()
  747. ->fetchColumn(0);
  748. $thousand = (int)(($siteCount + 1) / 1000);
  749. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  750. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  751. $uid = $queryBuilder
  752. ->select('uid')
  753. ->from('pages')
  754. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  755. ->andWhere('dokType=254')
  756. ->execute()
  757. ->fetchColumn(0);
  758. if ($uid == null) {
  759. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  760. $queryBuilder->insert('pages')
  761. ->values([
  762. 'pid' => 0,
  763. 'title' => $folderName,
  764. 'dokType' => 254,
  765. 'sorting' => 11264,
  766. 'perms_userid' => 1,
  767. 'perms_groupid' => 31,
  768. 'perms_group' => 27,
  769. ])
  770. ->execute();
  771. $uid = $queryBuilder->getConnection()->lastInsertId();
  772. }
  773. return $uid;
  774. }
  775. /**
  776. * Insert a new row in the 'pages' table of the Typo3 DB
  777. *
  778. * @param Organization $organization
  779. * @param int $pid
  780. * @param string $title
  781. * @param string $slug
  782. * @param string $template
  783. * @param array $moreValues
  784. * @return string
  785. */
  786. private function insertPage(Organization $organization,
  787. int $pid,
  788. string $title,
  789. string $slug,
  790. string $template = '',
  791. array $moreValues = []
  792. ) {
  793. $defaultValues = [
  794. 'pid' => $pid,
  795. 'perms_groupid' => 3,
  796. 'perms_user' => 27,
  797. 'cruser_id' => 1,
  798. 'dokType' => self::DOK_PAGE,
  799. 'title' => $title,
  800. 'slug' => $slug,
  801. 'backend_layout' => 'flux__grid',
  802. 'backend_layout_next_level' => 'flux__grid',
  803. 'tx_opentalent_structure_id' => $organization->getId()
  804. ];
  805. if ($template) {
  806. $defaultValues['tx_fed_page_controller_action'] = $template;
  807. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  808. }
  809. $values = array_merge($defaultValues, $moreValues);
  810. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('pages');
  811. $queryBuilder->insert('pages')
  812. ->values($values)
  813. ->execute();
  814. $uid = $queryBuilder->getConnection()->lastInsertId();
  815. $this->createdPagesIndex[$slug] = $uid;
  816. return $uid;
  817. }
  818. /**
  819. * Insert the root page of a new organization's website
  820. *
  821. * @param Organization $organization
  822. * @return string
  823. */
  824. private function insertRootPage(Organization $organization) {
  825. return $this->insertPage(
  826. $organization,
  827. $this->getParentFolderUid(),
  828. $organization->getName(),
  829. '/',
  830. self::TEMPLATE_HOME,
  831. [
  832. 'is_siteroot' => 1,
  833. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  834. 'tx_opentalent_template' => self::DEFAULT_THEME,
  835. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  836. ]
  837. );
  838. }
  839. /**
  840. * Insert a new row in the 'tt_content' table of the Typo3 DB
  841. *
  842. * @param int $pid
  843. * @param string $cType
  844. * @param string $bodyText
  845. * @param int $colPos
  846. * @param array $moreValues
  847. */
  848. private function insertContent(int $pid,
  849. string $cType=self::CTYPE_TEXT,
  850. string $bodyText = '',
  851. int $colPos=0,
  852. array $moreValues = []) {
  853. $defaultValues = [
  854. 'pid' => $pid,
  855. 'cruser_id' => 1,
  856. 'CType' => $cType,
  857. 'colPos' => $colPos,
  858. 'bodyText' => $bodyText
  859. ];
  860. $values = array_merge($defaultValues, $moreValues);
  861. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('tt_content');
  862. $queryBuilder->insert('tt_content')
  863. ->values($values)
  864. ->execute();
  865. }
  866. /**
  867. * Return the content of `sys_template`.`constants` of
  868. * the website of the given organization
  869. *
  870. * @param int $organizationId
  871. * @return string
  872. */
  873. private function genTemplateConstants(int $organizationId) {
  874. $rootUid = null;
  875. $cnn = new PDO(
  876. "mysql:host=prod-back;dbname=opentalent",
  877. 'dbcloner',
  878. 'wWZ4hYcrmHLW2mUK',
  879. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  880. );
  881. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  882. $stmt = $cnn->prepare(
  883. "SELECT o.id, o.name, o.facebook, o.twitter,
  884. o.category, o.logo_id, p.logoDonorsMove
  885. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  886. ON o.parameters_id = p.id
  887. WHERE o.id=" . $organizationId . ";"
  888. );
  889. $stmt->execute();
  890. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  891. $org_data = $stmt->fetch();
  892. $stmt = $cnn->prepare(
  893. "SELECT c.email
  894. FROM opentalent.ContactPoint c
  895. INNER JOIN opentalent.organization_contactpoint o
  896. ON o.contactPoint_id = c.id
  897. WHERE c.contactType = 'PRINCIPAL'
  898. AND o.organization_id = " . $organizationId . ";"
  899. );
  900. $stmt->execute();
  901. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  902. $contact = $stmt->fetch();
  903. $stmt = $cnn->prepare(
  904. "SELECT n.name, n.logo, n.url
  905. FROM opentalent.Network n
  906. INNER JOIN
  907. (opentalent.NetworkOrganization l
  908. INNER JOIN opentalent.Organization o
  909. ON l.organization_id = o.id)
  910. ON l.network_id = n.id
  911. WHERE l.endDate is NULL
  912. AND o.id=" . $organizationId . ";"
  913. );
  914. $stmt->execute();
  915. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  916. $network = $stmt->fetch();
  917. return "plugin.tx_ottemplating {\n" .
  918. " settings {\n" .
  919. " organization {\n" .
  920. " id = " . $organizationId . "\n" .
  921. " name = " . $org_data['name'] . "\n" .
  922. " is_network = " . ($org_data['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  923. " email = " . $contact['email'] . "\n" .
  924. " logoid = " . $org_data['logo_id'] . "\n" .
  925. " twitter = " . $org_data['twitter'] . "\n" .
  926. " facebook = " . $org_data['facebook'] . "\n" .
  927. " }\n" .
  928. " network {\n" .
  929. " logo = " . $network['logo'] . "\n" .
  930. " name = " . $network['name'] . "\n" .
  931. " url = " . $network['url'] . "\n" .
  932. " }\n" .
  933. " }\n" .
  934. "}";
  935. }
  936. /**
  937. * Create the given directory, give its property to the www-data group and
  938. * record it as a newly created dir (for an eventual rollback)
  939. *
  940. * @param string $dirPath
  941. */
  942. private function mkDir(string $dirPath) {
  943. mkdir($dirPath);
  944. $this->createdDirs[] = $dirPath;
  945. chgrp($dirPath, 'www-data');
  946. }
  947. /**
  948. * Write the given file with content, give its property to the www-data group and
  949. * record it as a newly created file (for an eventual rollback)
  950. *
  951. * @param string $path
  952. * @param string $content
  953. */
  954. private function writeFile(string $path, string $content) {
  955. $f = fopen($path, "w");
  956. try
  957. {
  958. fwrite($f, $content);
  959. $this->createdFiles[] = $path;
  960. chgrp($path, 'www-data');
  961. } finally {
  962. fclose($f);
  963. }
  964. }
  965. /**
  966. * Write the .../sites/.../config.yml file of the given site
  967. *
  968. * @param int $organizationId
  969. * @param int $rootUid
  970. * @param string $domain
  971. */
  972. private function writeConfigFile(int $organizationId, int $rootUid, string $domain) {
  973. $folder_id = explode('.', $domain)[0] . '_' . $organizationId;
  974. $config_dir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $folder_id;
  975. $config_filename = $config_dir . "/config.yaml";
  976. if (file_exists($config_filename)) {
  977. throw new \RuntimeException("A file " . $config_filename . " already exists. Abort.");
  978. }
  979. $config = ['base'=> 'https://' . $domain,
  980. 'baseVariants'=>[],
  981. 'errorHandling'=>[
  982. ['errorCode'=>'404',
  983. 'errorHandler'=>'Page',
  984. 'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']],
  985. ['errorCode'=>'403',
  986. 'errorHandler'=>'Page',
  987. 'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']]
  988. ],
  989. 'flux_content_types'=>'',
  990. 'flux_page_templates'=>'',
  991. 'languages'=>[[
  992. 'title'=>'Fr',
  993. 'enabled'=>True,
  994. 'base'=>'/',
  995. 'typo3Language'=>'fr',
  996. 'locale'=>'fr_FR',
  997. 'iso-639-1'=>'fr',
  998. 'navigationTitle'=>'Fr',
  999. 'hreflang'=>'fr-FR',
  1000. 'direction'=>'ltr',
  1001. 'flag'=>'fr',
  1002. 'languageId'=>'0',
  1003. ]],
  1004. 'rootPageId'=>$rootUid,
  1005. 'routes'=>[]
  1006. ];
  1007. $yamlConfig = Yaml::dump($config, 4);
  1008. if (!file_exists($config_dir)) {
  1009. $this->mkDir($config_dir);
  1010. }
  1011. $this->writeFile($config_filename, $yamlConfig);
  1012. }
  1013. /**
  1014. * Create the BE user for the website
  1015. * The user shall be already created in the Opentalent DB
  1016. *
  1017. * @param int $organizationId
  1018. * @param int $rootUid
  1019. * @param string $domain
  1020. * @return int
  1021. */
  1022. private function createBeUser(int $organizationId, int $rootUid, string $domain) {
  1023. $cnn = new PDO(
  1024. "mysql:host=prod-back;dbname=opentalent",
  1025. 'dbcloner',
  1026. 'wWZ4hYcrmHLW2mUK',
  1027. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1028. );
  1029. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1030. $stmt = $cnn->prepare(
  1031. "SELECT p.username, a.id, s.product
  1032. FROM opentalent.Person p
  1033. INNER JOIN Access a ON p.id = a.person_id
  1034. INNER JOIN Settings s on a.organization_id = s.organization_id
  1035. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1036. );
  1037. $stmt->execute();
  1038. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1039. $user_data = $stmt->fetch();
  1040. if (!$user_data) {
  1041. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1042. }
  1043. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1044. $randomStr = (new Random)->generateRandomHexString(20);
  1045. // get the existing filemounts
  1046. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  1047. $queryBuilder
  1048. ->select('uid')
  1049. ->from('sys_filemounts')
  1050. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1051. $statement = $queryBuilder->execute();
  1052. $rows = $statement->fetchAll(3) ?: [];
  1053. $files = [];
  1054. foreach ($rows as $row) {
  1055. $files[] = $row[0];
  1056. }
  1057. $values = [
  1058. 'username' => $user_data['username'],
  1059. 'password' => $randomStr,
  1060. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $user_data['id'] . ')',
  1061. 'deleted' => 0,
  1062. 'lang' => 'fr',
  1063. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$user_data['product']] : 1,
  1064. 'db_mountpoints' => $rootUid,
  1065. 'file_mountPoints' => join(',', $files),
  1066. 'options' => 2,
  1067. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1068. 'tx_opentalent_opentalentId' => $user_data['id'],
  1069. 'tx_opentalent_organizationId' => $organizationId,
  1070. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1071. ];
  1072. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  1073. $queryBuilder->insert('be_users')
  1074. ->values($values)
  1075. ->execute();
  1076. $beUid = $queryBuilder->getConnection()->lastInsertId();
  1077. // enable frontend editing
  1078. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1079. $user = $BE_USER->getRawUserByUid($beUid);
  1080. $BE_USER->user = $user;
  1081. $BE_USER->backendSetUC();
  1082. $BE_USER->uc['frontend_editing'] = 1;
  1083. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1084. $BE_USER->writeUC($BE_USER->uc);
  1085. return $beUid;
  1086. }
  1087. }