SiteController.php 89 KB

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