SiteController.php 102 KB

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