SiteController.php 90 KB

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