SiteController.php 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  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 = 'Modern';
  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. * Update the organization's website if it exists, restore
  673. * it if it has been deleted, or create it if it does not exist.
  674. *
  675. * It also removes any redirections that may have been set on the domain.
  676. */
  677. public function justeMakeItWorkSiteAction(int $organizationId): int
  678. {
  679. try {
  680. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId, false);
  681. } catch (NoSuchWebsiteException $e) {
  682. $website = null;
  683. }
  684. if ($website) {
  685. if ($website['deleted'] === 1) {
  686. $this->undeleteSiteAction($organizationId);
  687. }
  688. $rootUid = $this->updateSiteAction($organizationId);
  689. } else {
  690. $rootUid = $this->createSiteAction($organizationId);
  691. }
  692. // Remove any existing redirection from this website production's domain
  693. $originUrl = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  694. $this->removeRedirectionsFrom($originUrl);
  695. return $rootUid;
  696. }
  697. /**
  698. * Delete the website with all its pages, contents, and related records
  699. *
  700. * If the hard parameter is false, the records' `deleted` field will be set to true and
  701. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  702. *
  703. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  704. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  705. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  706. *
  707. * If $redirectToParent is set to true, the website's url will be redirected to its parent's website
  708. *
  709. * The $force parameter, if true, will both bypass the 'DEL###' file confirmation and recursively delete the
  710. * user_upload and form_definitions of the website. <!> USE WITH CAUTION
  711. *
  712. * @param int $organizationId
  713. * @param bool $hard
  714. * @param bool $redirectToParent If set to true, the website's url will be redirected to its parent's website
  715. * @param bool $force
  716. * @return int
  717. * @throws NoSuchRecordException
  718. * @throws NoSuchWebsiteException
  719. * @throws \Doctrine\DBAL\DBALException
  720. * @throws \Throwable
  721. */
  722. public function deleteSiteAction(int $organizationId, bool $hard=false, bool $redirectToParent=true, bool $force = false): int
  723. {
  724. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  725. $websiteUid = $website['uid'];
  726. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  727. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  728. $isDeleted = $queryBuilder
  729. ->select('deleted')
  730. ->from('ot_websites')
  731. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  732. ->execute()
  733. ->fetchOne() === 1;
  734. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  735. if ($hard && !$force && !file_exists($confirm_file)) {
  736. throw new RuntimeException(
  737. "You are going to completely delete the website with root uid " . $rootUid .
  738. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  739. $confirm_file . "', and launch this command again."
  740. );
  741. }
  742. // Prepare the redirection
  743. if ($redirectToParent) {
  744. $originDomain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  745. try {
  746. $organization = $this->fetchOrganization($organizationId);
  747. $targetOrganizationId = $organization->getParentId();
  748. $targetOrganizationWebsite = $this->otWebsiteRepository->getWebsiteByOrganizationId($targetOrganizationId);
  749. $targetDomain = $this->otWebsiteRepository->resolveWebsiteDomain($targetOrganizationWebsite);
  750. } catch (NoSuchOrganizationException $e) {
  751. $targetDomain = 'opentalent.fr';
  752. }
  753. }
  754. // start transactions
  755. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  756. // keep track of renamed file for an eventual rollback
  757. $renamed = [];
  758. try {
  759. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  760. foreach($pages as $page) {
  761. $this->delete('tt_content', 'pid', $page['uid'], $hard);
  762. $this->delete('pages', 'uid', $page['uid'], $hard);
  763. }
  764. $this->delete('tt_content', 'pid', $rootUid, $hard);
  765. $this->delete('pages', 'uid', $rootUid, $hard);
  766. $this->delete('sys_template', 'pid', $rootUid, $hard);
  767. $this->delete('ot_websites', 'uid', $websiteUid, $hard);
  768. try {
  769. $adminBeUserUid = $this->findAdminBeUserUid($rootUid);
  770. if ($adminBeUserUid !== null) {
  771. $this->delete('be_users', 'uid', $adminBeUserUid, $hard);
  772. }
  773. } catch (NoSuchRecordException $e) {}
  774. try {
  775. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  776. if ($editorsGroupUid !== null) {
  777. $this->delete('be_groups', 'uid', $editorsGroupUid, $hard);
  778. }
  779. } catch (NoSuchRecordException $e) {}
  780. // Delete the filemounts
  781. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  782. $queryBuilder
  783. ->select('uid')
  784. ->from('sys_filemounts')
  785. ->where("identifier LIKE '1:%user_upload/" . $organizationId . "/%'")
  786. ->orWhere("identifier LIKE '1:%form_definitions/" . $organizationId . "/%'");
  787. $statement = $queryBuilder->executeQuery();
  788. $rows = $statement->fetchAllAssociative();
  789. foreach ($rows as $row) {
  790. $this->delete('sys_filemounts', 'uid', $row['uid'], $hard);
  791. }
  792. // Look up for the config.yaml file of the website
  793. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  794. $configYamlFile = "";
  795. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  796. if (!$isDeleted) {
  797. $yamlFile = $subdir . '/config.yaml';
  798. } else {
  799. $yamlFile = $subdir . '/config.yaml.deleted';
  800. }
  801. if (is_file($yamlFile)) {
  802. $conf = Yaml::parseFile($yamlFile);
  803. if ($conf['rootPageId'] === $rootUid) {
  804. $configYamlFile = $yamlFile;
  805. break;
  806. }
  807. }
  808. }
  809. if (!$isDeleted) {
  810. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/' . $organizationId . '/';
  811. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/' . $organizationId . '/';
  812. } else {
  813. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  814. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/deleted_' . $organizationId . '/';
  815. }
  816. // If hard deletion, verify that dirs are empty
  817. if (!$force) {
  818. foreach ([$uploadDir, $formsDir] as $dir) {
  819. if ($hard && is_dir($dir)) {
  820. foreach (scandir($dir) as $subdir) {
  821. if ($subdir === '.' || $subdir === '..') {
  822. continue;
  823. }
  824. $subdir = $dir . $subdir;
  825. if (!is_dir($subdir)) {
  826. throw new RuntimeException(
  827. 'The directory ' . $dir . ' contains directories' .
  828. ', please delete them manually. Abort.');
  829. }
  830. if (is_readable($subdir)) {
  831. foreach (scandir($subdir) as $filename) {
  832. if ($filename !== '.' && $filename !== '..') {
  833. throw new RuntimeException(
  834. 'The directory ' . $subdir . ' is not empty, ' .
  835. 'please delete it manually. Abort.');
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. // If soft deletion, check that no deleted file or directory exist
  844. if (!$hard) {
  845. $toRename = [];
  846. if (is_file($configYamlFile)) {
  847. $toRename[$configYamlFile] = $configYamlFile . '.deleted';
  848. }
  849. if (is_dir($uploadDir)) {
  850. $toRename[$uploadDir] = dirname($uploadDir) . '/deleted_' . basename($uploadDir);
  851. }
  852. foreach ($toRename as $initialPath => $newPath) {
  853. if (is_file($newPath)) {
  854. throw new RuntimeException(
  855. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  856. }
  857. }
  858. }
  859. // Delete or rename files and dirs
  860. if ($hard) {
  861. if (is_file($configYamlFile)) {
  862. unlink($configYamlFile);
  863. }
  864. if (is_dir(dirname($configYamlFile))) {
  865. FileUtility::rmdir(dirname($configYamlFile), $force);
  866. }
  867. if (is_dir($uploadDir)) {
  868. FileUtility::rmdir($uploadDir, $force);
  869. }
  870. if (is_dir($formsDir)) {
  871. FileUtility::rmdir($formsDir, $force);
  872. }
  873. } else {
  874. $renamed = [];
  875. foreach ($toRename as $initialPath => $newPath) {
  876. rename($initialPath, $newPath);
  877. $renamed[$initialPath] = $newPath;
  878. }
  879. }
  880. // Add the redirection
  881. if ($redirectToParent) {
  882. try {
  883. $this->addRedirection($originDomain, $targetDomain);
  884. } catch (RuntimeException $e) {} // silent the error until this https://assistance.opentalent.fr/browse/V8-3344
  885. }
  886. // Try to commit the result
  887. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  888. if (!$commitSuccess) {
  889. throw new RuntimeException('Something went wrong while commiting the result');
  890. }
  891. return $rootUid;
  892. } catch(\Throwable $e) {
  893. // rollback
  894. $this->connectionPool->getConnectionByName('Default')->rollback();
  895. if (!$hard) {
  896. foreach ($renamed as $initialPath => $newPath) {
  897. rename($newPath, $initialPath);
  898. }
  899. }
  900. throw $e;
  901. } finally {
  902. if (file_exists($confirm_file)) {
  903. unlink($confirm_file);
  904. }
  905. }
  906. }
  907. /**
  908. * Delete a record from the typo3 db.
  909. * If $hard is true, the record is permanently deleted.
  910. * Else, it's just marked as deleted.
  911. *
  912. * @param string $table
  913. * @param string $whereKey
  914. * @param $whereValue
  915. * @param bool $hard
  916. */
  917. private function delete(string $table, string $whereKey, $whereValue, bool $hard=false): void
  918. {
  919. $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
  920. if (!$hard) {
  921. if ($table === 'pages' || $table === 'tt_content') {
  922. // Keep track of the manually deleted pages and content, so that these won't be restored if the site
  923. // is undeleted
  924. $cnn = $this->connectionPool->getConnectionForTable($table);
  925. $cnn->executeStatement("
  926. UPDATE " . $table . " t
  927. SET t.manually_deleted = t.deleted
  928. WHERE " . $whereKey . "=?;",
  929. [$whereValue]
  930. );
  931. }
  932. $queryBuilder
  933. ->update($table)
  934. ->set('deleted', 1)
  935. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  936. ->execute();
  937. } else {
  938. $queryBuilder
  939. ->delete($table)
  940. ->where($queryBuilder->expr()->eq($whereKey, $whereValue))
  941. ->execute();
  942. }
  943. }
  944. /**
  945. * Undo a soft-deletion performed using deleteSiteAction()
  946. *
  947. * @param int $organizationId
  948. * @return int
  949. * @throws NoSuchRecordException
  950. * @throws NoSuchWebsiteException
  951. * @throws \Doctrine\DBAL\ConnectionException
  952. * @throws \Doctrine\DBAL\DBALException
  953. * @throws \Throwable
  954. */
  955. public function undeleteSiteAction(int $organizationId): int
  956. {
  957. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId, false);
  958. $websiteUid = $website['uid'];
  959. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid'], false);
  960. // start transactions
  961. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  962. // keep track of renamed file for an eventual rollback
  963. $renamed = [];
  964. try {
  965. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  966. $queryBuilder
  967. ->update('ot_websites')
  968. ->set('deleted', 0)
  969. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  970. ->execute();
  971. $pages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  972. foreach($pages as $page) {
  973. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  974. $queryBuilder
  975. ->update('tt_content')
  976. ->set('deleted', 0)
  977. ->where(
  978. $queryBuilder->expr()->andX(
  979. $queryBuilder->expr()->eq('pid', $page['uid']),
  980. $queryBuilder->expr()->eq('manually_deleted', 0)
  981. )
  982. )
  983. ->execute();
  984. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  985. $queryBuilder
  986. ->update('pages')
  987. ->set('deleted', 0)
  988. ->where(
  989. $queryBuilder->expr()->andX(
  990. $queryBuilder->expr()->eq('uid', $page['uid']),
  991. $queryBuilder->expr()->eq('manually_deleted', 0)
  992. )
  993. )
  994. ->execute();
  995. }
  996. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  997. $queryBuilder
  998. ->update('tt_content')
  999. ->set('deleted', 0)
  1000. ->where(
  1001. $queryBuilder->expr()->andX(
  1002. $queryBuilder->expr()->eq('pid', $rootUid),
  1003. $queryBuilder->expr()->eq('manually_deleted', 0)
  1004. )
  1005. )
  1006. ->execute();
  1007. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1008. $queryBuilder
  1009. ->update('pages')
  1010. ->set('deleted', 0)
  1011. ->where(
  1012. $queryBuilder->expr()->andX(
  1013. $queryBuilder->expr()->eq('uid', $rootUid),
  1014. $queryBuilder->expr()->eq('manually_deleted', 0)
  1015. )
  1016. )
  1017. ->execute();
  1018. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  1019. $queryBuilder
  1020. ->update('sys_template')
  1021. ->set('deleted', 0)
  1022. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  1023. ->executeStatement();
  1024. // remove filemounts
  1025. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1026. $queryBuilder
  1027. ->update('sys_filemounts')
  1028. ->set('deleted', 0)
  1029. ->where($queryBuilder->expr()->eq('identifier', "'1:/user_upload/" . $organizationId . "/'"))
  1030. ->executeStatement();
  1031. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  1032. $queryBuilder
  1033. ->update('sys_filemounts')
  1034. ->set('deleted', 0)
  1035. ->where($queryBuilder->expr()->eq('identifier', "'1:/form_definitions/" . $organizationId . "/'"))
  1036. ->executeStatement();
  1037. try {
  1038. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid, false);
  1039. if ($editorsGroupUid !== null) {
  1040. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1041. $queryBuilder
  1042. ->update('be_groups')
  1043. ->set('deleted', 0)
  1044. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1045. ->executeStatement();
  1046. }
  1047. } catch (NoSuchRecordException $e) {}
  1048. try {
  1049. $adminBeUserUid = $this->findAdminBeUserUid($rootUid, false);
  1050. if ($adminBeUserUid !== null) {
  1051. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1052. $queryBuilder
  1053. ->update('be_users')
  1054. ->set('deleted', 0)
  1055. ->where($queryBuilder->expr()->eq('uid', $adminBeUserUid))
  1056. ->executeStatement();
  1057. }
  1058. } catch (NoSuchRecordException $e) {}
  1059. // Look up for the config.yaml file of the website
  1060. $configMainDir = $_ENV['TYPO3_PATH_APP'] . '/config/sites';
  1061. $configYamlFile = "";
  1062. foreach (glob($configMainDir . '/*', GLOB_ONLYDIR) as $subdir) {
  1063. $yamlFile = $subdir . '/config.yaml.deleted';
  1064. if (is_file($yamlFile)) {
  1065. $conf = Yaml::parseFile($yamlFile);
  1066. if ($conf['rootPageId'] === $rootUid) {
  1067. $configYamlFile = $yamlFile;
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. $uploadDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/user_upload/deleted_' . $organizationId . '/';
  1073. $formsDir = $_ENV['TYPO3_PATH_APP'] . '/public/fileadmin/form_definitions/deleted_' . $organizationId . '/';
  1074. $toRename = [];
  1075. if (is_file($configYamlFile)) {
  1076. $toRename[$configYamlFile] = dirname($configYamlFile) . '/config.yaml';
  1077. }
  1078. if (is_dir($uploadDir)) {
  1079. $toRename[$uploadDir] = dirname($uploadDir) . '/' . $organizationId;
  1080. }
  1081. if (is_dir($formsDir)) {
  1082. $toRename[$formsDir] = dirname($formsDir) . '/' . $organizationId;
  1083. }
  1084. foreach ($toRename as $initialPath => $newPath) {
  1085. if (is_file($newPath)) {
  1086. throw new RuntimeException(
  1087. 'A file or directory named ' . $newPath . ' already exists, what happened?. Cancel.');
  1088. }
  1089. }
  1090. $renamed = [];
  1091. foreach ($toRename as $initialPath => $newPath) {
  1092. rename($initialPath, $newPath);
  1093. $renamed[$initialPath] = $newPath;
  1094. }
  1095. // remove eventual redirection from this site to another
  1096. $originUrl = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  1097. $this->removeRedirectionsFrom($originUrl);
  1098. // Try to commit the result
  1099. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1100. if (!$commitSuccess) {
  1101. throw new RuntimeException('Something went wrong while commiting the result');
  1102. }
  1103. return $rootUid;
  1104. } catch(\Throwable $e) {
  1105. // rollback
  1106. $this->connectionPool->getConnectionByName('Default')->rollback();
  1107. foreach ($renamed as $initialPath => $newPath) {
  1108. rename($newPath, $initialPath);
  1109. }
  1110. throw $e;
  1111. }
  1112. }
  1113. /**
  1114. * Clear the cache of the organization's website
  1115. *
  1116. * @param int $organizationId the organization's id whom site cache should be cleared
  1117. * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
  1118. * @return int
  1119. * @throws NoSuchWebsiteException
  1120. */
  1121. public function clearSiteCacheAction(int $organizationId, bool $clearAll=false): int
  1122. {
  1123. $rootUid = $this->otWebsiteRepository->findRootUidForOrganization($organizationId);
  1124. $this->otCacheManager->clearSiteCache($rootUid, $clearAll);
  1125. return $rootUid;
  1126. }
  1127. /**
  1128. * Perform a full scan of the website and returns a list of warnings
  1129. *
  1130. * @param int $organizationId
  1131. * @return array
  1132. * @throws NoSuchOrganizationException
  1133. * @throws NoSuchRecordException
  1134. * @throws NoSuchWebsiteException
  1135. */
  1136. private function scanSite(int $organizationId): array
  1137. {
  1138. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  1139. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  1140. $warnings = [];
  1141. // fetch and index pages and root page
  1142. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1143. $rootPage = null;
  1144. $pageIndex = [];
  1145. foreach ($pages as $page) {
  1146. $pageIndex[$page['uid']] = $page;
  1147. if ($page['is_siteroot'] === 1) { $rootPage = $page; }
  1148. }
  1149. // fetch organization and extradata
  1150. $organization = $this->fetchOrganization($organizationId);
  1151. $extraData = $this->fetchOrganizationExtraData($organizationId);
  1152. // load site's settings (uncomment if needed)
  1153. // $config = $this->otWebsiteRepository->findConfigFor($rootUid);
  1154. // Check site's title
  1155. if (trim($website['organization_name']) !== trim($organization->getName())) {
  1156. $warnings[] = "Website's organization name is different from what is registered in the Opentalent DB";
  1157. }
  1158. if (trim($rootPage['title']) !== trim($organization->getName())) {
  1159. $warnings[] = "Root page's title does not match the organization name";
  1160. }
  1161. // Who is the expected owner among the be_users? there should be only one.
  1162. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1163. $queryBuilder->getRestrictions()->removeAll();
  1164. $beUsers = $queryBuilder
  1165. ->select('uid', 'username')
  1166. ->from('be_users')
  1167. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  1168. ->execute()
  1169. ->fetchAllAssociative();
  1170. $owner = null;
  1171. if (count($beUsers) > 1) {
  1172. $warnings[] = 'Website is mounted on more than one be_user: ' .
  1173. implode(', ', array_map(static function($u) { return $u['username']; } ,$beUsers));
  1174. } elseif (count($beUsers) === 0) {
  1175. $warnings[] = 'Website is not mounted on any be_user';
  1176. } else {
  1177. $owner = $beUsers[0];
  1178. }
  1179. // are template constants up to date?
  1180. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1181. $actual_constants = $queryBuilder
  1182. ->select('constants')
  1183. ->from('sys_template')
  1184. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  1185. ->execute()
  1186. ->fetchOne();
  1187. $expected_constants = $this->getTemplateConstants($organizationId, $extraData);
  1188. $norm = static function ($s) {
  1189. return strtolower(preg_replace('/\s/', '', $s));
  1190. };
  1191. if ($norm($expected_constants) !== $norm($actual_constants)) {
  1192. $warnings[] = 'Template constants need an update';
  1193. }
  1194. $expected_templates = [
  1195. "OpenTalent.OtTemplating->home" => 0,
  1196. "OpenTalent.OtTemplating->legal" => 0,
  1197. "OpenTalent.OtTemplating->contact" => 0
  1198. ];
  1199. foreach ($pages as $page) {
  1200. if ($page['deleted']) {
  1201. continue;
  1202. }
  1203. // Is it the correct owner?
  1204. if ($owner !== null && $page['perms_userid'] !== $owner['uid']) {
  1205. $warnings[] = 'Page ' . $page['uid'] . ' has wrong owner';
  1206. }
  1207. if (!$page['is_siteroot']) {
  1208. // is the parent page state (deleted, hidden, restricted) the same as this page?
  1209. $parent = $pageIndex[$page['pid']];
  1210. if ($parent['deleted']) {
  1211. $warnings[] = 'The non-deleted page ' . $page['uid'] . ' has a deleted parent page';
  1212. }
  1213. if ($parent['hidden'] && !$page['hidden']) {
  1214. $warnings[] = 'The non-hidden page ' . $page['uid'] . ' has a hidden parent page';
  1215. }
  1216. if ($parent['fe_group'] < 0 && !($page['fe_group'] >= 0)) {
  1217. $warnings[] = 'The non-restricted page ' . $page['uid'] . ' has a restricted parent page';
  1218. }
  1219. }
  1220. // an expected template was found, remove it from the list of expected
  1221. if (
  1222. !$page['hidden'] &&
  1223. in_array($page['tx_fed_page_controller_action'], $expected_templates, true)
  1224. )
  1225. {
  1226. unset($expected_templates[$page['tx_fed_page_controller_action']]);
  1227. }
  1228. }
  1229. foreach ($expected_templates as $template => $_) {
  1230. $warnings[] = 'No page with template ' . $template;
  1231. }
  1232. return $warnings;
  1233. }
  1234. /**
  1235. * Get the current status of the organization's website
  1236. * If $fullScan is true, a deeper scan will be performed and warnings may be logged
  1237. *
  1238. * The status is among:
  1239. *
  1240. * - STATUS_NO_SUCH_WEBSITE
  1241. * - STATUS_EXISTING
  1242. * - STATUS_EXISTING_DELETED
  1243. * - STATUS_EXISTING_HIDDEN
  1244. * - STATUS_EXISTING_WITH_WARNINGS
  1245. * - STATUS_EXISTING_WITH_CRITICAL_ERRORS
  1246. *
  1247. * @param int $organizationId the organization's id whom site cache should be cleared
  1248. * @param bool $fullScan If true, a 'warnings' entry will be added to the result, and a full scan of
  1249. * the website pages will be performed.
  1250. * @return SiteStatus
  1251. * @throws Exception
  1252. * @throws InvalidWebsiteConfigurationException
  1253. * @throws NoSuchOrganizationException
  1254. * @throws NoSuchRecordException
  1255. * @throws NoSuchWebsiteException
  1256. */
  1257. public function getSiteStatusAction(int $organizationId, bool $fullScan = false): SiteStatus
  1258. {
  1259. try {
  1260. $siteInfos = $this->getSiteInfosAction($organizationId);
  1261. } catch (NoSuchWebsiteException $e) {
  1262. return new SiteStatus($organizationId, SiteStatus::STATUS_NO_SUCH_WEBSITE);
  1263. } catch(\Throwable $e) {
  1264. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_WITH_CRITICAL_ERRORS);
  1265. }
  1266. if ($siteInfos->isDeleted()) {
  1267. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_DELETED, $siteInfos);
  1268. }
  1269. if ($siteInfos->isHiddenOrRestricted()) {
  1270. return new SiteStatus($organizationId, SiteStatus::STATUS_EXISTING_HIDDEN, $siteInfos);
  1271. }
  1272. $warnings = null;
  1273. if ($fullScan) {
  1274. // ** Look for potential issues
  1275. $warnings = $this->scanSite($organizationId);
  1276. }
  1277. return new SiteStatus(
  1278. $organizationId,
  1279. $warnings ? SiteStatus::STATUS_EXISTING_WITH_WARNINGS : SiteStatus::STATUS_EXISTING,
  1280. $siteInfos,
  1281. $warnings
  1282. );
  1283. }
  1284. /**
  1285. * Set a new domain for the website.
  1286. * If $redirect is true, also add a redirection from the former domain to the new one
  1287. *
  1288. * @param int $organizationId
  1289. * @param string $newDomain
  1290. * @param bool $redirect
  1291. * @return int
  1292. * @throws InvalidWebsiteConfigurationException
  1293. * @throws NoSuchRecordException
  1294. * @throws NoSuchWebsiteException
  1295. */
  1296. public function setSiteCustomDomainAction(int $organizationId, string $newDomain, bool $redirect = true): int
  1297. {
  1298. if (!preg_match(self::RX_DOMAIN,$newDomain) &&
  1299. !preg_match("/[a-z0-9A-Z-]+\//", $newDomain)) {
  1300. throw new \InvalidArgumentException("The given domain does not seems to be a valid domain: " . $newDomain);
  1301. }
  1302. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  1303. $websiteUid = $website['uid'];
  1304. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($websiteUid);
  1305. // ## Update the ot_website table
  1306. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1307. $queryBuilder->update('ot_websites')
  1308. ->set('custom_domain', $newDomain)
  1309. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  1310. ->execute();
  1311. $originDomain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  1312. if (preg_replace('/https?:\/\//', '', $originDomain) === preg_replace('/https?:\/\//', '', $newDomain) ) {
  1313. throw new RuntimeException('The new domain should be different of the current one');
  1314. }
  1315. $this->writeConfigFile($rootUid, $newDomain);
  1316. if ($redirect) {
  1317. // Add the redirection
  1318. try {
  1319. $this->addRedirection($originDomain, $newDomain);
  1320. } catch (\RuntimeException $e) {} // silent the error until this https://assistance.opentalent.fr/browse/V8-3344
  1321. }
  1322. // Redirect the www.xyz to xyz
  1323. $this->addRedirection('www.' . $newDomain, $newDomain);
  1324. $this->otCacheManager->clearSiteCache($rootUid, true);
  1325. return $rootUid;
  1326. }
  1327. /**
  1328. * Return all the redirections from the given domain name,
  1329. * even if they have been marked as deleted.
  1330. *
  1331. * @param $domain string Domain name, without the http(s):// part
  1332. * @return array Rows from the sys_redirect table
  1333. * @throws Exception
  1334. */
  1335. protected function getRedirectionsFrom(string $domain): array
  1336. {
  1337. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1338. $queryBuilder->getRestrictions()->removeAll();
  1339. return $queryBuilder
  1340. ->select('*')
  1341. ->from('sys_redirect')
  1342. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1343. ->execute()
  1344. ->fetchAllAssociative();
  1345. }
  1346. /**
  1347. * Return all the redirections to the given domain name,
  1348. * even if they have been marked as deleted.
  1349. *
  1350. * @param $domain string Domain name, without the http(s):// part
  1351. * @return array Rows from the sys_redirect table
  1352. */
  1353. protected function getRedirectionsTo(string $domain): array
  1354. {
  1355. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1356. $queryBuilder->getRestrictions()->removeAll();
  1357. /** @noinspection HttpUrlsUsage */
  1358. return $queryBuilder
  1359. ->select('*')
  1360. ->from('sys_redirect')
  1361. ->where(
  1362. $queryBuilder->expr()->in(
  1363. 'target',
  1364. [
  1365. 'http://' . $queryBuilder->expr()->literal($domain),
  1366. 'https://' . $queryBuilder->expr()->literal($domain)
  1367. ]
  1368. )
  1369. )
  1370. ->execute()
  1371. ->fetchAllAssociative();
  1372. }
  1373. /**
  1374. * Add a new redirection from $fromDomain to $toDomain.
  1375. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1376. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1377. *
  1378. * @param $fromDomain
  1379. * @param $toDomain
  1380. * @return int Status of the operation
  1381. * @throws Exception
  1382. */
  1383. public function addRedirection($fromDomain, $toDomain): int
  1384. {
  1385. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1386. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1387. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1388. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1389. }
  1390. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1391. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1392. }
  1393. $existing = $this->getRedirectionsFrom($fromDomain);
  1394. $toUpdate = null;
  1395. foreach ($existing as $redirection) {
  1396. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1397. // a redirection from this domain already exists, and it is not deleted nor disabled
  1398. // check if the target is not the same domain
  1399. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1400. throw new RuntimeException(
  1401. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1402. );
  1403. }
  1404. // else, target is already the same domain, it will be updated
  1405. $toUpdate = $redirection;
  1406. break;
  1407. }
  1408. // a redirection from this domain already exists, but it is deleted or disabled
  1409. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1410. // the target is the same domain, we'll reactivate this record
  1411. $toUpdate = $redirection;
  1412. break;
  1413. }
  1414. }
  1415. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1416. $data = [
  1417. 'deleted' => 0,
  1418. 'disabled' => 0,
  1419. 'source_host' => $fromDomain,
  1420. 'source_path' => '/.*/',
  1421. 'is_regexp' => 1,
  1422. 'force_https' => 0,
  1423. 'respect_query_parameters' => 0,
  1424. 'keep_query_parameters' => 1,
  1425. 'target' => 'https://' . $toDomain,
  1426. 'target_statuscode' => 301
  1427. ];
  1428. if ($toUpdate !== null) {
  1429. $q = $queryBuilder
  1430. ->update('sys_redirect')
  1431. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1432. foreach ($data as $k => $v) {
  1433. $q->set($k, $v);
  1434. }
  1435. $q->execute();
  1436. return self::REDIRECTION_UPDATED;
  1437. }
  1438. $queryBuilder
  1439. ->insert('sys_redirect')
  1440. ->values($data)
  1441. ->execute();
  1442. return self::REDIRECTION_CREATED;
  1443. }
  1444. /**
  1445. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1446. * If $hard is true, delete it completely.
  1447. *
  1448. * @param $fromDomain
  1449. * @param bool $hard
  1450. * @return int Number of affected rows
  1451. * @throws Exception
  1452. */
  1453. public function removeRedirectionsFrom($fromDomain, bool $hard=false): int
  1454. {
  1455. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1456. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1457. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1458. }
  1459. $existing = $this->getRedirectionsFrom($fromDomain);
  1460. $deleted = 0;
  1461. foreach ($existing as $redirection) {
  1462. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1463. ++$deleted;
  1464. }
  1465. return $deleted;
  1466. }
  1467. /**
  1468. * Set the rights of admin and editors of the website
  1469. * on all the existing pages, including deleted ones
  1470. *
  1471. * @param int $organizationId
  1472. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1473. * @param int|null $editorsGroupUid Force the editors be-group uid
  1474. * @param int|null $adminUid Force the admin be-user uid
  1475. * @return int The uid of the website root page
  1476. * @throws NoSuchWebsiteException
  1477. * @throws NoSuchRecordException
  1478. */
  1479. protected function setBeUserPerms(
  1480. int $organizationId,
  1481. bool $createIfMissing = false,
  1482. int $editorsGroupUid = null,
  1483. int $adminUid = null
  1484. ): int
  1485. {
  1486. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1487. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1488. "and force the admin or group uid at the same time.");
  1489. }
  1490. $rootUid = $this->otWebsiteRepository->findRootUidForOrganization($organizationId);
  1491. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1492. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']] ?? false;
  1493. if ($editorsGroupUid === null) {
  1494. try {
  1495. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1496. } catch (NoSuchRecordException $e) {
  1497. if (!$createIfMissing) {
  1498. throw $e;
  1499. }
  1500. }
  1501. }
  1502. if ($adminUid === null) {
  1503. try {
  1504. $adminUid = $this->findAdminBeUserUid($rootUid);
  1505. } catch (NoSuchRecordException $e) {
  1506. if (!$createIfMissing) {
  1507. throw $e;
  1508. }
  1509. }
  1510. }
  1511. // Creates or update the admin be_group
  1512. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1513. $organizationId,
  1514. $rootUid,
  1515. $organizationExtraData['admin'],
  1516. $editorsGroupUid
  1517. );
  1518. // Creates or update the admin be_user
  1519. $adminUid = $this->createOrUpdateBeUser(
  1520. $organizationId,
  1521. $editorsGroupUid,
  1522. $organizationExtraData['admin'],
  1523. $adminUid
  1524. );
  1525. // Reset the appartenance to groups
  1526. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1527. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1528. $queryBuilder
  1529. ->update('be_users')
  1530. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1531. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1532. ->execute();
  1533. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1534. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1535. $queryBuilder
  1536. ->update('be_groups')
  1537. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1538. ->set('subgroup', $mainEditorGroupUid)
  1539. ->execute();
  1540. // setup default owner for the website
  1541. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1542. $tsConfig = $queryBuilder->select('TSconfig')
  1543. ->from('pages')
  1544. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1545. ->execute()
  1546. ->fetchOne();
  1547. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1548. $tsConfig .= "\nTCEMAIN {\n" .
  1549. " permissions.userid = " . $adminUid ."\n" .
  1550. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1551. "}";
  1552. $queryBuilder
  1553. ->update('pages')
  1554. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1555. ->set('TSconfig', $tsConfig)
  1556. ->execute();
  1557. // fetch pages and root page
  1558. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1559. // To understand how the rights levels are computed:
  1560. // @see https://gitlab.2iopenservice.com/opentalent/ot_typo3/-/blob/master/doc/be_users.md?ref_type=heads
  1561. foreach ($pages as $page) {
  1562. $hidden = $page['hidden'];
  1563. if ($page['ot_page_type'] === OtPageTypeEnum::ROOT->value) {
  1564. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1565. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1566. if ($isPremium) {
  1567. $adminPerms += self::PERM_NEW;
  1568. $editorsPerms += self::PERM_NEW;
  1569. }
  1570. } else if ($page['ot_page_type'] === OtPageTypeEnum::MANDATORY_NON_EDITABLE->value) {
  1571. $adminPerms = self::PERM_SHOW;
  1572. $editorsPerms = self::PERM_SHOW;
  1573. if ($isPremium) {
  1574. $adminPerms += self::PERM_NEW;
  1575. $editorsPerms += self::PERM_NEW;
  1576. }
  1577. } else if ($page['ot_page_type'] === OtPageTypeEnum::MANDATORY_EDITABLE->value) {
  1578. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_PAGE + self::PERM_EDIT_CONTENT;
  1579. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_PAGE + self::PERM_EDIT_CONTENT;
  1580. if ($isPremium) {
  1581. $adminPerms += self::PERM_NEW;
  1582. $editorsPerms += self::PERM_NEW;
  1583. }
  1584. } else if ($page['ot_page_type'] === OtPageTypeEnum::USER_CREATED->value && !$isPremium) {
  1585. // Un utilisateur standard ne peut pas créer de nouvelles pages; les pages créées précédemment
  1586. // avec une version premium doivent être inaccessibles.
  1587. $adminPerms = self::PERM_NONE;
  1588. $editorsPerms = self::PERM_NONE;
  1589. $hidden = 1;
  1590. } else if ($page['ot_page_type'] === OtPageTypeEnum::LEGACY_USER_CREATED->value && !$isPremium) {
  1591. // Cas particulier des pages créées par les utilisateurs standard avant la remise à plat des droits
  1592. // @see doc/be_users.md
  1593. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE + self::PERM_DELETE;
  1594. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE + self::PERM_DELETE;
  1595. } else {
  1596. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1597. if ($isPremium) {
  1598. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1599. }
  1600. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1601. if ($isPremium) {
  1602. $editorsPerms += self::PERM_DELETE + self::PERM_NEW;
  1603. }
  1604. }
  1605. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1606. $queryBuilder
  1607. ->update('pages')
  1608. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1609. ->set('perms_userid', $adminUid)
  1610. ->set('perms_groupid', $editorsGroupUid)
  1611. ->set('perms_user', $adminPerms)
  1612. ->set('perms_group', $editorsPerms)
  1613. ->set('perms_everybody', self::PERM_NONE)
  1614. ->set('hidden', $hidden)
  1615. ->execute();
  1616. }
  1617. return $rootUid;
  1618. }
  1619. /**
  1620. * Action for resetting the rights of admin and editors of the website
  1621. * on all the existing pages, including deleted ones
  1622. *
  1623. * @param int $organizationId
  1624. * @param bool $createIfMissing
  1625. * @return int
  1626. * @throws NoSuchRecordException
  1627. * @throws NoSuchWebsiteException
  1628. * @throws \Throwable
  1629. */
  1630. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1631. {
  1632. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1633. try {
  1634. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1635. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1636. if (!$commitSuccess) {
  1637. throw new RuntimeException('Something went wrong while commiting the result');
  1638. }
  1639. return $rootUid;
  1640. }
  1641. catch (\Throwable $e) {
  1642. // rollback
  1643. $this->connectionPool->getConnectionByName('Default')->rollback();
  1644. throw $e;
  1645. }
  1646. }
  1647. /**
  1648. * Delete all the pages created by the users, leaving only the starting mandatory pages.
  1649. *
  1650. * @param int $organizationId
  1651. * @return int
  1652. * @throws NoSuchRecordException
  1653. * @throws NoSuchWebsiteException
  1654. * @throws \Doctrine\DBAL\Exception
  1655. * @throws Throwable
  1656. */
  1657. public function deleteUserCreatedPagesAction(int $organizationId): int
  1658. {
  1659. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  1660. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  1661. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1662. $cnn = $this->connectionPool->getConnectionByName('Default');
  1663. $cnn->beginTransaction();
  1664. try {
  1665. foreach($pages as $page) {
  1666. if ($page['ot_page_type'] === OtPageTypeEnum::USER_CREATED->value) {
  1667. $this->delete('tt_content', 'pid', $page['uid'], true);
  1668. $this->delete('pages', 'uid', $page['uid'], true);
  1669. }
  1670. }
  1671. $cnn->commit();
  1672. } catch (\Throwable $e) {
  1673. $cnn->rollBack();
  1674. throw $e;
  1675. }
  1676. return $rootUid;
  1677. }
  1678. /**
  1679. * Delete then regenerate all the typo3 sites yaml config files
  1680. *
  1681. * This is a more efficient alternative to the update --all, designed to be executed on a development environment
  1682. * just after the databases cloning.
  1683. *
  1684. * @throws NoSuchRecordException
  1685. * @throws NoSuchWebsiteException
  1686. * @throws \Doctrine\DBAL\ConnectionException
  1687. * @throws \Doctrine\DBAL\DBALException
  1688. * @throws InvalidWebsiteConfigurationException
  1689. * @throws \Throwable
  1690. */
  1691. public function regenConfigFilesAction(): void
  1692. {
  1693. $configRootDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1694. $backupConfigDir = $_ENV['TYPO3_PATH_APP'] . "/config/bkp_sites";
  1695. if (file_exists($backupConfigDir)) {
  1696. throw new RuntimeException(
  1697. 'A directory or a file with this name already exist: ' . $backupConfigDir . '. Delete it before continuing.'
  1698. );
  1699. }
  1700. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1701. try {
  1702. // archive the existing files, in case a rollback is needed
  1703. rename($configRootDir, $backupConfigDir);
  1704. $this->mkDir($configRootDir);
  1705. $websites = $this->otWebsiteRepository->getAll();
  1706. foreach ($websites as $website) {
  1707. if (!((int)$website['organization_id'] > 0)) {
  1708. continue;
  1709. }
  1710. $identifier = str_replace('/', '', $website['subdomain']) . '_' . $website['organization_id'];
  1711. $configDir = $configRootDir . $identifier;
  1712. $configFilename = $configDir . "/config.yaml";
  1713. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  1714. $config = $siteConfig->getConfiguration();
  1715. $yamlConfig = Yaml::dump($config, 99, 2);
  1716. try {
  1717. $this->mkDir($configDir);
  1718. } catch (\Throwable $e) {
  1719. throw new RuntimeException('Unable to create the directory ' . $configDir, 0, $e);
  1720. }
  1721. $this->writeFile($configFilename, $yamlConfig);
  1722. // ## Update the ot_website identifier
  1723. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1724. $queryBuilder->update('ot_websites')
  1725. ->set('config_identifier', $identifier)
  1726. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  1727. ->execute();
  1728. }
  1729. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1730. if (!$commitSuccess) {
  1731. throw new RuntimeException('Something went wrong while committing the result');
  1732. }
  1733. $this->rrmdir($backupConfigDir);
  1734. }
  1735. catch (\Throwable $e) {
  1736. // rollback
  1737. if (!file_exists($configRootDir)) {
  1738. $this->rrmdir($configRootDir);
  1739. }
  1740. if (!file_exists($backupConfigDir)) {
  1741. rename($backupConfigDir, $configRootDir);
  1742. }
  1743. $this->connectionPool->getConnectionByName('Default')->rollback();
  1744. throw $e;
  1745. }
  1746. }
  1747. /**
  1748. * Retrieve the Organization object from the repository and then,
  1749. * from the Opentalent API
  1750. *
  1751. * @param $organizationId
  1752. * @return Organization
  1753. * @throws NoSuchOrganizationException
  1754. */
  1755. public function fetchOrganization($organizationId): object
  1756. {
  1757. try {
  1758. return $this->organizationRepository->findById($organizationId);
  1759. } catch (ApiRequestException $e) {
  1760. throw new NoSuchOrganizationException('Unable to fetch the organization with id: ' . $organizationId);
  1761. }
  1762. }
  1763. /**
  1764. * Insert a new row in the 'pages' table of the Typo3 DB
  1765. * and return its uid
  1766. *
  1767. * @param Organization $organization
  1768. * @return int
  1769. */
  1770. private function insertOtWebsite(Organization $organization): int
  1771. {
  1772. $values = [
  1773. 'organization_id' => $organization->getId(),
  1774. 'subdomain' => $organization->getSubDomain(),
  1775. 'locale' => 'fr_FR',
  1776. 'organization_name' => $organization->getName(),
  1777. 'template' => self::DEFAULT_THEME
  1778. ];
  1779. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1780. $queryBuilder->insert('ot_websites')
  1781. ->values($values)
  1782. ->execute();
  1783. return (int)$queryBuilder->getConnection()->lastInsertId();
  1784. }
  1785. /**
  1786. * Determine which folder-type Typo3 page should contain the new website
  1787. * CREATES IT if needed, and return its uid
  1788. *
  1789. * @return int
  1790. */
  1791. private function getParentFolderUid(): int
  1792. {
  1793. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1794. $siteCount = $queryBuilder
  1795. ->count('uid')
  1796. ->from('pages')
  1797. ->where('is_siteroot=1')
  1798. ->execute()
  1799. ->fetchOne();
  1800. $thousand = (int)(($siteCount + 1) / 1000);
  1801. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1802. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1803. $uid = $queryBuilder
  1804. ->select('uid')
  1805. ->from('pages')
  1806. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1807. ->andWhere('dokType=254')
  1808. ->execute()
  1809. ->fetchOne();
  1810. if ($uid === null) {
  1811. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1812. $queryBuilder->insert('pages')
  1813. ->values([
  1814. 'pid' => 0,
  1815. 'title' => $folderName,
  1816. 'dokType' => 254,
  1817. 'sorting' => 11264,
  1818. 'perms_userid' => 1,
  1819. 'perms_groupid' => 31,
  1820. 'perms_group' => 27,
  1821. ])
  1822. ->execute();
  1823. $uid = $queryBuilder->getConnection()->lastInsertId();
  1824. }
  1825. return $uid;
  1826. }
  1827. /**
  1828. * Insert a new row in the 'pages' table of the Typo3 DB
  1829. * and return its uid
  1830. *
  1831. * @param int $website_uid
  1832. * @param int $pid
  1833. * @param string $title
  1834. * @param string $slug
  1835. * @param OtPageTypeEnum $otPageType
  1836. * @param string $template
  1837. * @param array $moreValues
  1838. * @return int
  1839. */
  1840. private function insertPage(int $website_uid,
  1841. int $pid,
  1842. string $title,
  1843. string $slug,
  1844. OtPageTypeEnum $otPageType = OtPageTypeEnum::MANDATORY_EDITABLE,
  1845. string $template = '',
  1846. array $moreValues = []
  1847. ): int
  1848. {
  1849. $defaultValues = [
  1850. 'pid' => $pid,
  1851. 'perms_groupid' => 3,
  1852. 'perms_user' => 27,
  1853. 'dokType' => self::DOK_PAGE,
  1854. 'title' => $title,
  1855. 'slug' => $slug,
  1856. 'backend_layout' => 'flux__grid',
  1857. 'backend_layout_next_level' => 'flux__grid',
  1858. 'ot_website_uid' => $website_uid,
  1859. 'ot_page_type' => $otPageType->value
  1860. ];
  1861. if ($template) {
  1862. $defaultValues['tx_fed_page_controller_action'] = $template;
  1863. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1864. }
  1865. $values = array_merge($defaultValues, $moreValues);
  1866. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1867. $queryBuilder->insert('pages')
  1868. ->values($values)
  1869. ->execute();
  1870. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1871. $this->createdPagesIndex[$slug] = $uid;
  1872. return $uid;
  1873. }
  1874. /**
  1875. * Insert the root page of a new organization's website
  1876. * and return its uid
  1877. *
  1878. * @param int $website_uid
  1879. * @param string $title
  1880. * @return int
  1881. */
  1882. private function insertRootPage(int $website_uid, string $title): int
  1883. {
  1884. return $this->insertPage(
  1885. $website_uid,
  1886. $this->getParentFolderUid(),
  1887. $title,
  1888. '/',
  1889. OtPageTypeEnum::ROOT,
  1890. self::TEMPLATE_HOME,
  1891. [
  1892. 'is_siteroot' => 1,
  1893. 'TSconfig' => 'TCAdefaults.pages.ot_website_uid=' . $website_uid
  1894. ]
  1895. );
  1896. }
  1897. /**
  1898. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1899. *
  1900. * @param int $pid
  1901. * @param string $cType
  1902. * @param string $bodyText
  1903. * @param int $colPos
  1904. * @param array $moreValues
  1905. */
  1906. private function insertContent(int $pid,
  1907. string $cType=self::CTYPE_TEXT,
  1908. string $bodyText = '',
  1909. int $colPos=0,
  1910. array $moreValues = []): void
  1911. {
  1912. $defaultValues = [
  1913. 'pid' => $pid,
  1914. 'CType' => $cType,
  1915. 'colPos' => $colPos,
  1916. 'bodyText' => $bodyText
  1917. ];
  1918. $values = array_merge($defaultValues, $moreValues);
  1919. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1920. $queryBuilder->insert('tt_content')
  1921. ->values($values)
  1922. ->execute();
  1923. }
  1924. private function fetchOrganizationExtraData(int $organizationId) {
  1925. $cnn = new PDO(
  1926. "mysql:host=" . OpentalentEnvService::get('DB_HOST') . ";dbname=opentalent",
  1927. OpentalentEnvService::get('DB_USER'),
  1928. OpentalentEnvService::get('DB_PASSWORD'),
  1929. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1930. );
  1931. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1932. $stmt = $cnn->query(
  1933. "SELECT o.id, o.name, o.facebook, o.twitter, o.instagram, o.youtube,
  1934. o.category, o.logo_id, p.logoDonorsMove
  1935. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1936. ON o.parameters_id = p.id
  1937. WHERE o.id=" . $organizationId . ";"
  1938. );
  1939. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1940. $data = $stmt->fetch();
  1941. $stmt = $cnn->query(
  1942. "SELECT c.email
  1943. FROM opentalent.ContactPoint c
  1944. INNER JOIN opentalent.organization_contactpoint o
  1945. ON o.contactPoint_id = c.id
  1946. WHERE o.organization_id = " . $organizationId . "
  1947. ORDER BY FIELD(c.contactType, 'CONTACT', 'PRINCIPAL', 'BILL', 'OTHER');"
  1948. );
  1949. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1950. $data['email'] = $stmt->fetch()['email'];
  1951. $stmt = $cnn->query(
  1952. "SELECT n.name, n.logo, n.url
  1953. FROM opentalent.Network n
  1954. INNER JOIN
  1955. (opentalent.NetworkOrganization l
  1956. INNER JOIN opentalent.Organization o
  1957. ON l.organization_id = o.id)
  1958. ON l.network_id = n.id
  1959. WHERE l.endDate is NULL
  1960. AND o.id=" . $organizationId . ";"
  1961. );
  1962. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1963. $data['network'] = $stmt->fetch();
  1964. $stmt = $cnn->query(
  1965. "SELECT p.username, p.id as person_id, s.product
  1966. FROM opentalent.Person p
  1967. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1968. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1969. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1970. );
  1971. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1972. $data['admin'] = $stmt->fetch();
  1973. return $data;
  1974. }
  1975. /**
  1976. * Return the content of `sys_template`.`constants` of
  1977. * the website of the given organization
  1978. *
  1979. * @param int $organizationId
  1980. * @param array $organizationExtraData
  1981. * @return string
  1982. */
  1983. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1984. {
  1985. return "plugin.tx_ottemplating {\n" .
  1986. " settings {\n" .
  1987. " organization {\n" .
  1988. " id = " . $organizationId . "\n" .
  1989. " name = " . $organizationExtraData['name'] . "\n" .
  1990. " is_network = " . ($organizationExtraData['category'] === 'NETWORK' ? '1' : '0') . "\n" .
  1991. " email = " . $organizationExtraData['email'] . "\n" .
  1992. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1993. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1994. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1995. " instagram = " . $organizationExtraData['instagram'] . "\n" .
  1996. " youtube = " . $organizationExtraData['youtube'] . "\n" .
  1997. " }\n" .
  1998. " network {\n" .
  1999. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  2000. " name = " . $organizationExtraData['network']['name'] . "\n" .
  2001. " url = " . $organizationExtraData['network']['url'] . "\n" .
  2002. " }\n" .
  2003. " }\n" .
  2004. "}";
  2005. }
  2006. /**
  2007. * Create the given directory, give its property to the www-data group, and
  2008. * record it as a newly created dir (for an eventual rollback)
  2009. *
  2010. * @param string $dirPath
  2011. */
  2012. private function mkDir(string $dirPath): void
  2013. {
  2014. if (!mkdir($dirPath) && !is_dir($dirPath)) {
  2015. throw new RuntimeException(sprintf('Directory "%s" was not created', $dirPath));
  2016. }
  2017. $this->createdDirs[] = $dirPath;
  2018. chgrp($dirPath, 'www-data');
  2019. }
  2020. /**
  2021. * Write the given file with content, give its property to the www-data group, and
  2022. * record it as a newly created file (for an eventual rollback)
  2023. *
  2024. * @param string $path
  2025. * @param string $content
  2026. */
  2027. private function writeFile(string $path, string $content): void
  2028. {
  2029. $f = fopen($path, 'wb');
  2030. try
  2031. {
  2032. fwrite($f, $content);
  2033. $this->createdFiles[] = $path;
  2034. try {
  2035. chgrp($path, 'www-data');
  2036. } catch (\Throwable $e) {
  2037. }
  2038. } finally {
  2039. fclose($f);
  2040. }
  2041. }
  2042. /**
  2043. * Create or update the .../sites/.../config.yaml file of the given site
  2044. * Return the identifier of the created website
  2045. *
  2046. * @param int $rootUid
  2047. * @param bool $forceRecreate
  2048. * @param null $identifier
  2049. * @return string Identifier of the newly created configuration file
  2050. * @throws InvalidWebsiteConfigurationException
  2051. * @throws NoSuchRecordException
  2052. * @throws NoSuchWebsiteException
  2053. */
  2054. private function writeConfigFile(int $rootUid, bool $forceRecreate = false, $identifier = null): string
  2055. {
  2056. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  2057. $domain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  2058. try {
  2059. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid, $identifier);
  2060. } catch (RuntimeException $e) {
  2061. // identifier might be obsolete
  2062. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid);
  2063. }
  2064. [$configFilename, $config] = $existing;
  2065. if (!$configFilename) {
  2066. $identifier = $website['subdomain'] . '_' . $website['organization_id'];
  2067. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $identifier;
  2068. $configFilename = $configDir . "/config.yaml";
  2069. $isNew = true;
  2070. if (file_exists($configFilename)) {
  2071. throw new RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  2072. }
  2073. } else {
  2074. $configDir = dirname($configFilename);
  2075. if ($identifier === null) {
  2076. $identifier = basename($configDir);
  2077. }
  2078. $config['base'] = 'https://' . $domain;
  2079. $isNew = false;
  2080. }
  2081. if ($isNew || $forceRecreate) {
  2082. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  2083. $config = $siteConfig->getConfiguration();
  2084. }
  2085. $yamlConfig = Yaml::dump($config, 99, 2);
  2086. if (!file_exists($configDir)) {
  2087. $this->mkDir($configDir);
  2088. }
  2089. $this->writeFile($configFilename, $yamlConfig);
  2090. // Set the owner and mods, in case www-data is not the one who run this command
  2091. // @see https://www.php.net/manual/fr/function.stat.php
  2092. try {
  2093. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  2094. chown($configFilename, $stats['4']);
  2095. chgrp($configFilename, $stats['5']);
  2096. chmod($configFilename, $stats['2']);
  2097. } catch (\Throwable $e) {
  2098. }
  2099. // Flush cache:
  2100. try {
  2101. $cacheSystem = $this->cacheManager->getCache('core');
  2102. $cacheSystem->remove('site-configuration');
  2103. $cacheSystem->remove('pseudo-sites');
  2104. } catch (NoSuchCacheException $e) {
  2105. }
  2106. return $identifier;
  2107. }
  2108. /**
  2109. * Recursively remove the target directory (! no rollback available)
  2110. */
  2111. private function rrmdir(string $dir): bool
  2112. {
  2113. if (!is_dir($dir) || is_link($dir)) {
  2114. return unlink($dir);
  2115. }
  2116. foreach (scandir($dir) as $file) {
  2117. if ($file === '.' || $file === '..') {
  2118. continue;
  2119. }
  2120. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) {
  2121. chmod($dir . DIRECTORY_SEPARATOR . $file, 0777);
  2122. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) {
  2123. return false;
  2124. }
  2125. }
  2126. }
  2127. return rmdir($dir);
  2128. }
  2129. /**
  2130. * Create the BE user for the website, then return its uid
  2131. * The user shall be already created in the Opentalent DB
  2132. *
  2133. * @param int $organizationId
  2134. * @param int $siteGroupUid
  2135. * @param array $userData
  2136. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  2137. * @return int The uid of the created be_user
  2138. * @throws InvalidPasswordHashException
  2139. */
  2140. private function createOrUpdateBeUser(int $organizationId,
  2141. int $siteGroupUid,
  2142. array $userData,
  2143. int $updateUid = null): int
  2144. {
  2145. if (!isset($userData['username'])) {
  2146. throw new RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  2147. }
  2148. $hashInstance = GeneralUtility::makeInstance(PasswordHashFactory::class)->getDefaultHashInstance('BE');
  2149. $hashedRandomPassword = $hashInstance->getHashedPassword(uniqid("", true));
  2150. $adminGroup = (self::IS_PRODUCT_PREMIUM[$userData['product']] ?? false) ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  2151. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  2152. $values = [
  2153. 'username' => $userData['username'],
  2154. 'password' => $hashedRandomPassword,
  2155. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  2156. 'deleted' => 0,
  2157. 'lang' => 'fr',
  2158. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  2159. 'userMods' => null, // inherited from the base AdminGroup
  2160. 'db_mountpoints' => null, // inherited from the editors group
  2161. 'file_mountpoints' => null, // inherited from the editors group
  2162. 'options' => 3, // allow to inherit both db and file mountpoints from groups
  2163. 'tx_opentalent_opentalentId' => $userData['id'] ?? null,
  2164. 'tx_opentalent_organizationId' => $organizationId,
  2165. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  2166. ];
  2167. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2168. if ($updateUid !== null) {
  2169. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));
  2170. foreach ($values as $k => $v) {
  2171. $q->set($k, $v);
  2172. }
  2173. $q->execute();
  2174. return $updateUid;
  2175. }
  2176. $queryBuilder->insert('be_users')
  2177. ->values($values)
  2178. ->execute();
  2179. return (int)$queryBuilder->getConnection()->lastInsertId();
  2180. }
  2181. /**
  2182. * Create the BE editors group for the website, then return its uid
  2183. *
  2184. * @param int $organizationId
  2185. * @param int $rootUid
  2186. * @param array $userData
  2187. * @param int|null $updateUid If passed, this method will update this be_group instead of creating a new one
  2188. * @return int The uid of the created be_group
  2189. */
  2190. private function createOrUpdateBeGroup(int $organizationId,
  2191. int $rootUid,
  2192. array $userData,
  2193. int $updateUid = null): int
  2194. {
  2195. $groupName = 'editors_' . $organizationId;
  2196. // get the existing filemounts
  2197. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  2198. $queryBuilder
  2199. ->select('uid')
  2200. ->from('sys_filemounts')
  2201. ->where("identifier LIKE '1:%user_upload/" . $organizationId . "/'")
  2202. ->orWhere("identifier LIKE '1:%form_definitions/" . $organizationId . "/'");
  2203. $statement = $queryBuilder->executeQuery();
  2204. $rows = $statement->fetchAllAssociative() ?: [];
  2205. $fileMounts = [];
  2206. foreach ($rows as $row) {
  2207. $fileMounts[] = $row['uid'];
  2208. }
  2209. $mainGroup = (self::IS_PRODUCT_PREMIUM[$userData['product']] ?? false) ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  2210. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  2211. $values = [
  2212. 'title' => $groupName,
  2213. 'deleted' => 0,
  2214. 'subgroup' => $mainGroupUid,
  2215. 'db_mountpoints' => $rootUid,
  2216. 'file_mountPoints' => implode(',', $fileMounts),
  2217. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  2218. 'groupMods' => '', // inherited from the base EditorsGroup
  2219. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  2220. 'tables_select' => '', // inherited from the base EditorsGroup
  2221. 'tables_modify' => '', // inherited from the base EditorsGroup
  2222. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  2223. ];
  2224. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2225. if ($updateUid !== null) {
  2226. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));
  2227. foreach ($values as $k => $v) {
  2228. $q->set($k, $v);
  2229. }
  2230. $q->executeStatement();
  2231. return $updateUid;
  2232. }
  2233. $queryBuilder->insert('be_groups')
  2234. ->values($values)
  2235. ->executeStatement();
  2236. return $queryBuilder->getConnection()->lastInsertId();
  2237. }
  2238. /**
  2239. * Try to find and return the uid of the editors be_group
  2240. * for this website
  2241. *
  2242. * @param int $rootUid
  2243. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2244. * @return int
  2245. * @throws Exception
  2246. * @throws NoSuchRecordException
  2247. */
  2248. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  2249. $editorsGroups = [
  2250. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  2251. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  2252. ];
  2253. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2254. if (!$withRestrictions) {
  2255. $queryBuilder->getRestrictions()->removeAll();
  2256. }
  2257. $editorsGroupUid = $queryBuilder
  2258. ->select('uid')
  2259. ->from('be_groups')
  2260. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2261. ->andWhere('(FIND_IN_SET(' . $editorsGroups[0] . ', subgroup) > 0 OR FIND_IN_SET(' . $editorsGroups[1] . ', subgroup) > 0)')
  2262. ->execute()
  2263. ->fetchOne();
  2264. if ($editorsGroupUid === null) {
  2265. throw new NoSuchRecordException("No editors be_group found " .
  2266. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  2267. }
  2268. return $editorsGroupUid;
  2269. }
  2270. /**
  2271. * Try to find and return the uid of the admin be_user
  2272. * for this website
  2273. *
  2274. * @param int $rootUid
  2275. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2276. * @return int
  2277. * @throws NoSuchRecordException
  2278. * @throws NoSuchWebsiteException
  2279. */
  2280. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2281. $adminGroups = [
  2282. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2283. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2284. ];
  2285. $adminUid = null;
  2286. try {
  2287. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2288. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2289. if (!$withRestrictions) {
  2290. $queryBuilder->getRestrictions()->removeAll();
  2291. }
  2292. return $queryBuilder
  2293. ->select('uid')
  2294. ->from('be_users')
  2295. ->where('FIND_IN_SET(' . $editorsGroupUid . ', usergroup) > 0')
  2296. ->andWhere('(FIND_IN_SET(' . $adminGroups[0] . ', usergroup) > 0 OR FIND_IN_SET(' . $adminGroups[1] . ', usergroup) > 0)')
  2297. ->execute()
  2298. ->fetchOne();
  2299. } catch (NoSuchRecordException $e) {
  2300. // the editors group does not exist
  2301. }
  2302. // [For retro-compatibility] Try to find if there is a be_user still in the v8.7 data format
  2303. if ($adminUid === null) {
  2304. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  2305. $extraData = $this->fetchOrganizationExtraData($website['organization_id']);
  2306. $expectedUsername = $extraData['admin']['username'];
  2307. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2308. if (!$withRestrictions) {
  2309. $queryBuilder->getRestrictions()->removeAll();
  2310. }
  2311. $row = $queryBuilder
  2312. ->select('uid', 'db_mountpoints')
  2313. ->from('be_users')
  2314. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2315. ->execute()
  2316. ->fetchAssociative();
  2317. if ($row['uid']) {
  2318. if ((string)$rootUid !== (string)$row['db_mountpoints']) {
  2319. throw new RuntimeException(
  2320. "The be_user named '" . $expectedUsername .
  2321. "' has unexpected mounted website(s) (expected: " . $rootUid .
  2322. ", found: " . $row['db_mountpoints'] . "). Abort."
  2323. );
  2324. }
  2325. $adminUid = $row['uid'];
  2326. }
  2327. }
  2328. if ($adminUid === null) {
  2329. throw new NoSuchRecordException("No admin be_user found " .
  2330. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2331. }
  2332. return $adminUid;
  2333. }
  2334. /**
  2335. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2336. *
  2337. * @param int $groupType
  2338. * @return int
  2339. */
  2340. protected function getBaseBeGroupUid(int $groupType): int
  2341. {
  2342. $expectedName = self::BEGROUP_NAME[$groupType];
  2343. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2344. $uid = $queryBuilder
  2345. ->select('uid')
  2346. ->from('be_groups')
  2347. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2348. ->execute()
  2349. ->fetchOne();
  2350. if (!$uid) {
  2351. throw new RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2352. }
  2353. return $uid;
  2354. }
  2355. /**
  2356. * Enable frontend editing for user
  2357. *
  2358. * @param int $adminUid
  2359. * @noinspection PhpInternalEntityUsedInspection
  2360. */
  2361. private function enableFeEditing(int $adminUid): void
  2362. {
  2363. $BE_USER = GeneralUtility::makeInstance(BackendUserAuthentication::class);
  2364. $user = $BE_USER->getRawUserByUid($adminUid);
  2365. $BE_USER->user = $user;
  2366. $BE_USER->backendSetUC();
  2367. $BE_USER->uc['frontend_editing'] = 1;
  2368. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2369. $BE_USER->writeUC($BE_USER->uc);
  2370. }
  2371. }