SiteController.php 100 KB

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