SiteController.php 92 KB

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