SiteController.php 101 KB

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