SiteController.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  1. <?php
  2. namespace Opentalent\OtAdmin\Controller;
  3. use Doctrine\DBAL\Driver\Exception;
  4. use Opentalent\OtAdmin\Domain\Entity\SiteInfos;
  5. use Opentalent\OtAdmin\Domain\Entity\SiteStatus;
  6. use Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException;
  7. use Opentalent\OtCore\Exception\NoSuchOrganizationException;
  8. use Opentalent\OtCore\Exception\NoSuchRecordException;
  9. use Opentalent\OtCore\Exception\NoSuchWebsiteException;
  10. use Opentalent\OtCore\Cache\OtCacheManager;
  11. use Opentalent\OtCore\Controller\ActionController;
  12. use Opentalent\OtCore\Domain\Model\Organization;
  13. use Opentalent\OtCore\Domain\Repository\OrganizationRepository;
  14. use Opentalent\OtCore\Exception\ApiRequestException;
  15. use Opentalent\OtCore\Service\OpentalentEnvService;
  16. use Opentalent\OtCore\Utility\FileUtility;
  17. use PDO;
  18. use RuntimeException;
  19. use Symfony\Component\Yaml\Yaml;
  20. use TYPO3\CMS\Core\Cache\CacheManager;
  21. use TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException;
  22. use TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException;
  23. use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
  24. use TYPO3\CMS\Core\Database\ConnectionPool;
  25. use TYPO3\CMS\Core\Utility\GeneralUtility;
  26. use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
  27. /**
  28. * The SiteController implements some admin-only operations
  29. * on Typo3 websites, like creation or update.
  30. */
  31. class SiteController extends ActionController
  32. {
  33. // Templates names
  34. private const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  35. private const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  36. private const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  37. private const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  38. private const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  39. private const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  40. private const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  41. private const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  42. private const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  43. private const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  44. private const TEMPLATE_LEGAL = "OpenTalent.OtTemplating->legal";
  45. // Pages dokType values
  46. private const DOK_PAGE = 1;
  47. private const DOK_SHORTCUT = 4;
  48. private const DOK_FOLDER = 116;
  49. // Contents CTypes
  50. private const CTYPE_TEXT = 'text';
  51. private const CTYPE_IMAGE = 'image';
  52. private const CTYPE_TEXTPIC = 'textpic';
  53. private const CTYPE_TEXTMEDIA = 'textmedia';
  54. private const CTYPE_HTML = 'html';
  55. private const CTYPE_HEADER = 'header';
  56. private const CTYPE_UPLOADS = 'uploads';
  57. private const CTYPE_LIST = 'list';
  58. private const CTYPE_SITEMAP = 'menu_sitemap';
  59. // Default values
  60. private const DEFAULT_THEME = 'Classic';
  61. private const DEFAULT_COLOR = 'light-blue';
  62. // BE rights
  63. private const BEGROUP_EDITOR_STANDARD = 10;
  64. private const BEGROUP_EDITOR_PREMIUM = 20;
  65. private const BEGROUP_ADMIN_STANDARD = 30;
  66. private const BEGROUP_ADMIN_PREMIUM = 40;
  67. private const BEGROUP_NAME = [
  68. self::BEGROUP_EDITOR_STANDARD => "Editor_Standard",
  69. self::BEGROUP_EDITOR_PREMIUM => "Editor_Premium",
  70. self::BEGROUP_ADMIN_STANDARD => "Admin_Standard",
  71. self::BEGROUP_ADMIN_PREMIUM => "Admin_Premium"
  72. ];
  73. private const IS_PRODUCT_PREMIUM = [
  74. "school-standard" => false,
  75. "artist-standard" => false,
  76. "school-premium" => true,
  77. "artist-premium" => true,
  78. "manager" => true,
  79. ];
  80. // access permissions
  81. private const PERM_SHOW = 1;
  82. private const PERM_EDIT_CONTENT = 16;
  83. private const PERM_EDIT_PAGE = 2;
  84. private const PERM_DELETE = 4;
  85. private const PERM_NEW = 8;
  86. // Domain name validation
  87. private 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}))*\/?/";
  88. // Redirections creation status
  89. private const REDIRECTION_UNKNOWN_STATUS = 0;
  90. private const REDIRECTION_UPDATED = 1;
  91. private const REDIRECTION_CREATED = 2;
  92. /**
  93. * @var ConnectionPool
  94. */
  95. private ConnectionPool $connectionPool;
  96. public function injectConnectionPool(ConnectionPool $connectionPool): void
  97. {
  98. $this->connectionPool = $connectionPool;
  99. }
  100. /**
  101. * @var CacheManager
  102. */
  103. private CacheManager $cacheManager;
  104. public function injectCacheManager(CacheManager $cacheManager): void
  105. {
  106. $this->cacheManager = $cacheManager;
  107. }
  108. /**
  109. * @var OrganizationRepository
  110. */
  111. private OrganizationRepository $organizationRepository;
  112. public function injectOrganizationRepository(OrganizationRepository $organizationRepository): void
  113. {
  114. $this->organizationRepository = $organizationRepository;
  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 NoSuchRecordException
  144. * @throws NoSuchWebsiteException
  145. * @throws InvalidWebsiteConfigurationException
  146. * @throws Exception
  147. */
  148. public function getSiteInfosAction(int $organizationId): SiteInfos
  149. {
  150. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  151. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  152. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  153. $rootPage = $this->otPageRepository->getPage($rootUid);
  154. $site = new SiteInfos(
  155. $rootUid,
  156. $website['organization_name'],
  157. $this->otWebsiteRepository->resolveWebsiteDomain($website),
  158. $website['template'],
  159. $website['template_preferences'],
  160. $website['matomo_id'],
  161. self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']] ?? false,
  162. (bool)$rootPage['deleted'],
  163. ($rootPage['hidden'] || $rootPage['fe_group'] < 0),
  164. null,
  165. null,
  166. $rootPage['perms_userid'],
  167. $rootPage['perms_groupid']
  168. );
  169. // Owners
  170. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  171. $queryBuilder->getRestrictions()->removeAll();
  172. $beUsers = $queryBuilder
  173. ->select('uid', 'username')
  174. ->from('be_users')
  175. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  176. ->execute()
  177. ->fetchAllAssociative();
  178. foreach ($beUsers as $beUser) {
  179. $site->addMountedForBeUser($beUser);
  180. }
  181. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  182. $queryBuilder->getRestrictions()->removeAll();
  183. $beGroups = $queryBuilder
  184. ->select('uid', 'title')
  185. ->from('be_groups')
  186. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  187. ->execute()
  188. ->fetchAllAssociative();
  189. foreach ($beGroups as $beGroup) {
  190. $site->addMountedForBeGroups($beGroup);
  191. }
  192. return $site;
  193. }
  194. /**
  195. * Creates a new website for the given organization, and
  196. * returns the root page uid of the newly created site
  197. *
  198. * @param int $organizationId
  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
  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. $include .= ",EXT:hcaptcha/Configuration/TypoScript";
  440. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  441. $queryBuilder->insert('sys_template')
  442. ->values([
  443. 'pid' => $rootUid,
  444. 'title' => $organization->getName(),
  445. 'sitetitle' => $organization->getName(),
  446. 'root' => 1,
  447. 'clear' => 3,
  448. 'config' => "config.frontend_editing = 1",
  449. 'include_static_file' => $include,
  450. 'constants' => $constants
  451. ])
  452. ->execute();
  453. // ## Create the site config.yaml file
  454. $identifier = $this->writeConfigFile(
  455. $rootUid,
  456. true
  457. );
  458. // Update the ot_website identifier
  459. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  460. $queryBuilder->update('ot_websites')
  461. ->set('config_identifier', $identifier)
  462. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  463. ->execute();
  464. // Create the user_upload and form_definitions directories and update the sys_filemounts table
  465. $uploadRelPath = "user_upload/" . $organizationId;
  466. $fileadminDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin";
  467. $uploadDir = rtrim($fileadminDir, '/') . "/" . ltrim($uploadRelPath, '/');
  468. if (file_exists($uploadDir)) {
  469. throw new RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  470. }
  471. $formsRelPath = '/form_definitions/' . $organizationId;
  472. $formsDir = $fileadminDir . $formsRelPath;
  473. if (file_exists($formsDir)) {
  474. throw new RuntimeException("A directory or file " . $formsDir . " already exists. Abort.");
  475. }
  476. $this->mkDir($uploadDir);
  477. $this->mkDir($formsDir);
  478. // Insert the filemounts points (sys_filemounts)
  479. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  480. $queryBuilder->insert('sys_filemounts')
  481. ->values([
  482. 'title' => 'Documents',
  483. 'path' => rtrim($uploadRelPath, '/') . '/',
  484. 'base' => 1
  485. ])
  486. ->execute();
  487. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  488. $queryBuilder->insert('sys_filemounts')
  489. ->values([
  490. 'title' => 'Forms_' . $organizationId,
  491. 'path' => rtrim($formsRelPath, '/') . '/',
  492. 'base' => 1
  493. ])
  494. ->execute();
  495. // Create the BE Editors group
  496. // -- NB: this user will then be auto-updated by the ot_connect extension --
  497. $beGroupUid = $this->createOrUpdateBeGroup(
  498. $organizationId,
  499. $rootUid,
  500. $organizationExtraData['admin']
  501. );
  502. // Create the BE User
  503. // -- NB: this user will then be auto-updated by the ot_connect extension --
  504. $beUserUid = $this->createOrUpdateBeUser(
  505. $organizationId,
  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 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. ->fetchOne() === 1;
  669. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  670. if ($hard && !$force && !file_exists($confirm_file)) {
  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->fetchAllAssociative();
  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 === '.' || $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 (is_file($configYamlFile)) {
  778. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  779. }
  780. if (is_dir($uploadDir)) {
  781. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  782. }
  783. foreach ($toRename as $initialPath => $newPath) {
  784. if (is_file($newPath)) {
  785. throw new RuntimeException(
  786. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  787. }
  788. }
  789. }
  790. // Delete or rename files and dirs
  791. if ($hard) {
  792. if (is_file($configYamlFile)) {
  793. unlink($configYamlFile);
  794. }
  795. if (is_dir(dirname($configYamlFile))) {
  796. FileUtility::rmdir(dirname($configYamlFile), $force);
  797. }
  798. if (is_dir($uploadDir)) {
  799. FileUtility::rmdir($uploadDir, $force);
  800. }
  801. if (is_dir($formsDir)) {
  802. FileUtility::rmdir($formsDir, $force);
  803. }
  804. } else {
  805. $renamed = [];
  806. foreach ($toRename as $initialPath => $newPath) {
  807. rename($initialPath, $newPath);
  808. $renamed[$initialPath] = $newPath;
  809. }
  810. }
  811. // Add the redirection
  812. if ($redirectToParent) {
  813. try {
  814. $this->addRedirection($originDomain, $targetDomain);
  815. } catch (RuntimeException $e) {} // silent the error until this https://assistance.opentalent.fr/browse/V8-3344
  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 bool $hard
  847. */
  848. private function delete(string $table, string $whereKey, $whereValue, bool $hard=false): void
  849. {
  850. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  851. if (!$hard) {
  852. $queryBuilder
  853. ->update($table)
  854. ->set('deleted', 1)
  855. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  856. ->execute();
  857. } else {
  858. $queryBuilder
  859. ->delete($table)
  860. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  861. ->execute();
  862. }
  863. }
  864. /**
  865. * Undo a soft-deletion performed using deleteSiteAction()
  866. *
  867. * @param int $organizationId
  868. * @return int
  869. * @throws NoSuchRecordException
  870. * @throws NoSuchWebsiteException
  871. * @throws \Doctrine\DBAL\ConnectionException
  872. * @throws \Doctrine\DBAL\DBALException
  873. * @throws \Throwable
  874. */
  875. public function undeleteSiteAction(int $organizationId): int
  876. {
  877. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId, false);
  878. $websiteUid = $website['uid'];
  879. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid'], false);
  880. // start transactions
  881. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  882. // keep track of renamed file for an eventual rollback
  883. $renamed = [];
  884. try {
  885. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  886. $queryBuilder
  887. ->update('ot_websites')
  888. ->set('deleted', 0)
  889. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  890. ->execute();
  891. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  892. foreach($pages as $page) {
  893. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  894. $queryBuilder
  895. ->update('tt_content')
  896. ->set('deleted', 0)
  897. ->where($queryBuilder->expr()->eq('pid', $page['uid']))
  898. ->execute();
  899. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  900. $queryBuilder
  901. ->update('pages')
  902. ->set('deleted', 0)
  903. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  904. ->execute();
  905. }
  906. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  907. $queryBuilder
  908. ->update('tt_content')
  909. ->set('deleted', 0)
  910. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  911. ->execute();
  912. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  913. $queryBuilder
  914. ->update('pages')
  915. ->set('deleted', 0)
  916. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  917. ->execute();
  918. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  919. $queryBuilder
  920. ->update('sys_template')
  921. ->set('deleted', 0)
  922. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  923. ->execute();
  924. // remove filemounts
  925. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  926. $queryBuilder
  927. ->update('sys_filemounts')
  928. ->set('deleted', 0)
  929. ->where($queryBuilder->expr()->eq('path', "'/user_upload/" . $organizationId . "/'"))
  930. ->execute();
  931. try {
  932. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid, false);
  933. if ($editorsGroupUid !== null) {
  934. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  935. $queryBuilder
  936. ->update('be_groups')
  937. ->set('deleted', 0)
  938. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  939. ->execute();
  940. }
  941. } catch (NoSuchRecordException $e) {}
  942. try {
  943. $adminBeUserUid = $this->findAdminBeUserUid($rootUid, false);
  944. if ($adminBeUserUid !== null) {
  945. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  946. $queryBuilder
  947. ->update('be_users')
  948. ->set('deleted', 0)
  949. ->where($queryBuilder->expr()->eq('uid', $adminBeUserUid))
  950. ->execute();
  951. }
  952. } catch (NoSuchRecordException $e) {}
  953. // Look up for the config.yaml file of the website
  954. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  955. $configYamlFile = "";
  956. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  957. $yamlFile = $subdir . '/config.yaml.deleted';
  958. if (is_file($yamlFile)) {
  959. $conf = Yaml::parseFile($yamlFile);
  960. if ($conf['rootPageId'] === $rootUid) {
  961. $configYamlFile = $yamlFile;
  962. break;
  963. }
  964. }
  965. }
  966. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  967. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/deleted_' . $organizationId . '/';
  968. $toRename = [];
  969. if (is_file($configYamlFile)) {
  970. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  971. }
  972. if (is_dir($uploadDir)) {
  973. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  974. }
  975. if (is_dir($formsDir)) {
  976. $toRename[$formsDir] = dirname($formsDir) . '/' . $organizationId;
  977. }
  978. foreach ($toRename as $initialPath => $newPath) {
  979. if (is_file($newPath)) {
  980. throw new RuntimeException(
  981. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  982. }
  983. }
  984. $renamed = [];
  985. foreach ($toRename as $initialPath => $newPath) {
  986. rename($initialPath, $newPath);
  987. $renamed[$initialPath] = $newPath;
  988. }
  989. // remove eventual redirection from this site to another
  990. $originUrl = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  991. $this->removeRedirectionsFrom($originUrl);
  992. // Try to commit the result
  993. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  994. if (!$commitSuccess) {
  995. throw new RuntimeException('Something went wrong while commiting the result');
  996. }
  997. return $rootUid;
  998. } catch(\Throwable $e) {
  999. // rollback
  1000. $this->connectionPool->getConnectionByName('Default')->rollback();
  1001. foreach ($renamed as $initialPath => $newPath) {
  1002. rename($newPath, $initialPath);
  1003. }
  1004. throw $e;
  1005. }
  1006. }
  1007. /**
  1008. * Clear the cache of the organization's website
  1009. *
  1010. * @param int $organizationId the organization's id whom site cache should be cleared
  1011. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  1012. * @return int
  1013. * @throws NoSuchWebsiteException
  1014. */
  1015. public function clearSiteCacheAction(int $organizationId, bool $clearAll=false): int
  1016. {
  1017. $rootUid = $this->otWebsiteRepository->findRootUidForOrganization($organizationId);
  1018. OtCacheManager::clearSiteCache($rootUid, $clearAll);
  1019. return $rootUid;
  1020. }
  1021. /**
  1022. * Perform a full scan of the website and returns a list of warnings
  1023. *
  1024. * @param int $organizationId
  1025. * @return array
  1026. * @throws NoSuchOrganizationException
  1027. * @throws NoSuchRecordException
  1028. * @throws NoSuchWebsiteException
  1029. * @throws Exception
  1030. */
  1031. private function scanSite(int $organizationId): array
  1032. {
  1033. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  1034. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  1035. $warnings = [];
  1036. // fetch and index pages and root page
  1037. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1038. $rootPage = null;
  1039. $pageIndex = [];
  1040. foreach ($pages as $page) {
  1041. $pageIndex[$page['uid']] = $page;
  1042. if ($page['is_siteroot'] === 1) { $rootPage = $page; }
  1043. }
  1044. // fetch organization and extradata
  1045. $organization = $this->fetchOrganization($organizationId);
  1046. $extraData = $this->fetchOrganizationExtraData($organizationId);
  1047. // load site's settings (uncomment if needed)
  1048. // $config = $this->otWebsiteRepository->findConfigFor($rootUid);
  1049. // Check site's title
  1050. if (trim($website['organization_name']) !== trim($organization->getName())) {
  1051. $warnings[] = "Website's organization name is different from what is registered in the Opentalent DB";
  1052. }
  1053. if (trim($rootPage['title']) !== trim($organization->getName())) {
  1054. $warnings[] = "Root page's title does not match the organization name";
  1055. }
  1056. // Who is the expected owner among the be_users? there should be only one.
  1057. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1058. $queryBuilder->getRestrictions()->removeAll();
  1059. $beUsers = $queryBuilder
  1060. ->select('uid', 'username')
  1061. ->from('be_users')
  1062. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  1063. ->execute()
  1064. ->fetchAllAssociative();
  1065. $owner = null;
  1066. if (count($beUsers) > 1) {
  1067. $warnings[] = 'Website is mounted on more than one be_user: ' .
  1068. implode(', ', array_map(static function($u) { return $u['username']; } ,$beUsers));
  1069. } elseif (count($beUsers) === 0) {
  1070. $warnings[] = 'Website is not mounted on any be_user';
  1071. } else {
  1072. $owner = $beUsers[0];
  1073. }
  1074. // are template constants up to date?
  1075. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1076. $actual_constants = $queryBuilder
  1077. ->select('constants')
  1078. ->from('sys_template')
  1079. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  1080. ->execute()
  1081. ->fetchOne();
  1082. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  1083. $norm = static function ($s) {
  1084. return strtolower(preg_replace('/\s/', '', $s));
  1085. };
  1086. if ($norm($expected_constants) !== $norm($actual_constants)) {
  1087. $warnings[] = 'Template constants need an update';
  1088. }
  1089. $expected_templates = [
  1090. "OpenTalent.OtTemplating->home" => 0,
  1091. "OpenTalent.OtTemplating->legal" => 0,
  1092. "OpenTalent.OtTemplating->contact" => 0
  1093. ];
  1094. foreach ($pages as $page) {
  1095. if ($page['deleted']) {
  1096. continue;
  1097. }
  1098. // Is it the correct owner?
  1099. if ($owner !== null && $page['perms_userid'] !== $owner['uid']) {
  1100. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  1101. }
  1102. if (!$page['is_siteroot']) {
  1103. // is the parent page state (deleted, hidden, restricted) the same as this page?
  1104. $parent = $pageIndex[$page['pid']];
  1105. if ($parent['deleted']) {
  1106. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  1107. }
  1108. if ($parent['hidden'] && !$page['hidden']) {
  1109. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  1110. }
  1111. if ($parent['fe_group'] < 0 && !($page['fe_group'] >= 0)) {
  1112. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  1113. }
  1114. }
  1115. // an expected template was found, remove it from the list of expected
  1116. if (
  1117. !$page['hidden'] &&
  1118. in_array($page['tx_fed_page_controller_action'], $expected_templates, true)
  1119. )
  1120. {
  1121. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  1122. }
  1123. }
  1124. foreach ($expected_templates as $template => $_) {
  1125. $warnings[] = 'No page with template ' . $template;
  1126. }
  1127. return $warnings;
  1128. }
  1129. /**
  1130. * Get the current status of the organization's website
  1131. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  1132. *
  1133. * The status is among:
  1134. *
  1135. * - STATUS_NO_SUCH_WEBSITE
  1136. * - STATUS_EXISTING
  1137. * - STATUS_EXISTING_DELETED
  1138. * - STATUS_EXISTING_HIDDEN
  1139. * - STATUS_EXISTING_WITH_WARNINGS
  1140. *
  1141. * @param int $organizationId the organization's id whom site cache should be cleared
  1142. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1143. * the website pages will be performed.
  1144. * @return SiteStatus
  1145. * @throws Exception
  1146. * @throws InvalidWebsiteConfigurationException
  1147. * @throws NoSuchOrganizationException
  1148. * @throws NoSuchRecordException
  1149. * @throws NoSuchWebsiteException
  1150. */
  1151. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  1152. {
  1153. try {
  1154. $siteInfos = $this->getSiteInfosAction($organizationId);
  1155. } catch (NoSuchWebsiteException $e) {
  1156. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  1157. }
  1158. if ($siteInfos->isDeleted()) {
  1159. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  1160. }
  1161. if ($siteInfos->isHiddenOrRestricted()) {
  1162. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  1163. }
  1164. $warnings = null;
  1165. if ($fullScan) {
  1166. // ** Look for potential issues
  1167. $warnings = $this->scanSite($organizationId);
  1168. }
  1169. return new SiteStatus(
  1170. $organizationId,
  1171. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  1172. $siteInfos,
  1173. $warnings
  1174. );
  1175. }
  1176. /**
  1177. * Set a new domain for the website.
  1178. * If $redirect is true, also add a redirection from the former domain to the new one
  1179. *
  1180. * @param int $organizationId
  1181. * @param string $newDomain
  1182. * @param bool $redirect
  1183. * @return int
  1184. * @throws InvalidWebsiteConfigurationException
  1185. * @throws NoSuchRecordException
  1186. * @throws NoSuchWebsiteException
  1187. */
  1188. public function setSiteCustomDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1189. {
  1190. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1191. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1192. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1193. }
  1194. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  1195. $websiteUid = $website['uid'];
  1196. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($websiteUid);
  1197. // ## Update the ot_website table
  1198. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1199. $queryBuilder->update('ot_websites')
  1200. ->set('custom_domain', $newDomain)
  1201. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  1202. ->execute();
  1203. $originDomain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  1204. if (preg_replace('/https?:\/\//', '', $originDomain) === preg_replace('/https?:\/\//', '', $newDomain) ) {
  1205. throw new RuntimeException('The new domain should be different of the current one');
  1206. }
  1207. $this->writeConfigFile($organizationId, $rootUid, $newDomain);
  1208. if ($redirect) {
  1209. // Add the redirection
  1210. try {
  1211. $this->addRedirection($originDomain, $newDomain);
  1212. } catch (\RuntimeException $e) {} // silent the error until this https://assistance.opentalent.fr/browse/V8-3344
  1213. }
  1214. OtCacheManager::clearSiteCache($rootUid, true);
  1215. return $rootUid;
  1216. }
  1217. /**
  1218. * Return all the redirections from the given domain name,
  1219. * even if they have been marked as deleted.
  1220. *
  1221. * @param $domain string Domain name, without the http(s):// part
  1222. * @return array Rows from the sys_redirect table
  1223. * @throws Exception
  1224. */
  1225. protected function getRedirectionsFrom(string $domain): array
  1226. {
  1227. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1228. $queryBuilder->getRestrictions()->removeAll();
  1229. return $queryBuilder
  1230. ->select('*')
  1231. ->from('sys_redirect')
  1232. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1233. ->execute()
  1234. ->fetchAllAssociative();
  1235. }
  1236. /**
  1237. * Return all the redirections to the given domain name,
  1238. * even if they have been marked as deleted.
  1239. *
  1240. * @param $domain string Domain name, without the http(s):// part
  1241. * @return array Rows from the sys_redirect table
  1242. */
  1243. protected function getRedirectionsTo(string $domain): array
  1244. {
  1245. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1246. $queryBuilder->getRestrictions()->removeAll();
  1247. /** @noinspection HttpUrlsUsage */
  1248. return $queryBuilder
  1249. ->select('*')
  1250. ->from('sys_redirect')
  1251. ->where(
  1252. $queryBuilder->expr()->in(
  1253. 'target',
  1254. [
  1255. 'http://' . $queryBuilder->expr()->literal($domain),
  1256. 'https://' . $queryBuilder->expr()->literal($domain)
  1257. ]
  1258. )
  1259. )
  1260. ->execute()
  1261. ->fetchAllAssociative();
  1262. }
  1263. /**
  1264. * Add a new redirection from $fromDomain to $toDomain.
  1265. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1266. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1267. *
  1268. * @param $fromDomain
  1269. * @param $toDomain
  1270. * @return int Status of the operation
  1271. * @throws Exception
  1272. */
  1273. public function addRedirection($fromDomain, $toDomain): int
  1274. {
  1275. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1276. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1277. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1278. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1279. }
  1280. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1281. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1282. }
  1283. $existing = $this->getRedirectionsFrom($fromDomain);
  1284. $toUpdate = null;
  1285. foreach ($existing as $redirection) {
  1286. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1287. // a redirection from this domain already exists, and it is not deleted nor disabled
  1288. // check if the target is not the same domain
  1289. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1290. throw new RuntimeException(
  1291. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1292. );
  1293. }
  1294. // else, target is already the same domain, it will be updated
  1295. $toUpdate = $redirection;
  1296. break;
  1297. }
  1298. // a redirection from this domain already exists, but it is deleted or disabled
  1299. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1300. // the target is the same domain, we'll reactivate this record
  1301. $toUpdate = $redirection;
  1302. break;
  1303. }
  1304. }
  1305. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1306. $data = [
  1307. 'deleted' => 0,
  1308. 'disabled' => 0,
  1309. 'source_host' => $fromDomain,
  1310. 'source_path' => '/.*/',
  1311. 'is_regexp' => 1,
  1312. 'force_https' => 0,
  1313. 'respect_query_parameters' => 0,
  1314. 'keep_query_parameters' => 1,
  1315. 'target' => 'https://' . $toDomain,
  1316. 'target_statuscode' => 301
  1317. ];
  1318. if ($toUpdate !== null) {
  1319. $q = $queryBuilder
  1320. ->update('sys_redirect')
  1321. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1322. foreach ($data as $k => $v) {
  1323. $q->set($k, $v);
  1324. }
  1325. $q->execute();
  1326. return self::REDIRECTION_UPDATED;
  1327. }
  1328. $queryBuilder
  1329. ->insert('sys_redirect')
  1330. ->values($data)
  1331. ->execute();
  1332. return self::REDIRECTION_CREATED;
  1333. }
  1334. /**
  1335. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1336. * If $hard is true, delete it completely.
  1337. *
  1338. * @param $fromDomain
  1339. * @param bool $hard
  1340. * @return int Number of affected rows
  1341. * @throws Exception
  1342. */
  1343. public function removeRedirectionsFrom($fromDomain, bool $hard=false): int
  1344. {
  1345. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1346. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1347. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1348. }
  1349. $existing = $this->getRedirectionsFrom($fromDomain);
  1350. $deleted = 0;
  1351. foreach ($existing as $redirection) {
  1352. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1353. ++$deleted;
  1354. }
  1355. return $deleted;
  1356. }
  1357. /**
  1358. * Set the rights of admin and editors of the website
  1359. * on all the existing pages, including deleted ones
  1360. *
  1361. * @param int $organizationId
  1362. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1363. * @param int|null $editorsGroupUid Force the editors be-group uid
  1364. * @param int|null $adminUid Force the admin be-user uid
  1365. * @return int The uid of the website root page
  1366. * @throws NoSuchWebsiteException
  1367. * @throws NoSuchRecordException
  1368. */
  1369. protected function setBeUserPerms(
  1370. int $organizationId,
  1371. bool $createIfMissing = false,
  1372. int $editorsGroupUid = null,
  1373. int $adminUid = null
  1374. ): int
  1375. {
  1376. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1377. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1378. "and force the admin or group uid at the same time.");
  1379. }
  1380. $rootUid = $this->otWebsiteRepository->findRootUidForOrganization($organizationId);
  1381. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1382. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']];
  1383. if ($editorsGroupUid === null) {
  1384. try {
  1385. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1386. } catch (NoSuchRecordException $e) {
  1387. if (!$createIfMissing) {
  1388. throw $e;
  1389. }
  1390. }
  1391. }
  1392. if ($adminUid === null) {
  1393. try {
  1394. $adminUid = $this->findAdminBeUserUid($rootUid);
  1395. } catch (NoSuchRecordException $e) {
  1396. if (!$createIfMissing) {
  1397. throw $e;
  1398. }
  1399. }
  1400. }
  1401. // Creates or update the admin be_group
  1402. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1403. $organizationId,
  1404. $rootUid,
  1405. $organizationExtraData['admin'],
  1406. $editorsGroupUid
  1407. );
  1408. // Creates or update the admin be_user
  1409. $adminUid = $this->createOrUpdateBeUser(
  1410. $organizationId,
  1411. $editorsGroupUid,
  1412. $organizationExtraData['admin'],
  1413. $adminUid
  1414. );
  1415. // Reset the appartenance to groups
  1416. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1417. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1418. $queryBuilder
  1419. ->update('be_users')
  1420. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1421. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1422. ->execute();
  1423. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1424. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1425. $queryBuilder
  1426. ->update('be_groups')
  1427. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1428. ->set('subgroup', $mainEditorGroupUid)
  1429. ->execute();
  1430. // setup default owner for the website
  1431. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1432. $tsConfig = $queryBuilder->select('TSconfig')
  1433. ->from('pages')
  1434. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1435. ->execute()
  1436. ->fetchOne();
  1437. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1438. $tsConfig .= "\nTCEMAIN {\n" .
  1439. " permissions.userid = " . $adminUid ."\n" .
  1440. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1441. "}";
  1442. $queryBuilder
  1443. ->update('pages')
  1444. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1445. ->set('TSconfig', $tsConfig)
  1446. ->execute();
  1447. // fetch pages and root page
  1448. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1449. // To understand how the rights levels are computed:
  1450. // @see https://ressources.opentalent.fr/display/EX/Droits+des+BE+Users
  1451. foreach ($pages as $page) {
  1452. if ($page['is_siteroot']) {
  1453. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1454. if ($isPremium) {
  1455. $adminPerms += self::PERM_NEW;
  1456. }
  1457. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT;
  1458. } else if (
  1459. $page['slug'] === '/footer' ||
  1460. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->legal' ||
  1461. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->contact' ||
  1462. $page['slug'] === '/plan-du-site'
  1463. ) {
  1464. $adminPerms = self::PERM_SHOW;
  1465. if ($isPremium) {
  1466. $adminPerms += self::PERM_NEW;
  1467. }
  1468. $editorsPerms = self::PERM_SHOW;
  1469. } else if (
  1470. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->members' ||
  1471. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->membersCa' ||
  1472. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->structures' ||
  1473. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->events' ||
  1474. $page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->structuresEvents'
  1475. ) {
  1476. $adminPerms = self::PERM_SHOW;
  1477. if ($isPremium) {
  1478. $adminPerms += self::PERM_NEW + self::PERM_EDIT_PAGE;
  1479. }
  1480. $editorsPerms = self::PERM_SHOW;
  1481. } else {
  1482. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1483. if ($isPremium) {
  1484. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1485. }
  1486. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1487. if ($isPremium) {
  1488. $editorsPerms += self::PERM_NEW;
  1489. }
  1490. }
  1491. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1492. $queryBuilder
  1493. ->update('pages')
  1494. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1495. ->set('perms_userid', $adminUid)
  1496. ->set('perms_groupid', $editorsGroupUid)
  1497. ->set('perms_user', $adminPerms)
  1498. ->set('perms_group', $editorsPerms)
  1499. ->set('perms_everybody', 0)
  1500. ->execute();
  1501. }
  1502. return $rootUid;
  1503. }
  1504. /**
  1505. * Action for resetting the rights of admin and editors of the website
  1506. * on all the existing pages, including deleted ones
  1507. *
  1508. * @param int $organizationId
  1509. * @param bool $createIfMissing
  1510. * @return int
  1511. * @throws NoSuchRecordException
  1512. * @throws NoSuchWebsiteException
  1513. * @throws \Throwable
  1514. */
  1515. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1516. {
  1517. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1518. try {
  1519. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1520. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1521. if (!$commitSuccess) {
  1522. throw new RuntimeException('Something went wrong while commiting the result');
  1523. }
  1524. return $rootUid;
  1525. }
  1526. catch (\Throwable $e) {
  1527. // rollback
  1528. $this->connectionPool->getConnectionByName('Default')->rollback();
  1529. throw $e;
  1530. }
  1531. }
  1532. /**
  1533. * Delete then regenerate all the typo3 sites yaml config files
  1534. *
  1535. * This is a more efficient alternative to the update --all, designed to be executed on a development environment
  1536. * just after the databases cloning.
  1537. *
  1538. * @throws NoSuchRecordException
  1539. * @throws NoSuchWebsiteException
  1540. * @throws \Doctrine\DBAL\ConnectionException
  1541. * @throws \Doctrine\DBAL\DBALException
  1542. * @throws InvalidWebsiteConfigurationException
  1543. * @throws \Throwable
  1544. */
  1545. public function regenConfigFilesAction(): void
  1546. {
  1547. $configRootDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1548. $backupConfigDir = $_ENV['TYPO3_PATH_APP'] . "/config/bkp_sites";
  1549. if (file_exists($backupConfigDir)) {
  1550. throw new RuntimeException('A directory or a file with this name already exist: ' . $backupConfigDir);
  1551. }
  1552. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1553. try {
  1554. // archive the existing files, in case a rollback is needed
  1555. rename($configRootDir, $backupConfigDir);
  1556. $this->mkDir($configRootDir);
  1557. $websites = $this->otWebsiteRepository->getAll();
  1558. foreach ($websites as $website) {
  1559. $identifier = $website['subdomain'] . '_' . $website['organization_id'];
  1560. $configDir = $configRootDir . $identifier;
  1561. $configFilename = $configDir . "/config.yaml";
  1562. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  1563. $config = $siteConfig->getConfiguration();
  1564. $yamlConfig = Yaml::dump($config, 99, 2);
  1565. $this->mkDir($configDir);
  1566. $this->writeFile($configFilename, $yamlConfig);
  1567. // ## Update the ot_website identifier
  1568. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1569. $queryBuilder->update('ot_websites')
  1570. ->set('config_identifier', $identifier)
  1571. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  1572. ->execute();
  1573. }
  1574. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1575. if (!$commitSuccess) {
  1576. throw new RuntimeException('Something went wrong while committing the result');
  1577. }
  1578. $this->rrmdir($backupConfigDir);
  1579. }
  1580. catch (\Throwable $e) {
  1581. // rollback
  1582. if (!file_exists($configRootDir)) {
  1583. $this->rrmdir($configRootDir);
  1584. }
  1585. if (!file_exists($backupConfigDir)) {
  1586. rename($backupConfigDir, $configRootDir);
  1587. }
  1588. $this->connectionPool->getConnectionByName('Default')->rollback();
  1589. throw $e;
  1590. }
  1591. }
  1592. /**
  1593. * Retrieve the Organization object from the repository and then,
  1594. * from the Opentalent API
  1595. *
  1596. * @param $organizationId
  1597. * @return Organization
  1598. * @throws NoSuchOrganizationException
  1599. */
  1600. private function fetchOrganization($organizationId): object
  1601. {
  1602. try {
  1603. return $this->organizationRepository->findById($organizationId);
  1604. } catch (ApiRequestException $e) {
  1605. throw new NoSuchOrganizationException('Unable to fetch the organization with id: ' . $organizationId);
  1606. }
  1607. }
  1608. /**
  1609. * Insert a new row in the 'pages' table of the Typo3 DB
  1610. * and return its uid
  1611. *
  1612. * @param Organization $organization
  1613. * @return int
  1614. */
  1615. private function insertOtWebsite(Organization $organization): int
  1616. {
  1617. $values = [
  1618. 'organization_id' => $organization->getId(),
  1619. 'subdomain' => $organization->getSubDomain(),
  1620. 'locale' => 'fr_FR',
  1621. 'organization_name' => $organization->getName()
  1622. ];
  1623. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1624. $queryBuilder->insert('ot_websites')
  1625. ->values($values)
  1626. ->execute();
  1627. return (int)$queryBuilder->getConnection()->lastInsertId();
  1628. }
  1629. /**
  1630. * Determine which folder-type Typo3 page should contain the new website
  1631. * CREATES IT if needed, and return its uid
  1632. *
  1633. * @return int
  1634. */
  1635. private function getParentFolderUid(): int
  1636. {
  1637. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1638. $siteCount = $queryBuilder
  1639. ->count('uid')
  1640. ->from('pages')
  1641. ->where('is_siteroot=1')
  1642. ->execute()
  1643. ->fetchOne();
  1644. $thousand = (int)(($siteCount + 1) / 1000);
  1645. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1646. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1647. $uid = $queryBuilder
  1648. ->select('uid')
  1649. ->from('pages')
  1650. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1651. ->andWhere('dokType=254')
  1652. ->execute()
  1653. ->fetchOne();
  1654. if ($uid === null) {
  1655. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1656. $queryBuilder->insert('pages')
  1657. ->values([
  1658. 'pid' => 0,
  1659. 'title' => $folderName,
  1660. 'dokType' => 254,
  1661. 'sorting' => 11264,
  1662. 'perms_userid' => 1,
  1663. 'perms_groupid' => 31,
  1664. 'perms_group' => 27,
  1665. ])
  1666. ->execute();
  1667. $uid = $queryBuilder->getConnection()->lastInsertId();
  1668. }
  1669. return $uid;
  1670. }
  1671. /**
  1672. * Insert a new row in the 'pages' table of the Typo3 DB
  1673. * and return its uid
  1674. *
  1675. * @param int $website_uid
  1676. * @param int $pid
  1677. * @param string $title
  1678. * @param string $slug
  1679. * @param string $template
  1680. * @param array $moreValues
  1681. * @return int
  1682. */
  1683. private function insertPage(int $website_uid,
  1684. int $pid,
  1685. string $title,
  1686. string $slug,
  1687. string $template = '',
  1688. array $moreValues = []
  1689. ): int
  1690. {
  1691. $defaultValues = [
  1692. 'pid' => $pid,
  1693. 'perms_groupid' => 3,
  1694. 'perms_user' => 27,
  1695. 'cruser_id' => 1,
  1696. 'dokType' => self::DOK_PAGE,
  1697. 'title' => $title,
  1698. 'slug' => $slug,
  1699. 'backend_layout' => 'flux__grid',
  1700. 'backend_layout_next_level' => 'flux__grid',
  1701. 'ot_website_uid' => $website_uid,
  1702. ];
  1703. if ($template) {
  1704. $defaultValues['tx_fed_page_controller_action'] = $template;
  1705. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1706. }
  1707. $values = array_merge($defaultValues, $moreValues);
  1708. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1709. $queryBuilder->insert('pages')
  1710. ->values($values)
  1711. ->execute();
  1712. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1713. $this->createdPagesIndex[$slug] = $uid;
  1714. return $uid;
  1715. }
  1716. /**
  1717. * Insert the root page of a new organization's website
  1718. * and return its uid
  1719. *
  1720. * @param int $website_uid
  1721. * @param string $title
  1722. * @return int
  1723. */
  1724. private function insertRootPage(int $website_uid, string $title): int
  1725. {
  1726. return $this->insertPage(
  1727. $website_uid,
  1728. $this->getParentFolderUid(),
  1729. $title,
  1730. '/',
  1731. self::TEMPLATE_HOME,
  1732. [
  1733. 'is_siteroot' => 1,
  1734. 'TSconfig' => 'TCAdefaults.pages.ot_website_uid=' . $website_uid
  1735. ]
  1736. );
  1737. }
  1738. /**
  1739. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1740. *
  1741. * @param int $pid
  1742. * @param string $cType
  1743. * @param string $bodyText
  1744. * @param int $colPos
  1745. * @param array $moreValues
  1746. */
  1747. private function insertContent(int $pid,
  1748. string $cType=self::CTYPE_TEXT,
  1749. string $bodyText = '',
  1750. int $colPos=0,
  1751. array $moreValues = []): void
  1752. {
  1753. $defaultValues = [
  1754. 'pid' => $pid,
  1755. 'cruser_id' => 1,
  1756. 'CType' => $cType,
  1757. 'colPos' => $colPos,
  1758. 'bodyText' => $bodyText
  1759. ];
  1760. $values = array_merge($defaultValues, $moreValues);
  1761. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1762. $queryBuilder->insert('tt_content')
  1763. ->values($values)
  1764. ->execute();
  1765. }
  1766. private function fetchOrganizationExtraData(int $organizationId) {
  1767. $cnn = new PDO(
  1768. "mysql:host=" . OpentalentEnvService::get('DB_HOST') . ";dbname=opentalent",
  1769. OpentalentEnvService::get('DB_USER'),
  1770. OpentalentEnvService::get('DB_PASSWORD'),
  1771. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1772. );
  1773. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1774. $stmt = $cnn->query(
  1775. "SELECT o.id, o.name, o.facebook, o.twitter, o.instagram, o.youtube,
  1776. o.category, o.logo_id, p.logoDonorsMove
  1777. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1778. ON o.parameters_id = p.id
  1779. WHERE o.id=" . $organizationId . ";"
  1780. );
  1781. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1782. $data = $stmt->fetch();
  1783. $stmt = $cnn->query(
  1784. "SELECT c.email
  1785. FROM opentalent.ContactPoint c
  1786. INNER JOIN opentalent.organization_contactpoint o
  1787. ON o.contactPoint_id = c.id
  1788. WHERE c.contactType = 'PRINCIPAL'
  1789. AND o.organization_id = " . $organizationId . ";"
  1790. );
  1791. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1792. $data['email'] = $stmt->fetch()['email'];
  1793. $stmt = $cnn->query(
  1794. "SELECT n.name, n.logo, n.url
  1795. FROM opentalent.Network n
  1796. INNER JOIN
  1797. (opentalent.NetworkOrganization l
  1798. INNER JOIN opentalent.Organization o
  1799. ON l.organization_id = o.id)
  1800. ON l.network_id = n.id
  1801. WHERE l.endDate is NULL
  1802. AND o.id=" . $organizationId . ";"
  1803. );
  1804. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1805. $data['network'] = $stmt->fetch();
  1806. $stmt = $cnn->query(
  1807. "SELECT p.username, p.id as person_id, s.product, p.password
  1808. FROM opentalent.Person p
  1809. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1810. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1811. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1812. );
  1813. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1814. $data['admin'] = $stmt->fetch();
  1815. return $data;
  1816. }
  1817. /**
  1818. * Return the content of `sys_template`.`constants` of
  1819. * the website of the given organization
  1820. *
  1821. * @param int $organizationId
  1822. * @param array $organizationExtraData
  1823. * @return string
  1824. */
  1825. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1826. {
  1827. return "plugin.tx_ottemplating {\n" .
  1828. " settings {\n" .
  1829. " organization {\n" .
  1830. " id = " . $organizationId . "\n" .
  1831. " name = " . $organizationExtraData['name'] . "\n" .
  1832. " is_network = " . ($organizationExtraData['category'] === 'NETWORK' ? '1' : '0') . "\n" .
  1833. " email = " . $organizationExtraData['email'] . "\n" .
  1834. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1835. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1836. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1837. " instagram = " . $organizationExtraData['instagram'] . "\n" .
  1838. " youtube = " . $organizationExtraData['youtube'] . "\n" .
  1839. " }\n" .
  1840. " network {\n" .
  1841. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1842. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1843. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1844. " }\n" .
  1845. " }\n" .
  1846. "}";
  1847. }
  1848. /**
  1849. * Create the given directory, give its property to the www-data group and
  1850. * record it as a newly created dir (for an eventual rollback)
  1851. *
  1852. * @param string $dirPath
  1853. */
  1854. private function mkDir(string $dirPath): void
  1855. {
  1856. if (!mkdir($dirPath) && !is_dir($dirPath)) {
  1857. throw new RuntimeException(sprintf('Directory "%s" was not created', $dirPath));
  1858. }
  1859. $this->createdDirs[] = $dirPath;
  1860. chgrp($dirPath, 'www-data');
  1861. }
  1862. /**
  1863. * Write the given file with content, give its property to the www-data group and
  1864. * record it as a newly created file (for an eventual rollback)
  1865. *
  1866. * @param string $path
  1867. * @param string $content
  1868. */
  1869. private function writeFile(string $path, string $content): void
  1870. {
  1871. $f = fopen($path, 'wb');
  1872. try
  1873. {
  1874. fwrite($f, $content);
  1875. $this->createdFiles[] = $path;
  1876. try {
  1877. chgrp($path, 'www-data');
  1878. } catch (\Throwable $e) {
  1879. }
  1880. } finally {
  1881. fclose($f);
  1882. }
  1883. }
  1884. /**
  1885. * Create or update the .../sites/.../config.yaml file of the given site
  1886. * Return the identifier of the created website
  1887. *
  1888. * @param int $rootUid
  1889. * @param bool $forceRecreate
  1890. * @param null $identifier
  1891. * @return string Identifier of the newly created configuration file
  1892. * @throws InvalidWebsiteConfigurationException
  1893. * @throws NoSuchRecordException
  1894. * @throws NoSuchWebsiteException
  1895. */
  1896. private function writeConfigFile(int $rootUid, bool $forceRecreate = false, $identifier = null): string
  1897. {
  1898. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  1899. $domain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  1900. try {
  1901. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid, $identifier);
  1902. } catch (RuntimeException $e) {
  1903. // identifier might be obsolete
  1904. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid);
  1905. }
  1906. [$configFilename, $config] = $existing;
  1907. if (!$configFilename) {
  1908. $identifier = $website['subdomain'] . '_' . $website['organization_id'];
  1909. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $identifier;
  1910. $configFilename = $configDir . "/config.yaml";
  1911. $isNew = true;
  1912. if (file_exists($configFilename)) {
  1913. throw new RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1914. }
  1915. } else {
  1916. $configDir = dirname($configFilename);
  1917. if ($identifier === null) {
  1918. $identifier = basename($configDir);
  1919. }
  1920. $config['base'] = 'https://' . $domain;
  1921. $isNew = false;
  1922. }
  1923. if ($isNew || $forceRecreate) {
  1924. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  1925. $config = $siteConfig->getConfiguration();
  1926. }
  1927. $yamlConfig = Yaml::dump($config, 99, 2);
  1928. if (!file_exists($configDir)) {
  1929. $this->mkDir($configDir);
  1930. }
  1931. $this->writeFile($configFilename, $yamlConfig);
  1932. // Set the owner and mods, in case www-data is not the one who run this command
  1933. // @see https://www.php.net/manual/fr/function.stat.php
  1934. try {
  1935. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1936. chown($configFilename, $stats['4']);
  1937. chgrp($configFilename, $stats['5']);
  1938. chmod($configFilename, $stats['2']);
  1939. } catch (\Throwable $e) {
  1940. }
  1941. // Flush cache:
  1942. try {
  1943. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1944. $cacheSystem->remove('site-configuration');
  1945. $cacheSystem->remove('pseudo-sites');
  1946. } catch (NoSuchCacheException $e) {
  1947. }
  1948. return $identifier;
  1949. }
  1950. /**
  1951. * Recursively remove the target directory (! no rollback available)
  1952. */
  1953. private function rrmdir(string $dir): bool
  1954. {
  1955. if (!is_dir($dir) || is_link($dir)) {
  1956. return unlink($dir);
  1957. }
  1958. foreach (scandir($dir) as $file) {
  1959. if ($file === '.' || $file === '..') {
  1960. continue;
  1961. }
  1962. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) {
  1963. chmod($dir . DIRECTORY_SEPARATOR . $file, 0777);
  1964. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) {
  1965. return false;
  1966. }
  1967. }
  1968. }
  1969. return rmdir($dir);
  1970. }
  1971. /**
  1972. * Create the BE user for the website, then return its uid
  1973. * The user shall be already created in the Opentalent DB
  1974. *
  1975. * @param int $organizationId
  1976. * @param int $siteGroupUid
  1977. * @param array $userData
  1978. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  1979. * @return int The uid of the created be_user
  1980. * @throws InvalidPasswordHashException
  1981. */
  1982. private function createOrUpdateBeUser(int $organizationId,
  1983. int $siteGroupUid,
  1984. array $userData,
  1985. int $updateUid = null): int
  1986. {
  1987. if (!isset($userData['username'])) {
  1988. throw new RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1989. }
  1990. $hashInstance = GeneralUtility::makeInstance(PasswordHashFactory::class)->getDefaultHashInstance('BE');
  1991. $hashedPassword = $hashInstance->getHashedPassword($userData['password']);
  1992. $adminGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  1993. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  1994. $values = [
  1995. 'username' => $userData['username'],
  1996. 'password' => $hashedPassword,
  1997. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  1998. 'deleted' => 0,
  1999. 'lang' => 'fr',
  2000. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  2001. 'userMods' => null, // inherited from the base AdminGroup
  2002. 'db_mountpoints' => null, // inherited from the editors group
  2003. 'file_mountpoints' => null, // inherited from the editors group
  2004. 'options' => 3, // allow to inherit both db and file mountpoints from groups
  2005. 'tx_opentalent_opentalentId' => $userData['id'],
  2006. 'tx_opentalent_organizationId' => $organizationId,
  2007. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  2008. ];
  2009. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2010. if ($updateUid !== null) {
  2011. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));
  2012. foreach ($values as $k => $v) {
  2013. $q->set($k, $v);
  2014. }
  2015. $q->execute();
  2016. return $updateUid;
  2017. }
  2018. $queryBuilder->insert('be_users')
  2019. ->values($values)
  2020. ->execute();
  2021. return (int)$queryBuilder->getConnection()->lastInsertId();
  2022. }
  2023. /**
  2024. * Create the BE editors group for the website, then return its uid
  2025. *
  2026. * @param int $organizationId
  2027. * @param int $rootUid
  2028. * @param array $userData
  2029. * @param int|null $updateUid If passed, this method will update this be_group instead of creating a new one
  2030. * @return int The uid of the created be_group
  2031. */
  2032. private function createOrUpdateBeGroup(int $organizationId,
  2033. int $rootUid,
  2034. array $userData,
  2035. int $updateUid = null): int
  2036. {
  2037. $groupName = 'editors_' . $organizationId;
  2038. // get the existing filemounts
  2039. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  2040. $queryBuilder
  2041. ->select('uid')
  2042. ->from('sys_filemounts')
  2043. ->where("path LIKE '%user_upload/" . $organizationId . "/'")
  2044. ->orWhere("path LIKE '%form_definitions/" . $organizationId . "/'");
  2045. $statement = $queryBuilder->execute();
  2046. $rows = $statement->fetchAllAssociative() ?: [];
  2047. $files = [];
  2048. foreach ($rows as $row) {
  2049. $files[] = $row[0];
  2050. }
  2051. $mainGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  2052. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  2053. $values = [
  2054. 'title' => $groupName,
  2055. 'deleted' => 0,
  2056. 'subgroup' => $mainGroupUid,
  2057. 'db_mountpoints' => $rootUid,
  2058. 'file_mountPoints' => implode(',', $files),
  2059. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  2060. 'groupMods' => '', // inherited from the base EditorsGroup
  2061. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  2062. 'tables_select' => '', // inherited from the base EditorsGroup
  2063. 'tables_modify' => '', // inherited from the base EditorsGroup
  2064. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  2065. ];
  2066. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2067. if ($updateUid !== null) {
  2068. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));
  2069. foreach ($values as $k => $v) {
  2070. $q->set($k, $v);
  2071. }
  2072. $q->execute();
  2073. return $updateUid;
  2074. }
  2075. $queryBuilder->insert('be_groups')
  2076. ->values($values)
  2077. ->execute();
  2078. return $queryBuilder->getConnection()->lastInsertId();
  2079. }
  2080. /**
  2081. * Try to find and return the uid of the editors be_group
  2082. * for this website
  2083. *
  2084. * @param int $rootUid
  2085. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2086. * @return int
  2087. * @throws Exception
  2088. * @throws NoSuchRecordException
  2089. */
  2090. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  2091. $editorsGroups = [
  2092. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  2093. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  2094. ];
  2095. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2096. if (!$withRestrictions) {
  2097. $queryBuilder->getRestrictions()->removeAll();
  2098. }
  2099. $editorsGroupUid = $queryBuilder
  2100. ->select('uid')
  2101. ->from('be_groups')
  2102. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2103. ->andWhere('(FIND_IN_SET(' . $editorsGroups[0] . ', subgroup) > 0 OR FIND_IN_SET(' . $editorsGroups[1] . ', subgroup) > 0)')
  2104. ->execute()
  2105. ->fetchOne();
  2106. if ($editorsGroupUid === null) {
  2107. throw new NoSuchRecordException("No editors be_group found " .
  2108. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  2109. }
  2110. return $editorsGroupUid;
  2111. }
  2112. /**
  2113. * Try to find and return the uid of the admin be_user
  2114. * for this website
  2115. *
  2116. * @param int $rootUid
  2117. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2118. * @return int
  2119. * @throws NoSuchRecordException
  2120. * @throws NoSuchWebsiteException
  2121. */
  2122. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2123. $adminGroups = [
  2124. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2125. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2126. ];
  2127. $adminUid = null;
  2128. try {
  2129. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2130. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2131. if (!$withRestrictions) {
  2132. $queryBuilder->getRestrictions()->removeAll();
  2133. }
  2134. return $queryBuilder
  2135. ->select('uid')
  2136. ->from('be_users')
  2137. ->where('FIND_IN_SET(' . $editorsGroupUid . ', usergroup) > 0')
  2138. ->andWhere('(FIND_IN_SET(' . $adminGroups[0] . ', usergroup) > 0 OR FIND_IN_SET(' . $adminGroups[1] . ', usergroup) > 0)')
  2139. ->execute()
  2140. ->fetchOne();
  2141. } catch (NoSuchRecordException $e) {
  2142. // the editors group does not exist
  2143. }
  2144. // [For retro-compatibility] Try to find if there is a be_user still in the v8.7 data format
  2145. if ($adminUid === null) {
  2146. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  2147. $extraData = $this->fetchOrganizationExtraData($website['organization_id']);
  2148. $expectedUsername = $extraData['admin']['username'];
  2149. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2150. if (!$withRestrictions) {
  2151. $queryBuilder->getRestrictions()->removeAll();
  2152. }
  2153. $row = $queryBuilder
  2154. ->select('uid', 'db_mountpoints')
  2155. ->from('be_users')
  2156. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2157. ->execute()
  2158. ->fetchAssociative();
  2159. if ($row['uid']) {
  2160. if ((string)$rootUid !== (string)$row['db_mountpoints']) {
  2161. throw new RuntimeException(
  2162. "The be_user named '" . $expectedUsername .
  2163. "' has unexpected mounted website(s) (expected: " . $rootUid .
  2164. ", found: " . $row['db_mountpoints'] . "). Abort."
  2165. );
  2166. }
  2167. $adminUid = $row['uid'];
  2168. }
  2169. }
  2170. if ($adminUid === null) {
  2171. throw new NoSuchRecordException("No admin be_user found " .
  2172. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2173. }
  2174. return $adminUid;
  2175. }
  2176. /**
  2177. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2178. *
  2179. * @param int $groupType
  2180. * @return int
  2181. */
  2182. protected function getBaseBeGroupUid(int $groupType): int
  2183. {
  2184. $expectedName = self::BEGROUP_NAME[$groupType];
  2185. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2186. $uid = $queryBuilder
  2187. ->select('uid')
  2188. ->from('be_groups')
  2189. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2190. ->execute()
  2191. ->fetchOne();
  2192. if (!$uid) {
  2193. throw new RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2194. }
  2195. return $uid;
  2196. }
  2197. /**
  2198. * Enable frontend editing for user
  2199. *
  2200. * @param int $adminUid
  2201. * @noinspection PhpInternalEntityUsedInspection
  2202. */
  2203. private function enableFeEditing(int $adminUid): void
  2204. {
  2205. $BE_USER = GeneralUtility::makeInstance(BackendUserAuthentication::class);
  2206. $user = $BE_USER->getRawUserByUid($adminUid);
  2207. $BE_USER->user = $user;
  2208. $BE_USER->backendSetUC();
  2209. $BE_USER->uc['frontend_editing'] = 1;
  2210. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2211. $BE_USER->writeUC($BE_USER->uc);
  2212. }
  2213. }