SiteController.php 87 KB

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