SiteController.php 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511
  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. ($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 = $this->getOrganizationDomain($organizationId);
  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` and the `pages`.`TSConfig` fields
  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 = $this->getOrganizationDomain($organizationId);
  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` and the `pages`.`TSConfig` fields
  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. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  590. $queryBuilder
  591. ->update('pages')
  592. ->set('TSconfig', $this->getRootPageTsConfig($organization))
  593. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  594. ->execute();
  595. // ## Reset the users permissions
  596. if ($deep) {
  597. $this->resetBeUserPermsAction($organizationId, true);
  598. }
  599. // ## Reset the routing index
  600. // TODO: complete
  601. // Try to commit the result
  602. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  603. if (!$commitSuccess) {
  604. throw new \RuntimeException('Something went wrong while committing the result');
  605. }
  606. } catch(\Throwable $e) {
  607. // rollback
  608. $this->connectionPool->getConnectionByName('Default')->rollback();
  609. throw $e;
  610. }
  611. // ## Clear the Typo3 cache for the website
  612. OtCacheManager::clearSiteCache($rootUid, true);
  613. return $rootUid;
  614. }
  615. /**
  616. * Delete the website with all its pages, contents and related records
  617. *
  618. * If the hard parameter is false, the records' `deleted` field will be set to true and
  619. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  620. *
  621. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  622. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  623. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  624. *
  625. * $redirectTo is the optional organization id to whom requests will be redirected
  626. *
  627. * The $force parameter, if true, will both bypass the 'DEL###' file confirmation and recursively delete the
  628. * user_upload and form_definitions of the website. <!> USE WITH CAUTION
  629. *
  630. * @param int $organizationId
  631. * @param bool $hard
  632. * @param int|null $redirectTo
  633. * @param bool $force
  634. * @return int
  635. * @throws NoSuchRecordException
  636. * @throws NoSuchWebsiteException
  637. * @throws \Doctrine\DBAL\DBALException
  638. * @throws \Throwable
  639. */
  640. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null, bool $force = false) {
  641. $rootUid = $this->findRootUidFor($organizationId);
  642. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  643. $isDeleted = $queryBuilder
  644. ->select('deleted')
  645. ->from('pages')
  646. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  647. ->execute()
  648. ->fetchColumn(0) == 1;
  649. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  650. if ($hard && !file_exists($confirm_file) && !$force) {
  651. throw new \RuntimeException(
  652. "You are going to completely delete the website with root uid " . $rootUid .
  653. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  654. $confirm_file . "', and launch this command again."
  655. );
  656. }
  657. // Prepare the redirection
  658. if ($redirectTo) {
  659. if ($redirectTo == $organizationId) {
  660. throw new \InvalidArgumentException('redirectTo value has to be different from the organizationId');
  661. }
  662. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  663. $targetUrl = $this->getSiteInfosAction($redirectTo)->getBaseUrl();
  664. }
  665. // start transactions
  666. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  667. // keep track of renamed file for an eventual rollback
  668. $renamed = [];
  669. try {
  670. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  671. foreach($pages as $page) {
  672. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  673. $this->delete('pages', 'uid', $page['uid'], $hard);
  674. }
  675. $this->delete('tt_content', 'pid', $rootUid, $hard);
  676. $this->delete('pages', 'uid', $rootUid, $hard);
  677. $this->delete('sys_template', 'pid', $rootUid, $hard);
  678. if ($hard) {
  679. // there is no 'deleted' field in sys_domain
  680. $this->delete('sys_domain', 'pid', $rootUid, $hard);
  681. }
  682. try {
  683. $adminBeUserUid = $this->findAdminBeUserUid($rootUid);
  684. if ($adminBeUserUid !== null) {
  685. $this->delete('be_users', 'uid', $adminBeUserUid, $hard);
  686. }
  687. } catch (NoSuchRecordException $e) {}
  688. try {
  689. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  690. if ($editorsGroupUid !== null) {
  691. $this->delete('be_groups', 'uid', $editorsGroupUid, $hard);
  692. }
  693. } catch (NoSuchRecordException $e) {}
  694. // Delete the filemounts
  695. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  696. $queryBuilder
  697. ->select('uid')
  698. ->from('sys_filemounts')
  699. ->where("path LIKE '%user_upload/" . $organizationId . "/%'")
  700. ->orWhere("path LIKE '%form_definitions/" . $organizationId . "/%'");
  701. $statement = $queryBuilder->execute();
  702. $rows = $statement->fetchAll();
  703. foreach ($rows as $row) {
  704. $this->delete('sys_filemounts', 'uid', $row['uid'], $hard);
  705. }
  706. // Look up for the config.yaml file of the website
  707. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  708. $configYamlFile = "";
  709. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  710. if (!$isDeleted) {
  711. $yamlFile = $subdir . '/config.yaml';
  712. } else {
  713. $yamlFile = $subdir . '/config.yaml.deleted';
  714. }
  715. if (is_file($yamlFile)) {
  716. $conf = Yaml::parseFile($yamlFile);
  717. if ($conf['rootPageId'] == $rootUid) {
  718. $configYamlFile = $yamlFile;
  719. break;
  720. }
  721. }
  722. }
  723. if (!$isDeleted) {
  724. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  725. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/' . $organizationId . '/';
  726. } else {
  727. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  728. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/deleted_' . $organizationId . '/';
  729. }
  730. // If hard deletion, verify that dirs are empty
  731. if (!$force) {
  732. foreach ([$uploadDir, $formsDir] as $dir) {
  733. if ($hard && is_dir($dir)) {
  734. foreach (scandir($dir) as $subdir) {
  735. if ($subdir == '.' or $subdir == '..') {
  736. continue;
  737. }
  738. $subdir = $dir . $subdir;
  739. if (!is_dir($subdir)) {
  740. throw new \RuntimeException(
  741. 'The directory ' . $dir . ' contains non-directory files' .
  742. ', this humble script prefers not to take care of them automatically. Abort.');
  743. }
  744. if (is_readable($subdir)) {
  745. foreach (scandir($subdir) as $filename) {
  746. if ($filename != '.' && $filename != '..') {
  747. throw new \RuntimeException(
  748. 'The directory ' . $subdir . ' is not empty, ' .
  749. 'this humble script prefers not to take care of them automatically. Abort.');
  750. }
  751. }
  752. }
  753. }
  754. }
  755. }
  756. }
  757. // If soft deletion, check that no deleted file or directory exist
  758. if (!$hard) {
  759. $toRename = [];
  760. if (!$hard) {
  761. if (is_file($configYamlFile)) {
  762. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  763. }
  764. if (is_dir($uploadDir)) {
  765. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  766. }
  767. }
  768. foreach ($toRename as $initialPath => $newPath) {
  769. if (is_file($newPath)) {
  770. throw new \RuntimeException(
  771. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  772. }
  773. }
  774. }
  775. // Delete or rename files and dirs
  776. if ($hard) {
  777. if (is_file($configYamlFile)) {
  778. unlink($configYamlFile);
  779. }
  780. if (is_dir(dirname($configYamlFile))) {
  781. FileUtility::rmdir(dirname($configYamlFile), $force);
  782. }
  783. if (is_dir($uploadDir)) {
  784. FileUtility::rmdir($uploadDir, $force);
  785. }
  786. if (is_dir($formsDir)) {
  787. FileUtility::rmdir($formsDir, $force);
  788. }
  789. } else {
  790. $renamed = [];
  791. foreach ($toRename as $initialPath => $newPath) {
  792. rename($initialPath, $newPath);
  793. $renamed[$initialPath] = $newPath;
  794. }
  795. }
  796. // Add the redirection
  797. if ($redirectTo) {
  798. $this->addRedirection($originUrl, $targetUrl);
  799. }
  800. // Try to commit the result
  801. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  802. if (!$commitSuccess) {
  803. throw new \RuntimeException('Something went wrong while commiting the result');
  804. }
  805. return $rootUid;
  806. } catch(\Throwable $e) {
  807. // rollback
  808. $this->connectionPool->getConnectionByName('Default')->rollback();
  809. if (!$hard) {
  810. foreach ($renamed as $initialPath => $newPath) {
  811. rename($newPath, $initialPath);
  812. }
  813. }
  814. throw $e;
  815. } finally {
  816. if (file_exists($confirm_file)) {
  817. unlink($confirm_file);
  818. }
  819. }
  820. }
  821. /**
  822. * Delete a record from the typo3 db.
  823. * If $hard is true, the record is permanently deleted.
  824. * Else, it's just marked as deleted.
  825. *
  826. * @param string $table
  827. * @param string $whereKey
  828. * @param $whereValue
  829. * @param int $hard
  830. */
  831. private function delete(string $table, string $whereKey, $whereValue, $hard=0) {
  832. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  833. if (!$hard) {
  834. $queryBuilder
  835. ->update($table)
  836. ->set('deleted', 1)
  837. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  838. ->execute();
  839. } else {
  840. $queryBuilder
  841. ->delete($table)
  842. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  843. ->execute();
  844. }
  845. }
  846. /**
  847. * Undo a soft-deletion performed using deleteSiteAction()
  848. *
  849. * @param int $organizationId
  850. * @return int
  851. * @throws NoSuchWebsiteException
  852. * @throws \Doctrine\DBAL\ConnectionException
  853. * @throws \Doctrine\DBAL\DBALException
  854. */
  855. public function undeleteSiteAction(int $organizationId) {
  856. $rootUid = $this->findRootUidFor($organizationId);
  857. // start transactions
  858. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  859. // keep track of renamed file for an eventual rollback
  860. $renamed = [];
  861. try {
  862. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  863. foreach($pages as $page) {
  864. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  865. $queryBuilder
  866. ->update('tt_content')
  867. ->set('deleted', 0)
  868. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  869. ->execute();
  870. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  871. $queryBuilder
  872. ->update('pages')
  873. ->set('deleted', 0)
  874. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  875. ->execute();
  876. }
  877. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  878. $queryBuilder
  879. ->update('tt_content')
  880. ->set('deleted', 0)
  881. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  882. ->execute();
  883. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  884. $queryBuilder
  885. ->update('pages')
  886. ->set('deleted', 0)
  887. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  888. ->execute();
  889. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  890. $queryBuilder
  891. ->update('sys_template')
  892. ->set('deleted', 0)
  893. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  894. ->execute();
  895. // remove filemounts
  896. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  897. $queryBuilder
  898. ->update('sys_filemounts')
  899. ->set('deleted', 0)
  900. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/'"))
  901. ->execute();
  902. try {
  903. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid, false);
  904. if ($editorsGroupUid !== null) {
  905. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  906. $queryBuilder
  907. ->update('be_groups')
  908. ->set('deleted', 0)
  909. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  910. ->execute();
  911. }
  912. } catch (NoSuchRecordException $e) {}
  913. try {
  914. $adminBeUserUid = $this->findAdminBeUserUid($rootUid, false);
  915. if ($adminBeUserUid !== null) {
  916. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  917. $queryBuilder
  918. ->update('be_users')
  919. ->set('deleted', 0)
  920. ->where($queryBuilder->expr()->eq('uid', $adminBeUserUid))
  921. ->execute();
  922. }
  923. } catch (NoSuchRecordException $e) {}
  924. // Look up for the config.yaml file of the website
  925. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  926. $configYamlFile = "";
  927. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  928. $yamlFile = $subdir . '/config.yaml.deleted';
  929. if (is_file($yamlFile)) {
  930. $conf = Yaml::parseFile($yamlFile);
  931. if ($conf['rootPageId'] == $rootUid) {
  932. $configYamlFile = $yamlFile;
  933. break;
  934. }
  935. }
  936. }
  937. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  938. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/deleted_' . $organizationId . '/';
  939. $toRename = [];
  940. if (is_file($configYamlFile)) {
  941. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  942. }
  943. if (is_dir($uploadDir)) {
  944. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  945. }
  946. if (is_dir($formsDir)) {
  947. $toRename[$formsDir] = dirname($formsDir) . '/' . $organizationId;
  948. }
  949. foreach ($toRename as $initialPath => $newPath) {
  950. if (is_file($newPath)) {
  951. throw new \RuntimeException(
  952. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  953. }
  954. }
  955. $renamed = [];
  956. foreach ($toRename as $initialPath => $newPath) {
  957. rename($initialPath, $newPath);
  958. $renamed[$initialPath] = $newPath;
  959. }
  960. // remove eventual redirection from this site to another
  961. $originUrl = $this->getSiteInfosAction($organizationId)->getBaseUrl();
  962. $this->removeRedirectionsFrom($originUrl);
  963. // Try to commit the result
  964. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  965. if (!$commitSuccess) {
  966. throw new \RuntimeException('Something went wrong while commiting the result');
  967. }
  968. return $rootUid;
  969. } catch(\Throwable $e) {
  970. // rollback
  971. $this->connectionPool->getConnectionByName('Default')->rollback();
  972. foreach ($renamed as $initialPath => $newPath) {
  973. rename($newPath, $initialPath);
  974. }
  975. throw $e;
  976. }
  977. }
  978. /**
  979. * Clear the cache of the organization's website
  980. *
  981. * @param int $organizationId the organization's id whom site cache should be cleared
  982. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  983. * @return int
  984. * @throws NoSuchWebsiteException
  985. */
  986. public function clearSiteCacheAction(int $organizationId, $clearAll=false): int
  987. {
  988. $rootUid = $this->findRootUidFor($organizationId);
  989. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  990. return $rootUid;
  991. }
  992. /**
  993. * Perform a full scan of the website and returns a list of warnings
  994. *
  995. * @param int $organizationId
  996. * @param int $rootUid
  997. * @return array
  998. */
  999. private function scanSite(int $organizationId, int $rootUid) {
  1000. $warnings = [];
  1001. // fetch pages and root page
  1002. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  1003. $rootPage = null;
  1004. $pageIndex = [];
  1005. foreach ($pages as $page) {
  1006. $pageIndex[$page['uid']] = $page;
  1007. if ($page['is_siteroot'] == 1) { $rootPage = $page; }
  1008. }
  1009. // fetch organization and extradata
  1010. $organization = $this->fetchOrganization($organizationId);
  1011. $extraData = $this->fetchOrganizationExtraData($organizationId);
  1012. // load site's settings (uncomment if needed)
  1013. // $config = $this->findConfigFor($rootUid);
  1014. // Check site's title
  1015. if (trim($rootPage['title']) != trim($organization->getName())) {
  1016. $warnings[] = "Site's title does not match the organization name";
  1017. }
  1018. // Who is the expected owner among the be_users? there should be only one.
  1019. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1020. $queryBuilder->getRestrictions()->removeAll();
  1021. $beUsers = $queryBuilder
  1022. ->select('uid', 'username')
  1023. ->from('be_users')
  1024. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  1025. ->execute()
  1026. ->fetchAll();
  1027. $owner = null;
  1028. if (count($beUsers) > 1) {
  1029. $warnings[] = 'Website is mounted on more than one be_user: ' .
  1030. join(', ', array_map(function($u) { return $u['username']; } ,$beUsers));
  1031. } elseif (count($beUsers) == 0) {
  1032. $warnings[] = 'Website is not mounted on any be_user';
  1033. } else {
  1034. $owner = $beUsers[0];
  1035. }
  1036. // are template constants up to date?
  1037. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1038. $actual_constants = $queryBuilder
  1039. ->select('constants')
  1040. ->from('sys_template')
  1041. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  1042. ->execute()
  1043. ->fetchColumn(0);
  1044. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  1045. $norm = function ($s) {
  1046. return strtolower(preg_replace('/\s/', '', $s));
  1047. };
  1048. if ($norm($expected_constants) != $norm($actual_constants)) {
  1049. $warnings[] = 'Template constants need an update';
  1050. }
  1051. $expected_templates = [
  1052. "OpenTalent.OtTemplating->home" => 0,
  1053. "OpenTalent.OtTemplating->legal" => 0,
  1054. "OpenTalent.OtTemplating->contact" => 0
  1055. ];
  1056. foreach ($pages as $page) {
  1057. if ($page['deleted']) {
  1058. continue;
  1059. }
  1060. // Is it the correct owner?
  1061. if ($owner !== null && !$page['deleted'] && $page['perms_userid'] != $owner['uid']) {
  1062. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  1063. }
  1064. if (!$page['is_siteroot']) {
  1065. // is the parent page state (deleted, hidden, restricted) the same as this page?
  1066. $parent = $pageIndex[$page['pid']];
  1067. if ($parent['deleted']) {
  1068. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  1069. }
  1070. if ($parent['hidden'] && !$page['hidden']) {
  1071. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  1072. }
  1073. if ($parent['fe_group'] < 0 && !$page['fe_group'] >= 0) {
  1074. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  1075. }
  1076. }
  1077. // an expected template was found, remove it from the list of expected
  1078. if (in_array($page['tx_fed_page_controller_action'], $expected_templates) &&
  1079. !$page['deleted'] && !$page['hidden']) {
  1080. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  1081. }
  1082. }
  1083. foreach ($expected_templates as $template => $_) {
  1084. $warnings[] = 'No page with template ' . $template;
  1085. }
  1086. return $warnings;
  1087. }
  1088. /**
  1089. * Get the current status and informations of the organization's website
  1090. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  1091. *
  1092. * The status is among:
  1093. *
  1094. * - STATUS_NO_SUCH_WEBSITE
  1095. * - STATUS_EXISTING
  1096. * - STATUS_EXISTING_DELETED
  1097. * - STATUS_EXISTING_HIDDEN
  1098. * - STATUS_EXISTING_WITH_WARNINGS
  1099. *
  1100. * @param int $organizationId the organization's id whom site cache should be cleared
  1101. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1102. * the website pages will be performed.
  1103. * @return SiteStatus
  1104. */
  1105. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  1106. {
  1107. try {
  1108. $siteInfos = $this->getSiteInfosAction($organizationId);
  1109. } catch (NoSuchWebsiteException $e) {
  1110. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  1111. }
  1112. if ($siteInfos->isDeleted()) {
  1113. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  1114. }
  1115. if ($siteInfos->isHiddenOrRestricted()) {
  1116. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  1117. }
  1118. $warnings = null;
  1119. if ($fullScan) {
  1120. // ** Look for potential issues
  1121. $warnings = $this->scanSite($organizationId, $siteInfos->getRootUid());
  1122. }
  1123. return new SiteStatus(
  1124. $organizationId,
  1125. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  1126. $siteInfos,
  1127. $warnings
  1128. );
  1129. }
  1130. /**
  1131. * Set a new domain for the website.
  1132. * If $redirect is true, also add a redirection from the former domain to the new one
  1133. *
  1134. * @param int $organizationId
  1135. * @param string $newDomain
  1136. * @param bool $redirect
  1137. * @return int
  1138. * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
  1139. * @throws NoSuchWebsiteException
  1140. */
  1141. public function setSiteDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1142. {
  1143. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1144. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1145. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1146. }
  1147. $infos = $this->getSiteInfosAction($organizationId);
  1148. $originUrl = $infos->getBaseUrl();
  1149. $rootUid = $infos->getRootUid();
  1150. if (preg_replace('/https?:\/\//', '', $originUrl) == preg_replace('/https?:\/\//', '', $newDomain) ) {
  1151. throw new \RuntimeException('The new domain should be different of the current one');
  1152. }
  1153. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1154. if ($redirect) {
  1155. // Add the redirection
  1156. $this->addRedirection($originUrl, $newDomain);
  1157. }
  1158. return $rootUid;
  1159. }
  1160. /**
  1161. * Return all of the redirections from the given domain name,
  1162. * even if they have been marked as deleted.
  1163. *
  1164. * @param $domain string Domain name, without the http(s):// part
  1165. * @return array Rows from the sys_redirect table
  1166. */
  1167. protected function getRedirectionsFrom(string $domain): array
  1168. {
  1169. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1170. $queryBuilder->getRestrictions()->removeAll();
  1171. return $queryBuilder
  1172. ->select('*')
  1173. ->from('sys_redirect')
  1174. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1175. ->execute()
  1176. ->fetchAll();
  1177. }
  1178. /**
  1179. * Return all of the redirections to the given domain name,
  1180. * even if they have been marked as deleted.
  1181. *
  1182. * @param $domain string Domain name, without the http(s):// part
  1183. * @return array Rows from the sys_redirect table
  1184. */
  1185. protected function getRedirectionsTo(string $domain): array
  1186. {
  1187. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1188. $queryBuilder->getRestrictions()->removeAll();
  1189. return $queryBuilder
  1190. ->select('*')
  1191. ->from('sys_redirect')
  1192. ->where(
  1193. $queryBuilder->expr()->in(
  1194. 'target',
  1195. [
  1196. 'http://' . $queryBuilder->expr()->literal($domain),
  1197. 'https://' . $queryBuilder->expr()->literal($domain)
  1198. ]
  1199. )
  1200. )
  1201. ->execute()
  1202. ->fetchAll();
  1203. }
  1204. /**
  1205. * Add a new redirection from $fromDomain to $toDomain.
  1206. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1207. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1208. *
  1209. * @param $fromDomain
  1210. * @param $toDomain
  1211. * @return int Status of the operation
  1212. */
  1213. public function addRedirection($fromDomain, $toDomain): int
  1214. {
  1215. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1216. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1217. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1218. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1219. }
  1220. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1221. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1222. }
  1223. $existing = $this->getRedirectionsFrom($fromDomain);
  1224. $toUpdate = null;
  1225. foreach ($existing as $redirection) {
  1226. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1227. // a redirection from this domain already exists, and it is not deleted nor disabled
  1228. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1229. // the target is not the same domain
  1230. throw new \RuntimeException(
  1231. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1232. );
  1233. } else {
  1234. // else, target is already the same domain, it will be updated
  1235. $toUpdate = $redirection;
  1236. break;
  1237. }
  1238. } else {
  1239. // a redirection from this domain already exists, but it is deleted or disabled
  1240. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1241. // the target is the same domain, we'll reactivate this record
  1242. $toUpdate = $redirection;
  1243. break;
  1244. }
  1245. }
  1246. }
  1247. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1248. $data = [
  1249. 'deleted' => 0,
  1250. 'disabled' => 0,
  1251. 'source_host' => $fromDomain,
  1252. 'source_path' => '/.*/',
  1253. 'is_regexp' => 1,
  1254. 'force_https' => 0,
  1255. 'respect_query_parameters' => 0,
  1256. 'keep_query_parameters' => 1,
  1257. 'target' => 'https://' . $toDomain,
  1258. 'target_statuscode' => 301
  1259. ];
  1260. if ($toUpdate !== null) {
  1261. $q = $queryBuilder
  1262. ->update('sys_redirect')
  1263. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1264. foreach ($data as $k => $v) {
  1265. $q->set($k, $v);
  1266. }
  1267. $q->execute();
  1268. return self::REDIRECTION_UPDATED;
  1269. } else {
  1270. $queryBuilder
  1271. ->insert('sys_redirect')
  1272. ->values($data)
  1273. ->execute();
  1274. return self::REDIRECTION_CREATED;
  1275. }
  1276. }
  1277. /**
  1278. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1279. * If $hard is true, delete it completely.
  1280. *
  1281. * @param $fromDomain
  1282. * @param bool $hard
  1283. * @return int Number of affected rows
  1284. */
  1285. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1286. {
  1287. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1288. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1289. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1290. }
  1291. $existing = $this->getRedirectionsFrom($fromDomain);
  1292. $deleted = 0;
  1293. foreach ($existing as $redirection) {
  1294. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1295. $deleted += 1;
  1296. }
  1297. return $deleted;
  1298. }
  1299. /**
  1300. * Set the rights of admin and editors of the website
  1301. * on all of the existing pages, including deleted ones
  1302. *
  1303. * @param int $organizationId
  1304. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1305. * @param int|null $editorsGroupUid Force the editors be-group uid
  1306. * @param int|null $adminUid Force the admin be-user uid
  1307. * @return int The uid of the website root page
  1308. * @throws NoSuchWebsiteException
  1309. * @throws NoSuchRecordException
  1310. */
  1311. protected function setBeUserPerms(
  1312. int $organizationId,
  1313. bool $createIfMissing = false,
  1314. int $editorsGroupUid = null,
  1315. int $adminUid = null
  1316. ): int
  1317. {
  1318. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1319. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1320. "and force the admin or group uid at the same time.");
  1321. }
  1322. $rootUid = $this->findRootUidFor($organizationId);
  1323. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1324. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']];
  1325. if ($editorsGroupUid == null) {
  1326. try {
  1327. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1328. } catch (NoSuchRecordException $e) {
  1329. if (!$createIfMissing) {
  1330. throw $e;
  1331. }
  1332. }
  1333. }
  1334. if ($adminUid == null) {
  1335. try {
  1336. $adminUid = $this->findAdminBeUserUid($rootUid);
  1337. } catch (NoSuchRecordException $e) {
  1338. if (!$createIfMissing) {
  1339. throw $e;
  1340. }
  1341. }
  1342. }
  1343. // Creates or update the admin be_group
  1344. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1345. $organizationId,
  1346. $rootUid,
  1347. $organizationExtraData['admin'],
  1348. $editorsGroupUid
  1349. );
  1350. // Creates or update the admin be_user
  1351. $adminUid = $this->createOrUpdateBeUser(
  1352. $organizationId,
  1353. $rootUid,
  1354. $editorsGroupUid,
  1355. $organizationExtraData['admin'],
  1356. $adminUid
  1357. );
  1358. // Reset the appartenance to groups
  1359. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1360. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1361. $queryBuilder
  1362. ->update('be_users')
  1363. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1364. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1365. ->execute();
  1366. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1367. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1368. $queryBuilder
  1369. ->update('be_groups')
  1370. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1371. ->set('subgroup', $mainEditorGroupUid)
  1372. ->execute();
  1373. // setup default owner for the website
  1374. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1375. $tsConfig = $queryBuilder->select('TSconfig')
  1376. ->from('pages')
  1377. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1378. ->execute()
  1379. ->fetchColumn(0);
  1380. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1381. $tsConfig .= "\nTCEMAIN {\n" .
  1382. " permissions.userid = " . $adminUid ."\n" .
  1383. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1384. "}";
  1385. $queryBuilder
  1386. ->update('pages')
  1387. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1388. ->set('TSconfig', $tsConfig)
  1389. ->execute();
  1390. // fetch pages and root page
  1391. $pages = $this->otPageRepository->getAllSitePages($rootUid);
  1392. // To understand how the rights levels are computed:
  1393. // @see https://ressources.opentalent.fr/display/EX/Droits+des+BE+Users
  1394. foreach ($pages as $page) {
  1395. if ($page['is_siteroot']) {
  1396. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1397. if ($isPremium) {
  1398. $adminPerms += self::PERM_NEW;
  1399. }
  1400. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT;
  1401. } else if (
  1402. $page['slug'] == '/footer' ||
  1403. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->legal' ||
  1404. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->contact' ||
  1405. $page['slug'] == '/plan-du-site'
  1406. ) {
  1407. $adminPerms = self::PERM_SHOW;
  1408. if ($isPremium) {
  1409. $adminPerms += self::PERM_NEW;
  1410. }
  1411. $editorsPerms = self::PERM_SHOW;
  1412. } else if (
  1413. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->members' ||
  1414. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->membersCa' ||
  1415. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structures' ||
  1416. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->events' ||
  1417. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structuresEvents'
  1418. ) {
  1419. $adminPerms = self::PERM_SHOW;
  1420. if ($isPremium) {
  1421. $adminPerms += self::PERM_NEW + self::PERM_EDIT_PAGE;
  1422. }
  1423. $editorsPerms = self::PERM_SHOW;
  1424. } else {
  1425. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1426. if ($isPremium) {
  1427. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1428. }
  1429. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1430. if ($isPremium) {
  1431. $editorsPerms += self::PERM_NEW;
  1432. }
  1433. }
  1434. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1435. $queryBuilder
  1436. ->update('pages')
  1437. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1438. ->set('perms_userid', $adminUid)
  1439. ->set('perms_groupid', $editorsGroupUid)
  1440. ->set('perms_user', $adminPerms)
  1441. ->set('perms_group', $editorsPerms)
  1442. ->set('perms_everybody', 0)
  1443. ->execute();
  1444. }
  1445. return $rootUid;
  1446. }
  1447. /**
  1448. * CLI action for resetting the rights of admin and editors of the website
  1449. * on all of the existing pages, including deleted ones
  1450. *
  1451. * @param int $organizationId
  1452. * @param bool $createIfMissing
  1453. * @return int
  1454. * @throws NoSuchRecordException
  1455. * @throws NoSuchWebsiteException
  1456. * @throws \Throwable
  1457. */
  1458. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1459. {
  1460. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1461. try {
  1462. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1463. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1464. if (!$commitSuccess) {
  1465. throw new \RuntimeException('Something went wrong while commiting the result');
  1466. }
  1467. return $rootUid;
  1468. }
  1469. catch (\Throwable $e) {
  1470. // rollback
  1471. $this->connectionPool->getConnectionByName('Default')->rollback();
  1472. throw $e;
  1473. }
  1474. }
  1475. /**
  1476. * Retrieve the Organization object from the repository and then,
  1477. * from the Opentalent API
  1478. *
  1479. * @param $organizationId
  1480. * @return Organization
  1481. */
  1482. private function fetchOrganization($organizationId): Organization
  1483. {
  1484. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1485. try {
  1486. return $organizationRepository->findById($organizationId);
  1487. } catch (ApiRequestException $e) {
  1488. throw new \RuntimeException('Unable to fetch the organization with id: ' . $organizationId);
  1489. }
  1490. }
  1491. /**
  1492. * Retrieves the current full domain of the given organization.
  1493. *
  1494. * @param int $organizationId
  1495. * @return string
  1496. */
  1497. private function getOrganizationDomain(int $organizationId): string
  1498. {
  1499. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1500. $queryBuilder->getRestrictions()->removeAll();
  1501. $customDomain = $queryBuilder
  1502. ->select('domain')
  1503. ->from('tx_opentalent_custom_domains')
  1504. ->where($queryBuilder->expr()->eq('organization_id', $organizationId))
  1505. ->execute()
  1506. ->fetchColumn(0);
  1507. if ($customDomain) {
  1508. return $customDomain;
  1509. }
  1510. $organization = $this->fetchOrganization($organizationId);
  1511. return $organization->getSubDomain() . '.opentalent.fr';
  1512. }
  1513. /**
  1514. * Try to find the root page uid of the organization's website and return it.
  1515. * Throw a Opentalent\OtAdmin\NoSuchWebsiteException exception if the website does not exist.
  1516. *
  1517. * @param $organizationId
  1518. * @return int
  1519. * @throws NoSuchWebsiteException
  1520. */
  1521. private function findRootUidFor($organizationId): int
  1522. {
  1523. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1524. $queryBuilder->getRestrictions()->removeAll();
  1525. $rows = $queryBuilder
  1526. ->select('uid')
  1527. ->from('pages')
  1528. ->where('is_siteroot=1')
  1529. ->andWhere($queryBuilder->expr()->eq('tx_opentalent_structure_id', $organizationId))
  1530. ->execute()
  1531. ->fetchAll();
  1532. if (count($rows) > 1) {
  1533. throw new \RuntimeException("More than one website match this organization id");
  1534. }
  1535. $rootUid = (int)$rows[0]['uid'];
  1536. if ($rootUid > 0) {
  1537. return $rootUid;
  1538. }
  1539. throw new NoSuchWebsiteException("No website found for organization " . $organizationId);
  1540. }
  1541. /**
  1542. * Try to find the id of the organization owning this website.
  1543. *
  1544. * @param $rootUid
  1545. * @return int
  1546. * @throws NoSuchWebsiteException
  1547. */
  1548. private function findOrganizationIdUidFor($rootUid): int
  1549. {
  1550. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1551. $queryBuilder->getRestrictions()->removeAll();
  1552. $organizationId = $queryBuilder
  1553. ->select('tx_opentalent_structure_id')
  1554. ->from('pages')
  1555. ->where('is_siteroot=1')
  1556. ->andWhere($queryBuilder->expr()->eq('uid', $rootUid))
  1557. ->execute()
  1558. ->fetchColumn(0);
  1559. if ($organizationId > 0) {
  1560. return $organizationId;
  1561. }
  1562. throw new NoSuchWebsiteException("No organization found for website " . $rootUid);
  1563. }
  1564. /**
  1565. * Determine which folder-type Typo3 page should contain the new website
  1566. * CREATES IT if needed, and return its uid
  1567. *
  1568. * @return int
  1569. */
  1570. private function getParentFolderUid(): int
  1571. {
  1572. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1573. $siteCount = $queryBuilder
  1574. ->count('uid')
  1575. ->from('pages')
  1576. ->where('is_siteroot=1')
  1577. ->execute()
  1578. ->fetchColumn(0);
  1579. $thousand = (int)(($siteCount + 1) / 1000);
  1580. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1581. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1582. $uid = $queryBuilder
  1583. ->select('uid')
  1584. ->from('pages')
  1585. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1586. ->andWhere('dokType=254')
  1587. ->execute()
  1588. ->fetchColumn(0);
  1589. if ($uid == null) {
  1590. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1591. $queryBuilder->insert('pages')
  1592. ->values([
  1593. 'pid' => 0,
  1594. 'title' => $folderName,
  1595. 'dokType' => 254,
  1596. 'sorting' => 11264,
  1597. 'perms_userid' => 1,
  1598. 'perms_groupid' => 31,
  1599. 'perms_group' => 27,
  1600. ])
  1601. ->execute();
  1602. $uid = $queryBuilder->getConnection()->lastInsertId();
  1603. }
  1604. return $uid;
  1605. }
  1606. /**
  1607. * Insert a new row in the 'pages' table of the Typo3 DB
  1608. * and return its uid
  1609. *
  1610. * @param Organization $organization
  1611. * @param int $pid
  1612. * @param string $title
  1613. * @param string $slug
  1614. * @param string $template
  1615. * @param array $moreValues
  1616. * @return int
  1617. */
  1618. private function insertPage(Organization $organization,
  1619. int $pid,
  1620. string $title,
  1621. string $slug,
  1622. string $template = '',
  1623. array $moreValues = []
  1624. ): int
  1625. {
  1626. $defaultValues = [
  1627. 'pid' => $pid,
  1628. 'perms_groupid' => 3,
  1629. 'perms_user' => 27,
  1630. 'cruser_id' => 1,
  1631. 'dokType' => self::DOK_PAGE,
  1632. 'title' => $title,
  1633. 'slug' => $slug,
  1634. 'backend_layout' => 'flux__grid',
  1635. 'backend_layout_next_level' => 'flux__grid',
  1636. 'tx_opentalent_structure_id' => $organization->getId(),
  1637. 'tx_opentalent_structure_domain' => $this->getOrganizationDomain($organization->getId()),
  1638. ];
  1639. if ($template) {
  1640. $defaultValues['tx_fed_page_controller_action'] = $template;
  1641. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1642. }
  1643. $values = array_merge($defaultValues, $moreValues);
  1644. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1645. $queryBuilder->insert('pages')
  1646. ->values($values)
  1647. ->execute();
  1648. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1649. $this->createdPagesIndex[$slug] = $uid;
  1650. return $uid;
  1651. }
  1652. /**
  1653. * Insert the root page of a new organization's website
  1654. * and return its uid
  1655. *
  1656. * @param Organization $organization
  1657. * @return int
  1658. */
  1659. private function insertRootPage(Organization $organization): int
  1660. {
  1661. return $this->insertPage(
  1662. $organization,
  1663. $this->getParentFolderUid(),
  1664. $organization->getName(),
  1665. '/',
  1666. self::TEMPLATE_HOME,
  1667. [
  1668. 'is_siteroot' => 1,
  1669. 'TSconfig' => $this->getRootPageTsConfig($organization),
  1670. 'tx_opentalent_template' => self::DEFAULT_THEME,
  1671. 'tx_opentalent_template_preferences' => '{"themeColor":"' . self::DEFAULT_COLOR . '","displayCarousel":"1"}'
  1672. ]
  1673. );
  1674. }
  1675. /**
  1676. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1677. *
  1678. * @param int $pid
  1679. * @param string $cType
  1680. * @param string $bodyText
  1681. * @param int $colPos
  1682. * @param array $moreValues
  1683. */
  1684. private function insertContent(int $pid,
  1685. string $cType=self::CTYPE_TEXT,
  1686. string $bodyText = '',
  1687. int $colPos=0,
  1688. array $moreValues = []) {
  1689. $defaultValues = [
  1690. 'pid' => $pid,
  1691. 'cruser_id' => 1,
  1692. 'CType' => $cType,
  1693. 'colPos' => $colPos,
  1694. 'bodyText' => $bodyText
  1695. ];
  1696. $values = array_merge($defaultValues, $moreValues);
  1697. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1698. $queryBuilder->insert('tt_content')
  1699. ->values($values)
  1700. ->execute();
  1701. }
  1702. private function fetchOrganizationExtraData(int $organizationId) {
  1703. $cnn = new PDO(
  1704. "mysql:host=prod-back;dbname=opentalent",
  1705. 'dbcloner',
  1706. 'wWZ4hYcrmHLW2mUK',
  1707. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1708. );
  1709. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1710. $stmt = $cnn->prepare(
  1711. "SELECT o.id, o.name, o.facebook, o.twitter,
  1712. o.category, o.logo_id, p.logoDonorsMove
  1713. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1714. ON o.parameters_id = p.id
  1715. WHERE o.id=" . $organizationId . ";"
  1716. );
  1717. $stmt->execute();
  1718. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1719. $data = $stmt->fetch();
  1720. $stmt = $cnn->prepare(
  1721. "SELECT c.email
  1722. FROM opentalent.ContactPoint c
  1723. INNER JOIN opentalent.organization_contactpoint o
  1724. ON o.contactPoint_id = c.id
  1725. WHERE c.contactType = 'PRINCIPAL'
  1726. AND o.organization_id = " . $organizationId . ";"
  1727. );
  1728. $stmt->execute();
  1729. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1730. $data['email'] = $stmt->fetch()['email'];
  1731. $stmt = $cnn->prepare(
  1732. "SELECT n.name, n.logo, n.url
  1733. FROM opentalent.Network n
  1734. INNER JOIN
  1735. (opentalent.NetworkOrganization l
  1736. INNER JOIN opentalent.Organization o
  1737. ON l.organization_id = o.id)
  1738. ON l.network_id = n.id
  1739. WHERE l.endDate is NULL
  1740. AND o.id=" . $organizationId . ";"
  1741. );
  1742. $stmt->execute();
  1743. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1744. $data['network'] = $stmt->fetch();
  1745. $stmt = $cnn->prepare(
  1746. "SELECT p.username, p.id as person_id, s.product
  1747. FROM opentalent.Person p
  1748. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1749. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1750. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1751. );
  1752. $stmt->execute();
  1753. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1754. $data['admin'] = $stmt->fetch();
  1755. return $data;
  1756. }
  1757. /**
  1758. * Return the content of `sys_template`.`constants` of
  1759. * the website of the given organization
  1760. *
  1761. * @param int $organizationId
  1762. * @param array $organizationExtraData
  1763. * @return string
  1764. */
  1765. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1766. {
  1767. return "plugin.tx_ottemplating {\n" .
  1768. " settings {\n" .
  1769. " organization {\n" .
  1770. " id = " . $organizationId . "\n" .
  1771. " name = " . $organizationExtraData['name'] . "\n" .
  1772. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1773. " email = " . $organizationExtraData['email'] . "\n" .
  1774. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1775. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1776. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1777. " }\n" .
  1778. " network {\n" .
  1779. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1780. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1781. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1782. " }\n" .
  1783. " }\n" .
  1784. "}";
  1785. }
  1786. /**
  1787. * Return the TSConfig for the root page of the given organization
  1788. *
  1789. * @param Organization $organization
  1790. * @return string
  1791. */
  1792. private function getRootPageTsConfig(Organization $organization): string {
  1793. return "TCAdefaults.pages.tx_opentalent_structure_id=" . $organization->getId() . "\r\n" .
  1794. "TCAdefaults.pages.tx_opentalent_structure_domain=" . $this->getOrganizationDomain($organization->getId());
  1795. }
  1796. /**
  1797. * Create the given directory, give its property to the www-data group and
  1798. * record it as a newly created dir (for an eventual rollback)
  1799. *
  1800. * @param string $dirPath
  1801. */
  1802. private function mkDir(string $dirPath) {
  1803. mkdir($dirPath);
  1804. $this->createdDirs[] = $dirPath;
  1805. chgrp($dirPath, 'www-data');
  1806. }
  1807. /**
  1808. * Write the given file with content, give its property to the www-data group and
  1809. * record it as a newly created file (for an eventual rollback)
  1810. *
  1811. * @param string $path
  1812. * @param string $content
  1813. */
  1814. private function writeFile(string $path, string $content) {
  1815. $f = fopen($path, "w");
  1816. try
  1817. {
  1818. fwrite($f, $content);
  1819. $this->createdFiles[] = $path;
  1820. chgrp($path, 'www-data');
  1821. } finally {
  1822. fclose($f);
  1823. }
  1824. }
  1825. /**
  1826. * Try to find the config file of the website in the less resource-consuming way
  1827. * and parse it.
  1828. *
  1829. * @param int $rootUid
  1830. * @return array Path of the configuration file and parsed configuration of the website
  1831. */
  1832. protected function findConfigFileAndContentFor(int $rootUid): array
  1833. {
  1834. $configs_directory = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1835. $candidates = array_filter(
  1836. scandir($configs_directory),
  1837. function ($x) { return $x != '.' && $x != '..'; }
  1838. );
  1839. // try to filter by directory name
  1840. foreach ($candidates as $subdir) {
  1841. if (preg_match('/\.*_' . $rootUid . '$/', $subdir)) {
  1842. $filename = $configs_directory . $subdir . '/config.yaml';
  1843. try {
  1844. $yamlConfig = Yaml::parseFile($filename);
  1845. if ($yamlConfig['rootPageId'] === $rootUid) {
  1846. return [$filename, $yamlConfig];
  1847. }
  1848. } catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
  1849. continue;
  1850. }
  1851. }
  1852. }
  1853. // it wasn't found the easy way, let's look to each file... :(
  1854. foreach ($candidates as $subdir) {
  1855. $filename = $configs_directory . $subdir . '/config.yaml';
  1856. try {
  1857. $yamlConfig = Yaml::parseFile($filename);
  1858. if ($yamlConfig['rootPageId'] === $rootUid) {
  1859. return [$filename, $yamlConfig];
  1860. }
  1861. } catch (\Symfony\Component\Yaml\Exception\ParseException $e) {
  1862. continue;
  1863. }
  1864. }
  1865. return [null, []];
  1866. }
  1867. /**
  1868. * Similar to findConfigFileAndContentFor(), but only returns the parsed configuration
  1869. * @param int $rootUid
  1870. * @return array Configuration of the website
  1871. */
  1872. protected function findConfigFor(int $rootUid): array
  1873. {
  1874. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1875. return $pathAndConfig[1];
  1876. }
  1877. /**
  1878. * Similar to findConfigFileAndContentFor(), but only returns the config file path
  1879. * @param int $rootUid
  1880. * @return string Path of the config file of the given website
  1881. */
  1882. protected function findConfigFilePathFor(int $rootUid): string
  1883. {
  1884. $pathAndConfig = $this->findConfigFileAndContentFor($rootUid);
  1885. return $pathAndConfig[0];
  1886. }
  1887. /**
  1888. * Create or update the .../sites/.../config.yaml file of the given site
  1889. *
  1890. * @param int $organizationId
  1891. * @param int $rootUid
  1892. * @param string $domain
  1893. * @param bool $forceRecreate
  1894. */
  1895. private function writeConfigFile(int $organizationId, int $rootUid, string $domain, bool $forceRecreate = false): void
  1896. {
  1897. $existing = $this->findConfigFileAndContentFor($rootUid);
  1898. $configFilename = $existing[0];
  1899. $config = $existing[1];
  1900. $subdomain = explode('.', $domain)[0];
  1901. if (!$configFilename) {
  1902. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $subdomain . '_' . $organizationId;
  1903. $configFilename = $configDir . "/config.yaml";
  1904. $isNew = true;
  1905. if (file_exists($configFilename)) {
  1906. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1907. }
  1908. } else {
  1909. $configDir = dirname($configFilename);
  1910. $config['base'] = 'https://' . $domain;
  1911. $isNew = false;
  1912. }
  1913. if ($isNew || $forceRecreate) {
  1914. $config = ['base' => 'https://' . $domain,
  1915. 'baseVariants' => [
  1916. ['base' => $subdomain . '/',
  1917. 'condition' => 'applicationContext == "Development"']
  1918. ],
  1919. 'errorHandling' => [
  1920. ['errorCode' => '404',
  1921. 'errorHandler' => 'PHP',
  1922. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1923. ['errorCode' => '403',
  1924. 'errorHandler' => 'PHP',
  1925. 'errorPhpClassFQCN' => 'Opentalent\OtTemplating\Page\ErrorHandler'],
  1926. ],
  1927. 'flux_content_types' => '',
  1928. 'flux_page_templates' => '',
  1929. 'languages' => [[
  1930. 'title' => 'Fr',
  1931. 'enabled' => True,
  1932. 'base' => '/',
  1933. 'typo3Language' => 'fr',
  1934. 'locale' => 'fr_FR',
  1935. 'iso-639-1' => 'fr',
  1936. 'navigationTitle' => 'Fr',
  1937. 'hreflang' => 'fr-FR',
  1938. 'direction' => 'ltr',
  1939. 'flag' => 'fr',
  1940. 'languageId' => '0',
  1941. ]],
  1942. 'rootPageId' => $rootUid,
  1943. 'routes' => []
  1944. ];
  1945. }
  1946. $yamlConfig = Yaml::dump($config, 99, 2);
  1947. if (!file_exists($configDir)) {
  1948. $this->mkDir($configDir);
  1949. }
  1950. $this->writeFile($configFilename, $yamlConfig);
  1951. // Set the owner and mods, in case www-data is not the one who run this command
  1952. // @see https://www.php.net/manual/fr/function.stat.php
  1953. try {
  1954. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1955. chown($configFilename, $stats['4']);
  1956. chgrp($configFilename, $stats['5']);
  1957. chmod($configFilename, $stats['2']);
  1958. } catch (\Exception $e) {
  1959. }
  1960. // Flush cache:
  1961. try {
  1962. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1963. $cacheSystem->remove('site-configuration');
  1964. $cacheSystem->remove('pseudo-sites');
  1965. } catch (NoSuchCacheException $e) {
  1966. }
  1967. }
  1968. /**
  1969. * Create the BE user for the website, then return its uid
  1970. * The user shall be already created in the Opentalent DB
  1971. *
  1972. * @param int $organizationId
  1973. * @param int $rootUid
  1974. * @param int $siteGroupUid
  1975. * @param array $userData
  1976. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  1977. * @return int The uid of the created be_user
  1978. */
  1979. private function createOrUpdateBeUser(int $organizationId,
  1980. int $rootUid,
  1981. int $siteGroupUid,
  1982. array $userData,
  1983. int $updateUid = null): int
  1984. {
  1985. if (!isset($userData['username'])) {
  1986. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1987. }
  1988. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1989. $randomStr = (new Random)->generateRandomHexString(20);
  1990. $adminGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  1991. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  1992. $values = [
  1993. 'username' => $userData['username'],
  1994. 'password' => $randomStr,
  1995. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  1996. 'deleted' => 0,
  1997. 'lang' => 'fr',
  1998. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  1999. 'userMods' => null, // inherited from the base AdminGroup
  2000. 'db_mountpoints' => null, // inherited from the editors group
  2001. 'file_mountpoints' => null, // inherited from the editors group
  2002. 'options' => 3, // allow to inherit both db and file mountpoints from groups
  2003. 'tx_opentalent_opentalentId' => $userData['id'],
  2004. 'tx_opentalent_organizationId' => $organizationId,
  2005. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  2006. ];
  2007. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2008. if ($updateUid != null) {
  2009. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  2010. foreach ($values as $k => $v) {
  2011. $q->set($k, $v);
  2012. }
  2013. $q->execute();
  2014. return $updateUid;
  2015. } else {
  2016. $queryBuilder->insert('be_users')
  2017. ->values($values)
  2018. ->execute();
  2019. return (int)$queryBuilder->getConnection()->lastInsertId();
  2020. }
  2021. }
  2022. /**
  2023. * Create the BE editors group for the website, then return its uid
  2024. *
  2025. * @param int $organizationId
  2026. * @param int $rootUid
  2027. * @param array $userData
  2028. * @param int|null $updateUid If passed, this method will update this be group instead of creating a new one
  2029. * @return int The uid of the created be_group
  2030. */
  2031. private function createOrUpdateBeGroup(int $organizationId,
  2032. int $rootUid,
  2033. array $userData,
  2034. int $updateUid = null): int
  2035. {
  2036. $groupName = 'editors_' . $organizationId;
  2037. // get the existing filemounts
  2038. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  2039. $queryBuilder
  2040. ->select('uid')
  2041. ->from('sys_filemounts')
  2042. ->where("path LIKE '%user_upload/" . $organizationId . "/'")
  2043. ->orWhere("path LIKE '%form_definitions/" . $organizationId . "/'");
  2044. $statement = $queryBuilder->execute();
  2045. $rows = $statement->fetchAll(3) ?: [];
  2046. $files = [];
  2047. foreach ($rows as $row) {
  2048. $files[] = $row[0];
  2049. }
  2050. $mainGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  2051. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  2052. $values = [
  2053. 'title' => $groupName,
  2054. 'deleted' => 0,
  2055. 'subgroup' => $mainGroupUid,
  2056. 'db_mountpoints' => $rootUid,
  2057. 'file_mountPoints' => join(',', $files),
  2058. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  2059. 'groupMods' => '', // inherited from the base EditorsGroup
  2060. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  2061. 'tables_select' => '', // inherited from the base EditorsGroup
  2062. 'tables_modify' => '', // inherited from the base EditorsGroup
  2063. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  2064. ];
  2065. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2066. if ($updateUid !== null) {
  2067. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  2068. foreach ($values as $k => $v) {
  2069. $q->set($k, $v);
  2070. }
  2071. $q->execute();
  2072. return $updateUid;
  2073. } else {
  2074. $queryBuilder->insert('be_groups')
  2075. ->values($values)
  2076. ->execute();
  2077. return $queryBuilder->getConnection()->lastInsertId();
  2078. }
  2079. }
  2080. /**
  2081. * Try to find and return the uid of the editors be_group
  2082. * for this website
  2083. *
  2084. * @param int $rootUid
  2085. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2086. * @return int
  2087. * @throws NoSuchRecordException
  2088. */
  2089. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  2090. $editorsGroups = [
  2091. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  2092. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  2093. ];
  2094. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2095. if (!$withRestrictions) {
  2096. $queryBuilder->getRestrictions()->removeAll();
  2097. }
  2098. $editorsGroupUid = $queryBuilder
  2099. ->select('uid')
  2100. ->from('be_groups')
  2101. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2102. ->andWhere('(FIND_IN_SET(' . $editorsGroups[0] . ', subgroup) > 0 OR FIND_IN_SET(' . $editorsGroups[1] . ', subgroup) > 0)')
  2103. ->execute()
  2104. ->fetchColumn(0);
  2105. if ($editorsGroupUid == null) {
  2106. throw new NoSuchRecordException("No editors be_group found " .
  2107. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  2108. }
  2109. return $editorsGroupUid;
  2110. }
  2111. /**
  2112. * Try to find and return the uid of the admin be_user
  2113. * for this website
  2114. *
  2115. * @param int $rootUid
  2116. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2117. * @return int
  2118. * @throws NoSuchRecordException
  2119. * @throws NoSuchWebsiteException
  2120. */
  2121. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2122. $adminGroups = [
  2123. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2124. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2125. ];
  2126. $adminUid = null;
  2127. try {
  2128. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2129. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2130. if (!$withRestrictions) {
  2131. $queryBuilder->getRestrictions()->removeAll();
  2132. }
  2133. $adminUid = $queryBuilder
  2134. ->select('uid')
  2135. ->from('be_users')
  2136. ->where('FIND_IN_SET(' . $editorsGroupUid . ', usergroup) > 0')
  2137. ->andWhere('(FIND_IN_SET(' . $adminGroups[0] . ', usergroup) > 0 OR FIND_IN_SET(' . $adminGroups[1] . ', usergroup) > 0)')
  2138. ->execute()
  2139. ->fetchColumn(0);
  2140. return $adminUid;
  2141. } catch (NoSuchRecordException $e) {
  2142. // the editors group does not exist
  2143. }
  2144. // [For retrocompatibility] Try to find if there is a be_user still in the v8.7 data format
  2145. if ($adminUid == null) {
  2146. $organizationId = $this->findOrganizationIdUidFor($rootUid);
  2147. $extraData = $this->fetchOrganizationExtraData($organizationId);
  2148. $expectedUsername = $extraData['admin']['username'];
  2149. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2150. if (!$withRestrictions) {
  2151. $queryBuilder->getRestrictions()->removeAll();
  2152. }
  2153. $row = $queryBuilder
  2154. ->select('uid', 'db_mountpoints')
  2155. ->from('be_users')
  2156. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2157. ->execute()
  2158. ->fetch();
  2159. if ($row['uid']) {
  2160. if ((string)$rootUid != (string)$row['db_mountpoints']) {
  2161. throw new \RuntimeException(
  2162. "The be_user named '" . $expectedUsername .
  2163. "' has unexpected mounted website(s) (expected: " . $rootUid .
  2164. ", found: " . (string)$row['db_mountpoints'] . "). Abort."
  2165. );
  2166. }
  2167. $adminUid = $row['uid'];
  2168. }
  2169. }
  2170. if ($adminUid == null) {
  2171. throw new NoSuchRecordException("No admin be_user found " .
  2172. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2173. }
  2174. return $adminUid;
  2175. }
  2176. /**
  2177. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2178. *
  2179. * @param int $groupType
  2180. * @return int
  2181. */
  2182. protected function getBaseBeGroupUid(int $groupType): int
  2183. {
  2184. $expectedName = self::BEGROUP_NAME[$groupType];
  2185. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2186. $uid = $queryBuilder
  2187. ->select('uid')
  2188. ->from('be_groups')
  2189. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2190. ->execute()
  2191. ->fetchColumn(0);
  2192. if (!$uid) {
  2193. throw new \RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2194. }
  2195. return $uid;
  2196. }
  2197. /**
  2198. * Enable frontend editing for user
  2199. *
  2200. * @param int $adminUid
  2201. */
  2202. private function enableFeEditing(int $adminUid) {
  2203. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  2204. $user = $BE_USER->getRawUserByUid($adminUid);
  2205. $BE_USER->user = $user;
  2206. $BE_USER->backendSetUC();
  2207. $BE_USER->uc['frontend_editing'] = 1;
  2208. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2209. $BE_USER->writeUC($BE_USER->uc);
  2210. }
  2211. }