SiteController.php 96 KB

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