SiteController.php 94 KB

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