SiteController.php 81 KB

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