SiteController.php 87 KB

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