SiteController.php 91 KB

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