SiteController.php 101 KB

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