SiteController.php 95 KB

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