SiteController.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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\nconfig.absRefPrefix = /',",
  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. );
  880. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  881. $stmt = $cnn->prepare(
  882. "SELECT o.id, o.name, o.facebook, o.twitter,
  883. o.category, o.logo_id, p.logoDonorsMove
  884. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  885. ON o.parameters_id = p.id
  886. WHERE o.id=" . $organizationId . ";"
  887. );
  888. $stmt->execute();
  889. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  890. $org_data = $stmt->fetch();
  891. $stmt = $cnn->prepare(
  892. "SELECT c.email
  893. FROM opentalent.ContactPoint c
  894. INNER JOIN opentalent.organization_contactpoint o
  895. ON o.contactPoint_id = c.id
  896. WHERE c.contactType = 'PRINCIPAL'
  897. AND o.organization_id = " . $organizationId . ";"
  898. );
  899. $stmt->execute();
  900. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  901. $contact = $stmt->fetch();
  902. $stmt = $cnn->prepare(
  903. "SELECT n.name, n.logo, n.url
  904. FROM opentalent.Network n
  905. INNER JOIN
  906. (opentalent.NetworkOrganization l
  907. INNER JOIN opentalent.Organization o
  908. ON l.organization_id = o.id)
  909. ON l.network_id = n.id
  910. WHERE l.endDate is NULL
  911. AND o.id=" . $organizationId . ";"
  912. );
  913. $stmt->execute();
  914. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  915. $network = $stmt->fetch();
  916. return "plugin.tx_ottemplating {\n" .
  917. " settings {\n" .
  918. " organization {\n" .
  919. " id = " . $organizationId . "\n" .
  920. " name = " . $org_data['name'] . "\n" .
  921. " is_network = " . ($org_data['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  922. " email = " . $contact['email'] . "\n" .
  923. " logoid = " . $org_data['logo_id'] . "\n" .
  924. " twitter = " . $org_data['twitter'] . "\n" .
  925. " facebook = " . $org_data['facebook'] . "\n" .
  926. " }\n" .
  927. " network {\n" .
  928. " logo = " . $network['logo'] . "\n" .
  929. " name = " . $network['name'] . "\n" .
  930. " url = " . $network['url'] . "\n" .
  931. " }\n" .
  932. " }\n" .
  933. "}";
  934. }
  935. /**
  936. * Create the given directory, give its property to the www-data group and
  937. * record it as a newly created dir (for an eventual rollback)
  938. *
  939. * @param string $dirPath
  940. */
  941. private function mkDir(string $dirPath) {
  942. mkdir($dirPath);
  943. $this->createdDirs[] = $dirPath;
  944. chgrp($dirPath, 'www-data');
  945. }
  946. /**
  947. * Write the given file with content, give its property to the www-data group and
  948. * record it as a newly created file (for an eventual rollback)
  949. *
  950. * @param string $path
  951. * @param string $content
  952. */
  953. private function writeFile(string $path, string $content) {
  954. $f = fopen($path, "w");
  955. try
  956. {
  957. fwrite($f, $content);
  958. $this->createdFiles[] = $path;
  959. chgrp($path, 'www-data');
  960. } finally {
  961. fclose($f);
  962. }
  963. }
  964. /**
  965. * Write the .../sites/.../config.yml file of the given site
  966. *
  967. * @param int $organizationId
  968. * @param int $rootUid
  969. * @param string $domain
  970. */
  971. private function writeConfigFile(int $organizationId, int $rootUid, string $domain) {
  972. $folder_id = explode('.', $domain)[0] . '_' . $organizationId;
  973. $config_dir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $folder_id;
  974. $config_filename = $config_dir . "/config.yaml";
  975. if (file_exists($config_filename)) {
  976. throw new \RuntimeException("A file " . $config_filename . " already exists. Abort.");
  977. }
  978. $config = ['base'=> 'https://' . $domain,
  979. 'baseVariants'=>[],
  980. 'errorHandling'=>[
  981. ['errorCode'=>'404',
  982. 'errorHandler'=>'Page',
  983. 'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']],
  984. ['errorCode'=>'403',
  985. 'errorHandler'=>'Page',
  986. 'errorContentSource'=>'t3://page?uid=' . $this->createdPagesIndex['/page-introuvable']]
  987. ],
  988. 'flux_content_types'=>'',
  989. 'flux_page_templates'=>'',
  990. 'languages'=>[[
  991. 'title'=>'Fr',
  992. 'enabled'=>True,
  993. 'base'=>'/',
  994. 'typo3Language'=>'fr',
  995. 'locale'=>'fr_FR',
  996. 'iso-639-1'=>'fr',
  997. 'navigationTitle'=>'Fr',
  998. 'hreflang'=>'fr-FR',
  999. 'direction'=>'ltr',
  1000. 'flag'=>'fr',
  1001. 'languageId'=>'0',
  1002. ]],
  1003. 'rootPageId'=>$rootUid,
  1004. 'routes'=>[]
  1005. ];
  1006. $yamlConfig = Yaml::dump($config, 4);
  1007. if (!file_exists($config_dir)) {
  1008. $this->mkDir($config_dir);
  1009. }
  1010. $this->writeFile($config_filename, $yamlConfig);
  1011. }
  1012. /**
  1013. * Create the BE user for the website
  1014. * The user shall be already created in the Opentalent DB
  1015. *
  1016. * @param int $organizationId
  1017. * @param int $rootUid
  1018. * @param string $domain
  1019. * @return int
  1020. */
  1021. private function createBeUser(int $organizationId, int $rootUid, string $domain) {
  1022. $cnn = new PDO(
  1023. "mysql:host=prod-back;dbname=opentalent",
  1024. 'dbcloner',
  1025. 'wWZ4hYcrmHLW2mUK'
  1026. );
  1027. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1028. $stmt = $cnn->prepare(
  1029. "SELECT p.username, a.id, s.product
  1030. FROM opentalent.Person p
  1031. INNER JOIN Access a ON p.id = a.person_id
  1032. INNER JOIN Settings s on a.organization_id = s.organization_id
  1033. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1034. );
  1035. $stmt->execute();
  1036. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1037. $user_data = $stmt->fetch();
  1038. if (!$user_data) {
  1039. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1040. }
  1041. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1042. $randomStr = (new Random)->generateRandomHexString(20);
  1043. // get the existing filemounts
  1044. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('sys_filemounts');
  1045. $queryBuilder
  1046. ->select('uid')
  1047. ->from('sys_filemounts')
  1048. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1049. $statement = $queryBuilder->execute();
  1050. $rows = $statement->fetchAll(3) ?: [];
  1051. $files = [];
  1052. foreach ($rows as $row) {
  1053. $files[] = $row[0];
  1054. }
  1055. $values = [
  1056. 'username' => $user_data['username'],
  1057. 'password' => $randomStr,
  1058. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $user_data['id'] . ')',
  1059. 'deleted' => 0,
  1060. 'lang' => 'fr',
  1061. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$user_data['product']] : 1,
  1062. 'db_mountpoints' => $rootUid,
  1063. 'file_mountPoints' => join(',', $files),
  1064. 'options' => 2,
  1065. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1066. 'tx_opentalent_opentalentId' => $user_data['id'],
  1067. 'tx_opentalent_organizationId' => $organizationId,
  1068. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1069. ];
  1070. $queryBuilder = $this->cnnPool->getQueryBuilderForTable('be_users');
  1071. $queryBuilder->insert('be_users')
  1072. ->values($values)
  1073. ->execute();
  1074. $beUid = $queryBuilder->getConnection()->lastInsertId();
  1075. // enable frontend editing
  1076. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1077. $user = $BE_USER->getRawUserByUid($beUid);
  1078. $BE_USER->user = $user;
  1079. $BE_USER->backendSetUC();
  1080. $BE_USER->uc['frontend_editing'] = 1;
  1081. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1082. $BE_USER->writeUC($BE_USER->uc);
  1083. return $beUid;
  1084. }
  1085. }