SiteController.php 96 KB

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