SiteController.php 96 KB

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