SiteController.php 91 KB

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