SiteController.php 97 KB

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