SiteController.php 98 KB

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