SiteController.php 91 KB

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