SiteController.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use http\Exception\RuntimeException;
  4. use Opentalent\OtAdmin\Exception\NoSuchWebsiteException;
  5. use Opentalent\OtCore\Cache\OtCacheManager;
  6. use Opentalent\OtCore\Controller\ActionController;
  7. use Opentalent\OtCore\Domain\Model\Organization;
  8. use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
  9. use Opentalent\OtCore\Exception\ApiRequestException;
  10. use Opentalent\OtCore\Page\OtPageRepository;
  11. use PDO;
  12. use Symfony\Component\Yaml\Yaml;
  13. use TYPO3\CMS\Core\Crypto\Random;
  14. use TYPO3\CMS\Core\Utility\GeneralUtility;
  15. use TYPO3\CMS\Extbase\Object\ObjectManager;
  16. /**
  17. * The SiteController implements some admin-only operations
  18. * on Typo3 websites, like creation or update.
  19. */
  20. class SiteController extends ActionController
  21. {
  22. // Templates names
  23. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  24. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  25. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  26. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  27. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  28. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  29. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  30. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  31. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  32. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  33. // Pages dokType values
  34. const DOK_PAGE = 1;
  35. const DOK_SHORTCUT = 4;
  36. const DOK_FOLDER = 116;
  37. // Contents CTypes
  38. const CTYPE_TEXT = 'text';
  39. const CTYPE_IMAGE = 'image';
  40. const CTYPE_TEXTPIC = 'textpic';
  41. const CTYPE_TEXTMEDIA = 'textmedia';
  42. const CTYPE_HTML = 'html';
  43. const CTYPE_HEADER = 'header';
  44. const CTYPE_UPLOADS = 'uploads';
  45. const CTYPE_LIST = 'list';
  46. const CTYPE_SITEMAP = 'menu_sitemap';
  47. // Default values
  48. const DEFAULT_THEME = 'Classic';
  49. const DEFAULT_COLOR = 'light-blue';
  50. // BE rights
  51. const PRODUCT_MAPPING = [
  52. "school-standard" => 1, // Association writer basic
  53. "artist-standard" => 1, // Association writer basic
  54. "school-premium" => 3, // Association writer full
  55. "artist-premium" => 3, // Association writer full
  56. "manager" => 3, // Association writer full
  57. ];
  58. // Websites statuses
  59. const STATUS_NO_SUCH_WEBSITE = 0;
  60. const STATUS_EXISTING = 1;
  61. const STATUS_EXISTING_DELETED = 2;
  62. const STATUS_EXISTING_HIDDEN = 3;
  63. const STATUS_EXISTING_WITH_WARNINGS = 4;
  64. const STATUS_LBL = [
  65. self::STATUS_NO_SUCH_WEBSITE => 'Does not exist',
  66. self::STATUS_EXISTING => 'Existing',
  67. self::STATUS_EXISTING_DELETED => 'Existing, deleted',
  68. self::STATUS_EXISTING_HIDDEN => 'Existing, hidden',
  69. self::STATUS_EXISTING_WITH_WARNINGS => 'Existing with warnings',
  70. ];
  71. const MODE_PROD = 1;
  72. const MODE_DEV = 1;
  73. const RX_DOMAIN = "/([a-z0-9A-Z]\.)*[a-z0-9-]+\.([a-z0-9]{2,24})+(\.co\.([a-z0-9]{2,24})|\.([a-z0-9]{2,24}))*\/?/";
  74. const REDIRECTION_UNKNOWN_STATUS = 0;
  75. const REDIRECTION_UPDATED = 1;
  76. const REDIRECTION_CREATED = 2;
  77. /**
  78. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  79. */
  80. private $connectionPool;
  81. public function injectConnectionPool(\TYPO3\CMS\Core\Database\ConnectionPool $connectionPool)
  82. {
  83. $this->connectionPool = $connectionPool;
  84. }
  85. /**
  86. * @var \TYPO3\CMS\Core\Cache\CacheManager
  87. */
  88. private $cacheManager;
  89. public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager $cacheManager)
  90. {
  91. $this->cacheManager = $cacheManager;
  92. }
  93. /**
  94. * Index of the pages created during the process
  95. * >> [slug => uid]
  96. * @var array
  97. */
  98. private $createdPagesIndex;
  99. /**
  100. * List of the directories created in the process (for rollback purposes)
  101. * @var array
  102. */
  103. private $createdDirs;
  104. /**
  105. * List of the files created in the process (for rollback purposes)
  106. * @var array
  107. */
  108. private $createdFiles;
  109. public function __construct()
  110. {
  111. parent::__construct();
  112. $this->createdPagesIndex = [];
  113. $this->createdDirs = [];
  114. $this->createdFiles = [];
  115. }
  116. /**
  117. * Return the main informations about the organization's website
  118. *
  119. * @param int $organizationId
  120. * @return array
  121. * @throws NoSuchWebsiteException
  122. */
  123. public function getSiteInfosAction(int $organizationId) {
  124. $rootUid = $this->findRootUidFor($organizationId);
  125. $config = $this->findConfigFor($organizationId, $rootUid);
  126. $extraData = $this->fetchOrganizationExtraData($organizationId);
  127. $rootPage = $this->otPageRepository->getPage($rootUid);
  128. $site = [
  129. 'rootUid' => $rootUid,
  130. 'siteTitle' => $rootPage['title'],
  131. 'baseUrl' => $config['base'],
  132. 'template' => $rootPage['tx_opentalent_template'],
  133. 'preferences' => $rootPage['tx_opentalent_template_preferences'],
  134. 'matomo_id' => $rootPage['tx_opentalent_matomo_id'],
  135. 'deleted' => $rootPage['deleted'],
  136. 'hiddenOrRestricted' => (int)($rootPage['hidden'] || $rootPage['fe_group'] < 0),
  137. 'mountedForBeUsers' => []
  138. ];
  139. // Owners
  140. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  141. $queryBuilder->getRestrictions()->removeAll();
  142. $beUsers = $queryBuilder
  143. ->select('uid', 'username')
  144. ->from('be_users')
  145. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  146. ->execute()
  147. ->fetchAll();
  148. foreach ($beUsers as $beUser) {
  149. $site['mountedForBeUsers'][] = $beUser;
  150. }
  151. return $site;
  152. }
  153. /**
  154. * Creates a new website for the given organization, and
  155. * returns the root page uid of the newly created site
  156. *
  157. * @param int $organizationId
  158. * @param int $mode Can be either MODE_PROD or MODE_DEV, MODE_PROD being the normal behaviour.
  159. * If MODE_DEV is used, sites urls will be of the form 'http://host/subdomain'
  160. * instead of 'http://subdomain/host'
  161. * @return int Uid of the root page of the newly created website
  162. * @throws \RuntimeException|\Exception
  163. */
  164. public function createSiteAction(int $organizationId, int $mode=self::MODE_PROD) {
  165. $organization = $this->fetchOrganization($organizationId);
  166. // This extra-data can not be retrieved from the API for now, but
  167. // this shall be set up as soon as possible, to avoid requesting
  168. // the prod-back DB directly.
  169. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  170. $isNetwork = $organizationExtraData['category'] == 'NETWORK';
  171. // Is there already a website with this organization's id?
  172. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  173. $queryBuilder->getRestrictions()->removeAll();
  174. $statement = $queryBuilder
  175. ->select('uid')
  176. ->from('pages')
  177. ->where($queryBuilder->expr()->eq('tx_opentalent_structure_id', $queryBuilder->createNamedParameter($organization->getId())))
  178. ->andWhere('is_siteroot=1')
  179. ->execute();
  180. if ($statement->rowCount() > 0) {
  181. 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)");
  182. }
  183. // ** Create the new website
  184. // start transactions
  185. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  186. // keep tracks of the created folders and files to be able to remove them during a rollback
  187. try {
  188. // Create the site pages:
  189. // > Root page
  190. $rootUid = $this->insertRootPage($organization);
  191. // > 'Accueil' shortcut
  192. $this->insertPage(
  193. $organization,
  194. $rootUid,
  195. 'Accueil',
  196. '/accueil',
  197. '',
  198. [
  199. 'dokType' => self::DOK_SHORTCUT,
  200. 'shortcut' => $rootUid
  201. ]
  202. );
  203. // > 'Présentation' page
  204. $this->insertPage(
  205. $organization,
  206. $rootUid,
  207. 'Présentation',
  208. '/presentation'
  209. );
  210. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  211. $this->insertPage(
  212. $organization,
  213. $this->createdPagesIndex['/presentation'],
  214. 'Qui sommes nous?',
  215. '/qui-sommes-nous',
  216. '',
  217. ['hidden' => 1]
  218. );
  219. // > 'Présentation > Les adhérents' page
  220. $this->insertPage(
  221. $organization,
  222. $this->createdPagesIndex['/presentation'],
  223. 'Les adhérents',
  224. '/les-adherents',
  225. self::TEMPLATE_MEMBERS
  226. );
  227. // > 'Présentation > Les membres du CA' page
  228. $this->insertPage(
  229. $organization,
  230. $this->createdPagesIndex['/presentation'],
  231. 'Les membres du CA',
  232. '/les-membres-du-ca',
  233. self::TEMPLATE_MEMBERSCA
  234. );
  235. if ($isNetwork) {
  236. // > 'Présentation > Les sociétés adhérentes' page
  237. $this->insertPage(
  238. $organization,
  239. $this->createdPagesIndex['/presentation'],
  240. 'Les sociétés adhérentes',
  241. '/societes-adherentes',
  242. self::TEMPLATE_STRUCTURES
  243. );
  244. }
  245. // > 'Présentation > Historique' page (hidden by default)
  246. $this->insertPage(
  247. $organization,
  248. $this->createdPagesIndex['/presentation'],
  249. 'Historique',
  250. '/historique',
  251. '',
  252. ['hidden' => 1]
  253. );
  254. // ~ Contact shortcut will be created after the contact page
  255. // > 'Actualités' page (hidden by default)
  256. $this->insertPage(
  257. $organization,
  258. $rootUid,
  259. 'Actualités',
  260. '/actualites',
  261. self::TEMPLATE_NEWS,
  262. ['hidden' => 1]
  263. );
  264. // > 'Saison en cours' page
  265. $this->insertPage(
  266. $organization,
  267. $rootUid,
  268. 'Saison en cours',
  269. '/saison-en-cours'
  270. );
  271. // > 'Saison en cours > Les évènements' page
  272. $this->insertPage(
  273. $organization,
  274. $this->createdPagesIndex['/saison-en-cours'],
  275. 'Les évènements',
  276. '/les-evenements',
  277. self::TEMPLATE_EVENTS
  278. );
  279. if ($isNetwork) {
  280. // > 'Présentation > Les sociétés adhérentes' page
  281. $this->insertPage(
  282. $organization,
  283. $this->createdPagesIndex['/presentation'],
  284. 'Évènements des structures',
  285. '/evenements-des-structures',
  286. self::TEMPLATE_STRUCTURESEVENTS
  287. );
  288. }
  289. // > 'Vie interne' page (restricted, hidden by default)
  290. $this->insertPage(
  291. $organization,
  292. $rootUid,
  293. 'Vie interne',
  294. '/vie-interne',
  295. '',
  296. [
  297. 'hidden' => 1,
  298. 'fe_group' => -2
  299. ]
  300. );
  301. // > 'Footer' page (not in the menu)
  302. $this->insertPage(
  303. $organization,
  304. $rootUid,
  305. 'Footer',
  306. '/footer',
  307. '',
  308. [
  309. 'dokType' => self::DOK_FOLDER,
  310. 'nav_hide' => 1
  311. ]
  312. );
  313. // > 'Footer > Contact' page
  314. $this->insertPage(
  315. $organization,
  316. $this->createdPagesIndex['/footer'],
  317. 'Contact',
  318. '/contact',
  319. self::TEMPLATE_CONTACT
  320. );
  321. // > 'Footer > Plan du site' page
  322. $this->insertPage(
  323. $organization,
  324. $this->createdPagesIndex['/footer'],
  325. 'Plan du site',
  326. '/plan-du-site'
  327. );
  328. // > 'Footer > Mentions légales' page
  329. $this->insertPage(
  330. $organization,
  331. $this->createdPagesIndex['/footer'],
  332. 'Mentions légales',
  333. '/mentions-legales'
  334. );
  335. // > 'Présentation > Contact' shortcut
  336. $this->insertPage(
  337. $organization,
  338. $this->createdPagesIndex['/presentation'],
  339. 'Contact',
  340. '/ecrivez-nous',
  341. '',
  342. [
  343. 'dokType' => self::DOK_SHORTCUT,
  344. 'shortcut' => $this->createdPagesIndex['/contact']
  345. ]
  346. );
  347. // > 'Page introuvable' page (not in the menu, read-only)
  348. $this->insertPage(
  349. $organization,
  350. $rootUid,
  351. 'Page introuvable',
  352. '/page-introuvable',
  353. '',
  354. [
  355. 'nav_hide' => 1,
  356. 'no_search' => 1
  357. ]
  358. );
  359. // Add content to these pages
  360. // >> root page content
  361. $this->insertContent(
  362. $rootUid,
  363. self::CTYPE_TEXTPIC,
  364. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  365. 0
  366. );
  367. // >> page 'qui sommes nous?'
  368. $this->insertContent(
  369. $this->createdPagesIndex['/qui-sommes-nous'],
  370. self::CTYPE_TEXT,
  371. 'Qui sommes nous ...',
  372. 0
  373. );
  374. // >> page 'historique'
  375. $this->insertContent(
  376. $this->createdPagesIndex['/historique'],
  377. self::CTYPE_TEXT,
  378. "Un peu d'histoire ...",
  379. 0
  380. );
  381. // >> page 'plan du site'
  382. $this->insertContent(
  383. $this->createdPagesIndex['/plan-du-site'],
  384. self::CTYPE_SITEMAP
  385. );
  386. // >> page 'mentions légales'
  387. $this->insertContent(
  388. $this->createdPagesIndex['/mentions-legales'],
  389. self::CTYPE_TEXT,
  390. '<p style="margin-bottom: 0"><b>Mentions Légales</b></p>',
  391. 0
  392. );
  393. // Build and update the domain
  394. if ($mode == self::MODE_PROD) {
  395. $domain = $organization->getSubDomain() . '.opentalent.fr';
  396. } elseif ($mode == self::MODE_DEV) {
  397. $domain = $organization->getSubDomain() . '/';
  398. } else {
  399. throw new RuntimeException('Unknown value for $mode: ' . $mode);
  400. }
  401. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_domain');
  402. $queryBuilder->insert('sys_domain')
  403. ->values([
  404. 'pid' => $rootUid,
  405. 'domainName' => $domain
  406. ])
  407. ->execute();
  408. // update sys_template
  409. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  410. $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
  411. $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
  412. $include .= ",EXT:form/Configuration/TypoScript/";
  413. $include .= ",EXT:news/Configuration/TypoScript";
  414. $include .= ",EXT:frontend_editing/Configuration/TypoScript";
  415. $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
  416. $include .= ",EXT:ot_templating/Configuration/TypoScript";
  417. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  418. $queryBuilder->insert('sys_template')
  419. ->values([
  420. 'pid' => $rootUid,
  421. 'title' => $organization->getName(),
  422. 'sitetitle' => $organization->getName(),
  423. 'root' => 1,
  424. 'clear' => 3,
  425. 'config' => "config.frontend_editing = 1",
  426. 'include_static_file' => $include,
  427. 'constants' => $constants
  428. ])
  429. ->execute();
  430. // Create the site config.yaml file
  431. $this->writeConfigFile($organizationId, $rootUid, $domain, true);
  432. // Create the user_upload directory and update the sys_filemounts table
  433. $uploadRelPath = "/user_upload/" . $organizationId;
  434. $uploadDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin" . $uploadRelPath;
  435. if (file_exists($uploadDir)) {
  436. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  437. }
  438. $defaultUploadDir = $uploadDir . '/images';
  439. $formsDir = $uploadDir . '/Forms';
  440. $this->mkDir($uploadDir);
  441. $this->mkDir($defaultUploadDir);
  442. $this->mkDir($formsDir);
  443. // Insert the filemounts points (sys_filemounts)
  444. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  445. $queryBuilder->insert('sys_filemounts')
  446. ->values([
  447. 'title' => 'Documents',
  448. 'path' => $defaultUploadDir,
  449. 'base' => 1
  450. ])
  451. ->execute();
  452. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  453. $queryBuilder->insert('sys_filemounts')
  454. ->values([
  455. 'title' => 'Forms_' . $organizationId,
  456. 'path' => $formsDir,
  457. 'base' => 1
  458. ])
  459. ->execute();
  460. // Create the BE User
  461. // -- NB: this user will then be auto-updated by the ot_connect extension --
  462. $beUserUid = $this->createBeUser(
  463. $organizationId,
  464. $rootUid,
  465. $domain,
  466. $organizationExtraData['admin']
  467. );
  468. // Update the user TsConfig
  469. $tsconfig = "options.uploadFieldsInTopOfEB = 1\n" .
  470. "options.defaultUploadFolder=1:" . $defaultUploadDir . "\n";
  471. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  472. $queryBuilder
  473. ->update('be_users')
  474. ->where($queryBuilder->expr()->eq('uid', $beUserUid))
  475. ->set('TSconfig', $tsconfig)
  476. ->execute();
  477. // Give the keys of the website to this user (makes him the owner)
  478. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  479. foreach($this->createdPagesIndex as $slug => $uid) {
  480. $queryBuilder
  481. ->update('pages')
  482. ->where($queryBuilder->expr()->eq('uid', $uid))
  483. ->set('perms_userid', $beUserUid)
  484. ->execute();
  485. }
  486. // Try to commit the result
  487. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  488. if (!$commitSuccess) {
  489. throw new \RuntimeException('Something went wrong while commiting the result');
  490. }
  491. } catch(\Exception $e) {
  492. // rollback
  493. $this->connectionPool->getConnectionByName('Default')->rollback();
  494. // remove created files and dirs
  495. foreach (array_reverse($this->createdFiles) as $filename) {
  496. unlink($filename);
  497. }
  498. $this->createdFiles = [];
  499. foreach (array_reverse($this->createdDirs) as $dirname) {
  500. rmdir($dirname);
  501. }
  502. $this->createdDirs = [];
  503. throw $e;
  504. }
  505. // Extra steps that do not need any rollback:
  506. $this->enableFeEditing($beUserUid);
  507. return $rootUid;
  508. }
  509. /**
  510. * Update the `sys_template`.`constants` field of the given
  511. * organization's website with the data fetched from the opentalent DB.
  512. *
  513. * @param int $organizationId
  514. * @return int
  515. * @throws NoSuchWebsiteException
  516. */
  517. public function updateSiteConstantsAction(int $organizationId): int
  518. {
  519. $rootUid = $this->findRootUidFor($organizationId);
  520. // This extra-data can not be retrieved from the API for now, but
  521. // this shall be set up as soon as possible, to avoid requesting
  522. // the prod-back DB directly.
  523. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  524. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  525. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  526. $queryBuilder
  527. ->update('sys_template')
  528. ->set('constants', $constants)
  529. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  530. ->execute();
  531. OtCacheManager::clearSiteCache($rootUid, true);
  532. return $rootUid;
  533. }
  534. /**
  535. * Delete the website with all its pages, contents and related records
  536. *
  537. * If the hard parameter is false, the records' `deleted` field will be set to true and
  538. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  539. *
  540. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  541. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  542. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  543. *
  544. * $redirectTo is the optional organization id to whom requests will be redirected
  545. *
  546. * @param int $organizationId
  547. * @param bool $hard
  548. * @param int|null $redirectTo
  549. * @return int
  550. * @throws NoSuchWebsiteException
  551. * @throws \Doctrine\DBAL\ConnectionException
  552. * @throws \Doctrine\DBAL\DBALException
  553. */
  554. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null) {
  555. $rootUid = $this->findRootUidFor($organizationId);
  556. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  557. $isDeleted = $queryBuilder
  558. ->select('deleted')
  559. ->from('pages')
  560. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  561. ->execute()
  562. ->fetchColumn(0) == 1;
  563. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  564. if ($hard && !file_exists($confirm_file)) {
  565. throw new \RuntimeException(
  566. "You are going to completely delete the website with root uid " . $rootUid .
  567. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  568. $confirm_file . "', and launch this command again."
  569. );
  570. }
  571. // Prepare the redirection
  572. if ($redirectTo) {
  573. $originUrl = $this->getSiteInfosAction($organizationId)['baseUrl'];
  574. $targetUrl = $this->getSiteInfosAction($redirectTo)['baseUrl'];
  575. }
  576. // start transactions
  577. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  578. // keep track of renamed file for an eventual rollback
  579. $renamed = [];
  580. try {
  581. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  582. foreach($pages as $page) {
  583. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  584. $this->delete('pages', 'uid', $page['uid'], $hard);
  585. }
  586. $this->delete('tt_content', 'pid', $rootUid, $hard);
  587. $this->delete('pages', 'uid', $rootUid, $hard);
  588. $this->delete('sys_template', 'pid', $rootUid, $hard);
  589. if ($hard) {
  590. // there is no 'deleted' field in sys_domain
  591. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  592. }
  593. // remove filemounts
  594. $this->delete('sys_filemounts',
  595. 'path',
  596. "'/user_upload/" . $organizationId . "/images'",
  597. $hard);
  598. $this->delete('sys_filemounts',
  599. 'path',
  600. "'/user_upload/" . $organizationId . "/Forms'",
  601. $hard);
  602. $this->delete('be_users', 'db_mountpoints', $rootUid, $hard);
  603. // Look up for the config.yaml file of the website
  604. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  605. $configYamlFile = "";
  606. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  607. if (!$isDeleted) {
  608. $yamlFile = $subdir . '/config.yaml';
  609. } else {
  610. $yamlFile = $subdir . '/config.yaml.deleted';
  611. }
  612. if (is_file($yamlFile)) {
  613. $conf = Yaml::parseFile($yamlFile);
  614. if ($conf['rootPageId'] == $rootUid) {
  615. $configYamlFile = $yamlFile;
  616. break;
  617. }
  618. }
  619. }
  620. if (!$isDeleted) {
  621. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  622. } else {
  623. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  624. }
  625. // If hard deletion, verify that upload dirs are empty
  626. if ($hard && is_dir($uploadDir)) {
  627. foreach (scandir($uploadDir) as $subdir) {
  628. if ($subdir == '.' or $subdir == '..') {
  629. continue;
  630. }
  631. $subdir = $uploadDir . $subdir;
  632. if (!is_dir($subdir)) {
  633. throw new \RuntimeException(
  634. 'The directory ' . $uploadDir . ' contains non-directory files' .
  635. ', this humble script prefers not to take care of them automatically. Abort.');
  636. }
  637. if (is_readable($subdir)) {
  638. foreach (scandir($subdir) as $filename) {
  639. if ($filename != '.' && $filename != '..') {
  640. throw new \RuntimeException(
  641. 'The directory ' . $subdir . ' is not empty, ' .
  642. 'this humble script prefers not to take care of them automatically. Abort.');
  643. }
  644. }
  645. }
  646. }
  647. }
  648. // If soft deletion, check that no deleted file or directory exist
  649. if (!$hard) {
  650. $toRename = [];
  651. if (!$hard) {
  652. if (is_file($configYamlFile)) {
  653. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  654. }
  655. if (is_dir($uploadDir)) {
  656. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  657. }
  658. }
  659. foreach ($toRename as $initialPath => $newPath) {
  660. if (is_file($newPath)) {
  661. throw new \RuntimeException(
  662. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  663. }
  664. }
  665. }
  666. // Delete or rename files and dirs
  667. if ($hard) {
  668. if (is_file($configYamlFile)) {
  669. unlink($configYamlFile);
  670. }
  671. if (is_dir(dirname($configYamlFile))) {
  672. rmdir(dirname($configYamlFile));
  673. }
  674. if (is_dir($uploadDir . 'images')) {
  675. rmdir($uploadDir . 'images');
  676. }
  677. if (is_dir($uploadDir . 'Forms')) {
  678. rmdir($uploadDir . 'Forms');
  679. }
  680. if (is_dir($uploadDir)) {
  681. rmdir($uploadDir);
  682. }
  683. } else {
  684. $renamed = [];
  685. foreach ($toRename as $initialPath => $newPath) {
  686. rename($initialPath, $newPath);
  687. $renamed[$initialPath] = $newPath;
  688. }
  689. }
  690. // Add the redirection
  691. if ($redirectTo) {
  692. $this->addRedirection($originUrl, $targetUrl);
  693. }
  694. // Try to commit the result
  695. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  696. if (!$commitSuccess) {
  697. throw new \RuntimeException('Something went wrong while commiting the result');
  698. }
  699. return $rootUid;
  700. } catch(\Exception $e) {
  701. // rollback
  702. $this->connectionPool->getConnectionByName('Default')->rollback();
  703. if (!$hard) {
  704. foreach ($renamed as $initialPath => $newPath) {
  705. rename($newPath, $initialPath);
  706. }
  707. }
  708. if (file_exists($confirm_file)) {
  709. unlink($confirm_file);
  710. }
  711. throw $e;
  712. }
  713. }
  714. /**
  715. * @param string $table
  716. * @param string $whereKey
  717. * @param $whereValue
  718. * @param int $hard
  719. */
  720. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  721. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  722. if (!$hard) {
  723. $queryBuilder
  724. ->update($table)
  725. ->set('deleted', 1)
  726. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  727. ->execute();
  728. } else {
  729. $queryBuilder
  730. ->delete($table)
  731. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  732. ->execute();
  733. }
  734. }
  735. public function undeleteSiteAction(int $organizationId) {
  736. $rootUid = $this->findRootUidFor($organizationId);
  737. // start transactions
  738. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  739. // keep track of renamed file for an eventual rollback
  740. $renamed = [];
  741. try {
  742. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  743. foreach($pages as $page) {
  744. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  745. $queryBuilder
  746. ->update('tt_content')
  747. ->set('deleted', 0)
  748. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  749. ->execute();
  750. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  751. $queryBuilder
  752. ->update('pages')
  753. ->set('deleted', 0)
  754. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  755. ->execute();
  756. }
  757. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  758. $queryBuilder
  759. ->update('tt_content')
  760. ->set('deleted', 0)
  761. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  762. ->execute();
  763. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  764. $queryBuilder
  765. ->update('pages')
  766. ->set('deleted', 0)
  767. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  768. ->execute();
  769. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  770. $queryBuilder
  771. ->update('sys_template')
  772. ->set('deleted', 0)
  773. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  774. ->execute();
  775. // remove filemounts
  776. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  777. $queryBuilder
  778. ->update('sys_filemounts')
  779. ->set('deleted', 0)
  780. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/images'"))
  781. ->execute();
  782. $queryBuilder
  783. ->update('sys_filemounts')
  784. ->set('deleted', 0)
  785. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/Forms'"))
  786. ->execute();
  787. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  788. $queryBuilder
  789. ->update('be_users')
  790. ->set('deleted', 0)
  791. ->where($queryBuilder->expr()->eq('db_mountpoints', $rootUid))
  792. ->execute();
  793. // Look up for the config.yaml file of the website
  794. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  795. $configYamlFile = "";
  796. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  797. $yamlFile = $subdir . '/config.yaml.deleted';
  798. if (is_file($yamlFile)) {
  799. $conf = Yaml::parseFile($yamlFile);
  800. if ($conf['rootPageId'] == $rootUid) {
  801. $configYamlFile = $yamlFile;
  802. break;
  803. }
  804. }
  805. }
  806. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  807. $toRename = [];
  808. if (is_file($configYamlFile)) {
  809. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  810. }
  811. if (is_dir($uploadDir)) {
  812. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  813. }
  814. foreach ($toRename as $initialPath => $newPath) {
  815. if (is_file($newPath)) {
  816. throw new \RuntimeException(
  817. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  818. }
  819. }
  820. $renamed = [];
  821. foreach ($toRename as $initialPath => $newPath) {
  822. rename($initialPath, $newPath);
  823. $renamed[$initialPath] = $newPath;
  824. }
  825. // remove eventual redirection from this site to another
  826. $originUrl = $this->getSiteInfosAction($organizationId)['baseUrl'];
  827. $this->removeRedirectionsFrom($originUrl);
  828. // Try to commit the result
  829. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  830. if (!$commitSuccess) {
  831. throw new \RuntimeException('Something went wrong while commiting the result');
  832. }
  833. return $rootUid;
  834. } catch(\Exception $e) {
  835. // rollback
  836. $this->connectionPool->getConnectionByName('Default')->rollback();
  837. foreach ($renamed as $initialPath => $newPath) {
  838. rename($newPath, $initialPath);
  839. }
  840. throw $e;
  841. }
  842. }
  843. /**
  844. * Clear the cache of the organization's website
  845. *
  846. * @param int $organizationId the organization's id whom site cache should be cleared
  847. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  848. * @return int
  849. * @throws NoSuchWebsiteException
  850. */
  851. public function clearSiteCacheAction(int $organizationId, $clearAll=false): int
  852. {
  853. $rootUid = $this->findRootUidFor($organizationId);
  854. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  855. return $rootUid;
  856. }
  857. /**
  858. * Pack the status informations into an array for the getSiteStatusAction method
  859. *
  860. * @param int $organizationId
  861. * @param int $code
  862. * @param int|null $rootUid
  863. * @param array|null $warnings
  864. * @return array
  865. */
  866. private function buildStatusResult(
  867. int $organizationId,
  868. int $code,
  869. ?int $rootUid = null,
  870. ?array $warnings = null): array
  871. {
  872. $message = "";
  873. if($code == self::STATUS_NO_SUCH_WEBSITE) {
  874. $message = 'No website were found for organization ' . $organizationId;
  875. } elseif ($code == self::STATUS_EXISTING) {
  876. $message = 'A website exists for organization ' . $organizationId;
  877. }
  878. elseif ($code == self::STATUS_EXISTING_DELETED) {
  879. $message = 'A website exists for organization ' . $organizationId . ', but has been deleted';
  880. }
  881. elseif ($code == self::STATUS_EXISTING_HIDDEN) {
  882. $message = 'A website exists for organization ' . $organizationId . ', but is hidden or has a restricted access';
  883. } elseif ($code == self::STATUS_EXISTING_WITH_WARNINGS) {
  884. $message = 'A website exists for organization ' . $organizationId . ', but warnings were raised';
  885. }
  886. $title = '';
  887. if ($rootUid !== null) {
  888. $title = $this->otPageRepository->getPage($rootUid)['title'];
  889. }
  890. $status = [
  891. 'organization_id' => $organizationId,
  892. 'code' => $code,
  893. 'status' => self::STATUS_LBL[$code],
  894. 'message' => $message,
  895. 'root_uid' => $rootUid,
  896. 'title' => $title
  897. ];
  898. if ($warnings !== null) {
  899. $status['warnings'] = $warnings;
  900. }
  901. return $status;
  902. }
  903. /**
  904. * Perform a full scan of the website and returns a list of warnings
  905. *
  906. * @param int $organizationId
  907. * @param int $rootUid
  908. * @return array
  909. */
  910. private function scanSite(int $organizationId, int $rootUid) {
  911. $warnings = [];
  912. // fetch pages and root page
  913. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  914. $rootPage = null;
  915. $pageIndex = [];
  916. foreach ($pages as $page) {
  917. $pageIndex[$page['uid']] = $page;
  918. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  919. }
  920. // fetch organization and extradata
  921. $organization = $this->fetchOrganization($organizationId);
  922. $extraData = $this->fetchOrganizationExtraData($organizationId);
  923. // load site's settings (uncomment if needed)
  924. // $config = $this->findConfigFor($organizationId, $rootUid);
  925. // Check site's title
  926. if (trim($rootPage['title']) != trim($organization->getName())) {
  927. $warnings[] = "Site's title does not match the organization name";
  928. }
  929. // Who is the expected owner among the be_users? there should be only one.
  930. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  931. $queryBuilder->getRestrictions()->removeAll();
  932. $beUsers = $queryBuilder
  933. ->select('uid', 'username')
  934. ->from('be_users')
  935. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  936. ->execute()
  937. ->fetchAll();
  938. $owner = null;
  939. if (count($beUsers) > 1) {
  940. $warnings[] = 'Website is mounted on more than one be_user: ' .
  941. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  942. } elseif (count($beUsers) == 0) {
  943. $warnings[] = 'Website is not mounted on any be_user';
  944. } else {
  945. $owner = $beUsers[0];
  946. }
  947. // are template constants up to date?
  948. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  949. $actual_constants = $queryBuilder
  950. ->select('constants')
  951. ->from('sys_template')
  952. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  953. ->execute()
  954. ->fetchColumn(0);
  955. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  956. $norm = function ($s) {
  957. return strtolower(preg_replace('/\s/', '', $s));
  958. };
  959. if ($norm($expected_constants) != $norm($actual_constants)) {
  960. $warnings[] = 'Template constants need an update';
  961. }
  962. $expected_templates = [
  963. "OpenTalent.OtTemplating->home" => 0,
  964. "OpenTalent.OtTemplating->legal" => 0,
  965. "OpenTalent.OtTemplating->contact" => 0
  966. ];
  967. foreach ($pages as $page) {
  968. if ($page['deleted']) {
  969. continue;
  970. }
  971. // Is it the correct owner?
  972. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  973. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  974. }
  975. if (!$page['is_siteroot']) {
  976. // is the parent page state (deleted, hidden, restricted) the same as this page?
  977. $parent = $pageIndex[$page['pid']];
  978. if ($parent['deleted']) {
  979. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  980. }
  981. if ($parent['hidden'] && !$page['hidden']) {
  982. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  983. }
  984. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  985. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  986. }
  987. }
  988. // an expected template was found, remove it from the list of expected
  989. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  990. !$page['deleted'] && !$page['hidden']) {
  991. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  992. }
  993. }
  994. foreach ($expected_templates as $template => $_) {
  995. $warnings[] = 'No page with template ' . $template;
  996. }
  997. return $warnings;
  998. }
  999. /**
  1000. * Get the current status of the organization's website
  1001. *
  1002. * The result is an array of the form:
  1003. *
  1004. * [
  1005. * 'organization_id' => int,
  1006. * 'code' => int,
  1007. * 'status' => int,
  1008. * 'message' => string,
  1009. * 'root_uid' => ?int,
  1010. * 'site_title' => ?string,
  1011. * ('warnings' => array)
  1012. * ]
  1013. *
  1014. * If $statusOnly is true, the warnings entry won't be added
  1015. *
  1016. * The code value is among:
  1017. *
  1018. * - STATUS_NO_SUCH_WEBSITE
  1019. * - STATUS_EXISTING
  1020. * - STATUS_EXISTING_DELETED
  1021. * - STATUS_EXISTING_HIDDEN
  1022. * - STATUS_EXISTING_WITH_WARNINGS
  1023. *
  1024. * @param int $organizationId the organization's id whom site cache should be cleared
  1025. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1026. * the website pages will be performed.
  1027. * @return array
  1028. */
  1029. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): array
  1030. {
  1031. try {
  1032. $rootUid = $this->findRootUidFor($organizationId);
  1033. } catch (NoSuchWebsiteException $e) {
  1034. return $this->buildStatusResult($organizationId, self::STATUS_NO_SUCH_WEBSITE);
  1035. }
  1036. if ($rootUid['deleted']) {
  1037. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_DELETED, $rootUid);
  1038. }
  1039. if ($rootUid['hidden'] || ($rootUid['fe_group'] < 0)) {
  1040. return $this->buildStatusResult($organizationId, self::STATUS_EXISTING_HIDDEN, $rootUid);
  1041. }
  1042. $warnings = null;
  1043. if ($fullScan) {
  1044. // ** Look for potential issues
  1045. $warnings = $this->scanSite($organizationId, $rootUid);
  1046. }
  1047. return $this->buildStatusResult(
  1048. $organizationId,
  1049. $warnings ? self::STATUS_EXISTING_WITH_WARNINGS : self::STATUS_EXISTING,
  1050. $rootUid,
  1051. $warnings);
  1052. }
  1053. /**
  1054. * Set a new domain for the website.
  1055. * If $redirect is true, also add a redirection from the former domain to the new one
  1056. *
  1057. * @param int $organizationId
  1058. * @param string $newDomain
  1059. * @param bool $redirect
  1060. * @return int
  1061. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1062. * @throws NoSuchWebsiteException
  1063. */
  1064. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1065. {
  1066. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1067. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1068. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1069. }
  1070. $infos = $this->getSiteInfosAction($organizationId);
  1071. $originUrl = $infos['baseUrl'];
  1072. $rootUid = $infos['rootUid'];
  1073. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1074. if ($redirect) {
  1075. // Add the redirection
  1076. $this->addRedirection($originUrl, $newDomain);
  1077. }
  1078. return $rootUid;
  1079. }
  1080. /**
  1081. * Return all of the redirections from the given domain name,
  1082. * even if they have been marked as deleted.
  1083. *
  1084. * @param $domain string Domain name, without the http(s):// part
  1085. * @return array Rows from the sys_redirect table
  1086. */
  1087. protected function getRedirectionsFrom(string $domain): array
  1088. {
  1089. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1090. $queryBuilder->getRestrictions()->removeAll();
  1091. return $queryBuilder
  1092. ->select('*')
  1093. ->from('sys_redirect')
  1094. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1095. ->execute()
  1096. ->fetchAll();
  1097. }
  1098. /**
  1099. * Return all of the redirections to the given domain name,
  1100. * even if they have been marked as deleted.
  1101. *
  1102. * @param $domain string Domain name, without the http(s):// part
  1103. * @return array Rows from the sys_redirect table
  1104. */
  1105. protected function getRedirectionsTo(string $domain): array
  1106. {
  1107. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1108. $queryBuilder->getRestrictions()->removeAll();
  1109. return $queryBuilder
  1110. ->select('*')
  1111. ->from('sys_redirect')
  1112. ->where(
  1113. $queryBuilder->expr()->in(
  1114. 'target',
  1115. [
  1116. 'http://' . $queryBuilder->expr()->literal($domain),
  1117. 'https://' . $queryBuilder->expr()->literal($domain)
  1118. ]
  1119. )
  1120. )
  1121. ->execute()
  1122. ->fetchAll();
  1123. }
  1124. /**
  1125. * Add a new redirection from $fromDomain to $toDomain.
  1126. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1127. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1128. *
  1129. * @param $fromDomain
  1130. * @param $toDomain
  1131. * @return int Status of the operation
  1132. */
  1133. public function addRedirection($fromDomain, $toDomain): int
  1134. {
  1135. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1136. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1137. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1138. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1139. }
  1140. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1141. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1142. }
  1143. $existing = $this->getRedirectionsFrom($fromDomain);
  1144. $toUpdate = null;
  1145. foreach ($existing as $redirection) {
  1146. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1147. // a redirection from this domain already exists, and it is not deleted nor disabled
  1148. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1149. // the target is not the same domain
  1150. throw new \RuntimeException(
  1151. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1152. );
  1153. } else {
  1154. // else, target is already the same domain, it will be updated
  1155. $toUpdate = $redirection;
  1156. break;
  1157. }
  1158. } else {
  1159. // a redirection from this domain already exists, but it is deleted or disabled
  1160. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1161. // the target is the same domain, we'll reactivate this record
  1162. $toUpdate = $redirection;
  1163. break;
  1164. }
  1165. }
  1166. }
  1167. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1168. $data = [
  1169. 'deleted' => 0,
  1170. 'disabled' => 0,
  1171. 'source_host' => $fromDomain,
  1172. 'source_path' => '/.*/',
  1173. 'is_regexp' => 1,
  1174. 'force_https' => 0,
  1175. 'respect_query_parameters' => 0,
  1176. 'keep_query_parameters' => 1,
  1177. 'target' => 'https://' . $toDomain,
  1178. 'target_statuscode' => 301
  1179. ];
  1180. if ($toUpdate !== null) {
  1181. $q = $queryBuilder
  1182. ->update('sys_redirect')
  1183. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1184. foreach ($data as $k => $v) {
  1185. $q->set($k, $v);
  1186. }
  1187. $q->execute();
  1188. return self::REDIRECTION_UPDATED;
  1189. } else {
  1190. $queryBuilder
  1191. ->insert('sys_redirect')
  1192. ->values($data)
  1193. ->execute();
  1194. return self::REDIRECTION_CREATED;
  1195. }
  1196. }
  1197. /**
  1198. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1199. * If $hard is true, delete it completely.
  1200. *
  1201. * @param $fromDomain
  1202. * @param bool $hard
  1203. * @return int Number of affected rows
  1204. */
  1205. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1206. {
  1207. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1208. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1209. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1210. }
  1211. $existing = $this->getRedirectionsFrom($fromDomain);
  1212. $deleted = 0;
  1213. foreach ($existing as $redirection) {
  1214. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1215. $deleted += 1;
  1216. }
  1217. return $deleted;
  1218. }
  1219. /**
  1220. * Retrieve the Organization object from the repository and then,
  1221. * from the Opentalent API
  1222. * @param $organizationId
  1223. * @return Organization
  1224. */
  1225. private function fetchOrganization($organizationId) {
  1226. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1227. try {
  1228. return $organizationRepository->findById($organizationId);
  1229. } catch (ApiRequestException $e) {
  1230. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1231. }
  1232. }
  1233. /**
  1234. * Try to find the root page uid of the organization's website and return it.
  1235. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1236. *
  1237. * @param $organizationId
  1238. * @return int
  1239. * @throws NoSuchWebsiteException
  1240. */
  1241. private function findRootUidFor($organizationId) {
  1242. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1243. $queryBuilder->getRestrictions()->removeAll();
  1244. $rootUid = $queryBuilder
  1245. ->select('uid')
  1246. ->from('pages')
  1247. ->where('is_siteroot=1')
  1248. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1249. ->execute()
  1250. ->fetchColumn(0);
  1251. if ($rootUid > 0) {
  1252. return $rootUid;
  1253. }
  1254. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1255. }
  1256. /**
  1257. * Determine which folder-type Typo3 page should contain the new website
  1258. * CREATES IT if needed, and return its uid
  1259. *
  1260. * @return int
  1261. */
  1262. private function getParentFolderUid() {
  1263. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1264. $siteCount = $queryBuilder
  1265. ->count('uid')
  1266. ->from('pages')
  1267. ->where('is_siteroot=1')
  1268. ->execute()
  1269. ->fetchColumn(0);
  1270. $thousand = (int)(($siteCount + 1) / 1000);
  1271. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1272. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1273. $uid = $queryBuilder
  1274. ->select('uid')
  1275. ->from('pages')
  1276. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1277. ->andWhere('dokType=254')
  1278. ->execute()
  1279. ->fetchColumn(0);
  1280. if ($uid == null) {
  1281. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1282. $queryBuilder->insert('pages')
  1283. ->values([
  1284. 'pid' => 0,
  1285. 'title' => $folderName,
  1286. 'dokType' => 254,
  1287. 'sorting' => 11264,
  1288. 'perms_userid' => 1,
  1289. 'perms_groupid' => 31,
  1290. 'perms_group' => 27,
  1291. ])
  1292. ->execute();
  1293. $uid = $queryBuilder->getConnection()->lastInsertId();
  1294. }
  1295. return $uid;
  1296. }
  1297. /**
  1298. * Insert a new row in the 'pages' table of the Typo3 DB
  1299. * and return its uid
  1300. *
  1301. * @param Organization $organization
  1302. * @param int $pid
  1303. * @param string $title
  1304. * @param string $slug
  1305. * @param string $template
  1306. * @param array $moreValues
  1307. * @return int
  1308. */
  1309. private function insertPage(Organization $organization,
  1310. int $pid,
  1311. string $title,
  1312. string $slug,
  1313. string $template = '',
  1314. array $moreValues = []
  1315. ) {
  1316. $defaultValues = [
  1317. 'pid' => $pid,
  1318. 'perms_groupid' => 3,
  1319. 'perms_user' => 27,
  1320. 'cruser_id' => 1,
  1321. 'dokType' => self::DOK_PAGE,
  1322. 'title' => $title,
  1323. 'slug' => $slug,
  1324. 'backend_layout' => 'flux__grid',
  1325. 'backend_layout_next_level' => 'flux__grid',
  1326. 'tx_opentalent_structure_id' => $organization->getId()
  1327. ];
  1328. if ($template) {
  1329. $defaultValues['tx_fed_page_controller_action'] = $template;
  1330. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1331. }
  1332. $values = array_merge($defaultValues, $moreValues);
  1333. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1334. $queryBuilder->insert('pages')
  1335. ->values($values)
  1336. ->execute();
  1337. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1338. $this->createdPagesIndex[$slug] = $uid;
  1339. return $uid;
  1340. }
  1341. /**
  1342. * Insert the root page of a new organization's website
  1343. * and return its uid
  1344. *
  1345. * @param Organization $organization
  1346. * @return int
  1347. */
  1348. private function insertRootPage(Organization $organization) {
  1349. return $this->insertPage(
  1350. $organization,
  1351. $this->getParentFolderUid(),
  1352. $organization->getName(),
  1353. '/',
  1354. self::TEMPLATE_HOME,
  1355. [
  1356. 'is_siteroot' => 1,
  1357. 'TSconfig' => 'TCAdefaults.pages.tx_opentalent_structure_id =' . $organization->getId(),
  1358. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1359. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1360. ]
  1361. );
  1362. }
  1363. /**
  1364. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1365. *
  1366. * @param int $pid
  1367. * @param string $cType
  1368. * @param string $bodyText
  1369. * @param int $colPos
  1370. * @param array $moreValues
  1371. */
  1372. private function insertContent(int $pid,
  1373. string $cType=self::CTYPE_TEXT,
  1374. string $bodyText = '',
  1375. int $colPos=0,
  1376. array $moreValues = []) {
  1377. $defaultValues = [
  1378. 'pid' => $pid,
  1379. 'cruser_id' => 1,
  1380. 'CType' => $cType,
  1381. 'colPos' => $colPos,
  1382. 'bodyText' => $bodyText
  1383. ];
  1384. $values = array_merge($defaultValues, $moreValues);
  1385. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1386. $queryBuilder->insert('tt_content')
  1387. ->values($values)
  1388. ->execute();
  1389. }
  1390. private function fetchOrganizationExtraData(int $organizationId) {
  1391. $cnn = new PDO(
  1392. "mysql:host=prod-back;dbname=opentalent",
  1393. 'dbcloner',
  1394. 'wWZ4hYcrmHLW2mUK',
  1395. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1396. );
  1397. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1398. $stmt = $cnn->prepare(
  1399. "SELECT o.id, o.name, o.facebook, o.twitter,
  1400. o.category, o.logo_id, p.logoDonorsMove
  1401. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1402. ON o.parameters_id = p.id
  1403. WHERE o.id=" . $organizationId . ";"
  1404. );
  1405. $stmt->execute();
  1406. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1407. $data = $stmt->fetch();
  1408. $stmt = $cnn->prepare(
  1409. "SELECT c.email
  1410. FROM opentalent.ContactPoint c
  1411. INNER JOIN opentalent.organization_contactpoint o
  1412. ON o.contactPoint_id = c.id
  1413. WHERE c.contactType = 'PRINCIPAL'
  1414. AND o.organization_id = " . $organizationId . ";"
  1415. );
  1416. $stmt->execute();
  1417. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1418. $data['email'] = $stmt->fetch()['email'];
  1419. $stmt = $cnn->prepare(
  1420. "SELECT n.name, n.logo, n.url
  1421. FROM opentalent.Network n
  1422. INNER JOIN
  1423. (opentalent.NetworkOrganization l
  1424. INNER JOIN opentalent.Organization o
  1425. ON l.organization_id = o.id)
  1426. ON l.network_id = n.id
  1427. WHERE l.endDate is NULL
  1428. AND o.id=" . $organizationId . ";"
  1429. );
  1430. $stmt->execute();
  1431. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1432. $data['network'] = $stmt->fetch();
  1433. $stmt = $cnn->prepare(
  1434. "SELECT p.username, a.id, s.product
  1435. FROM opentalent.Person p
  1436. INNER JOIN Access a ON p.id = a.person_id
  1437. INNER JOIN Settings s on a.organization_id = s.organization_id
  1438. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1439. );
  1440. $stmt->execute();
  1441. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1442. $data['admin'] = $stmt->fetch();
  1443. return $data;
  1444. }
  1445. /**
  1446. * Return the content of `sys_template`.`constants` of
  1447. * the website of the given organization
  1448. *
  1449. * @param int $organizationId
  1450. * @param array $organizationExtraData
  1451. * @return string
  1452. */
  1453. private function getTemplateConstants(int $organizationId, array $organizationExtraData) {
  1454. return "plugin.tx_ottemplating {\n" .
  1455. " settings {\n" .
  1456. " organization {\n" .
  1457. " id = " . $organizationId . "\n" .
  1458. " name = " . $organizationExtraData['name'] . "\n" .
  1459. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1460. " email = " . $organizationExtraData['email'] . "\n" .
  1461. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1462. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1463. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1464. " }\n" .
  1465. " network {\n" .
  1466. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1467. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1468. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1469. " }\n" .
  1470. " }\n" .
  1471. "}";
  1472. }
  1473. /**
  1474. * Create the given directory, give its property to the www-data group and
  1475. * record it as a newly created dir (for an eventual rollback)
  1476. *
  1477. * @param string $dirPath
  1478. */
  1479. private function mkDir(string $dirPath) {
  1480. mkdir($dirPath);
  1481. $this->createdDirs[] = $dirPath;
  1482. chgrp($dirPath, 'www-data');
  1483. }
  1484. /**
  1485. * Write the given file with content, give its property to the www-data group and
  1486. * record it as a newly created file (for an eventual rollback)
  1487. *
  1488. * @param string $path
  1489. * @param string $content
  1490. */
  1491. private function writeFile(string $path, string $content) {
  1492. $f = fopen($path, "w");
  1493. try
  1494. {
  1495. fwrite($f, $content);
  1496. $this->createdFiles[] = $path;
  1497. chgrp($path, 'www-data');
  1498. } finally {
  1499. fclose($f);
  1500. }
  1501. }
  1502. /**
  1503. * Try to find the config file of the website in the less resource-consuming way
  1504. * and parse it.
  1505. *
  1506. * @param int $organizationId
  1507. * @param int $rootUid
  1508. * @return array Path of the configuration file and parsed configuration of the website
  1509. */
  1510. protected function findConfigFileAndContentFor(int $organizationId, int $rootUid) {
  1511. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1512. $candidates = scandir($configs_directory);
  1513. // try to filter by directory name
  1514. foreach ($candidates as $subdir) {
  1515. if (preg_match('/\.*_' . $organizationId . '$/', $subdir)) {
  1516. $filename = $configs_directory . $subdir . '/config.yaml';
  1517. $yamlConfig = Yaml::parseFile($filename);
  1518. if ($yamlConfig['rootPageId'] === $rootUid) {
  1519. return [$filename, $yamlConfig];
  1520. }
  1521. }
  1522. }
  1523. // it wasn't found the easy way, let's look to each file... :(
  1524. foreach ($candidates as $subdir) {
  1525. $yamlConfig = Yaml::parseFile($filename);
  1526. if ($yamlConfig['rootPageId'] === $rootUid) {
  1527. return [$filename, $yamlConfig];
  1528. }
  1529. }
  1530. return [null, []];
  1531. }
  1532. /**
  1533. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1534. * @param int $organizationId
  1535. * @param int $rootUid
  1536. * @return array Configuration of the website
  1537. */
  1538. protected function findConfigFor(int $organizationId, int $rootUid) {
  1539. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1540. return $pathAndConfig[1];
  1541. }
  1542. /**
  1543. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1544. * @param int $organizationId
  1545. * @param int $rootUid
  1546. * @return string Path of the config file of the given website
  1547. */
  1548. protected function findConfigFilePathFor(int $organizationId, int $rootUid) {
  1549. $pathAndConfig = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1550. return $pathAndConfig[0];
  1551. }
  1552. /**
  1553. * Create or update the .../sites/.../config.yaml file of the given site
  1554. *
  1555. * @param int $organizationId
  1556. * @param int $rootUid
  1557. * @param string $domain
  1558. * @param bool $forceRecreate
  1559. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1560. */
  1561. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false) {
  1562. $existing = $this->findConfigFileAndContentFor($organizationId, $rootUid);
  1563. $configFilename = $existing[0];
  1564. $config = $existing[1];
  1565. $subdomain = explode('.', $domain)[0];
  1566. if (!$configFilename) {
  1567. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1568. $configFilename = $configDir . "/config.yaml";
  1569. $isNew = true;
  1570. if (file_exists($configFilename)) {
  1571. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1572. }
  1573. } else {
  1574. $configDir = dirname($configFilename);
  1575. $config['base'] = 'https://' . $domain;
  1576. $isNew = false;
  1577. }
  1578. if ($isNew || $forceRecreate) {
  1579. $config = ['base' => 'https://' . $domain,
  1580. 'baseVariants' => [
  1581. ['base' => $subdomain . '/',
  1582. 'condition' => 'applicationContext == "Development"']
  1583. ],
  1584. 'errorHandling' => [
  1585. ['errorCode' => '404',
  1586. 'errorHandler' => 'PHP',
  1587. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1588. ['errorCode' => '403',
  1589. 'errorHandler' => 'PHP',
  1590. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1591. ],
  1592. 'flux_content_types' => '',
  1593. 'flux_page_templates' => '',
  1594. 'languages' => [[
  1595. 'title' => 'Fr',
  1596. 'enabled' => True,
  1597. 'base' => '/',
  1598. 'typo3Language' => 'fr',
  1599. 'locale' => 'fr_FR',
  1600. 'iso-639-1' => 'fr',
  1601. 'navigationTitle' => 'Fr',
  1602. 'hreflang' => 'fr-FR',
  1603. 'direction' => 'ltr',
  1604. 'flag' => 'fr',
  1605. 'languageId' => '0',
  1606. ]],
  1607. 'rootPageId' => $rootUid,
  1608. 'routes' => []
  1609. ];
  1610. }
  1611. $yamlConfig = Yaml::dump($config, 99, 2);
  1612. if (!file_exists($configDir)) {
  1613. $this->mkDir($configDir);
  1614. }
  1615. GeneralUtility::writeFile($configFilename, $yamlConfig);
  1616. // Set the owner and mods, in case www-data is not the one who run this command
  1617. // @see https://www.php.net/manual/fr/function.stat.php
  1618. try {
  1619. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1620. chown($configFilename, $stats['4']);
  1621. chgrp($configFilename, $stats['5']);
  1622. chmod($configFilename, $stats['2']);
  1623. } catch (\TYPO3\CMS\Core\Error\Exception $e) {
  1624. }
  1625. // Flush cache:
  1626. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1627. $cacheSystem->remove('site-configuration');
  1628. $cacheSystem->remove('pseudo-sites');
  1629. }
  1630. /**
  1631. * Create the BE user for the website
  1632. * The user shall be already created in the Opentalent DB
  1633. *
  1634. * @param int $organizationId
  1635. * @param int $rootUid
  1636. * @param string $domain
  1637. * @param array $userData
  1638. * @return int
  1639. */
  1640. private function createBeUser(int $organizationId,
  1641. int $rootUid,
  1642. string $domain,
  1643. array $userData) {
  1644. if (!isset($userData['username'])) {
  1645. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1646. }
  1647. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1648. $randomStr = (new Random)->generateRandomHexString(20);
  1649. // get the existing filemounts
  1650. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1651. $queryBuilder
  1652. ->select('uid')
  1653. ->from('sys_filemounts')
  1654. ->where("path LIKE '%user_upload/" . $organizationId . "/%'");
  1655. $statement = $queryBuilder->execute();
  1656. $rows = $statement->fetchAll(3) ?: [];
  1657. $files = [];
  1658. foreach ($rows as $row) {
  1659. $files[] = $row[0];
  1660. }
  1661. $values = [
  1662. 'username' => $userData['username'],
  1663. 'password' => $randomStr,
  1664. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $domain . ' (id: ' . $userData['id'] . ')',
  1665. 'deleted' => 0,
  1666. 'lang' => 'fr',
  1667. 'usergroup' => isset(self::PRODUCT_MAPPING[$user_data['product']]) ? self::PRODUCT_MAPPING[$userData['product']] : 1,
  1668. 'db_mountpoints' => $rootUid,
  1669. 'userMods' => 'file_FilelistList',
  1670. 'file_mountPoints' => join(',', $files),
  1671. 'options' => 2,
  1672. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  1673. 'tx_opentalent_opentalentId' => $userData['id'],
  1674. 'tx_opentalent_organizationId' => $organizationId,
  1675. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1676. ];
  1677. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1678. $queryBuilder->insert('be_users')
  1679. ->values($values)
  1680. ->execute();
  1681. return $queryBuilder->getConnection()->lastInsertId();
  1682. }
  1683. /**
  1684. * Enable frontend editing for user
  1685. *
  1686. * @param int $adminUid
  1687. */
  1688. private function enableFeEditing(int $adminUid) {
  1689. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  1690. $user = $BE_USER->getRawUserByUid($adminUid);
  1691. $BE_USER->user = $user;
  1692. $BE_USER->backendSetUC();
  1693. $BE_USER->uc['frontend_editing'] = 1;
  1694. $BE_USER->uc['frontend_editing_overlay'] = 1;
  1695. $BE_USER->writeUC($BE_USER->uc);
  1696. }
  1697. }