SiteController.php 98 KB

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