SiteController.php 94 KB

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