SiteController.php 93 KB

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