SiteController.php 98 KB

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