SiteController.php 94 KB

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