SiteController.php 54 KB

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