SiteController.php 90 KB

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