SiteController.php 95 KB

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