SiteController.php 98 KB

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