SiteController.php 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  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\Random;
  21. use TYPO3\CMS\Core\Utility\GeneralUtility;
  22. use TYPO3\CMS\Extbase\Object\ObjectManager;
  23. /**
  24. * The SiteController implements some admin-only operations
  25. * on Typo3 websites, like creation or update.
  26. */
  27. class SiteController extends ActionController
  28. {
  29. // Templates names
  30. const TEMPLATE_HOME = "OpenTalent.OtTemplating->home";
  31. const TEMPLATE_1COL = "OpenTalent.OtTemplating->1Col";
  32. const TEMPLATE_3COL = "OpenTalent.OtTemplating->home";
  33. const TEMPLATE_EVENTS = "OpenTalent.OtTemplating->events";
  34. const TEMPLATE_STRUCTURESEVENTS = "OpenTalent.OtTemplating->structuresEvents";
  35. const TEMPLATE_STRUCTURES = "OpenTalent.OtTemplating->structures";
  36. const TEMPLATE_CONTACT = "OpenTalent.OtTemplating->contact";
  37. const TEMPLATE_NEWS = "OpenTalent.OtTemplating->news";
  38. const TEMPLATE_MEMBERS = "OpenTalent.OtTemplating->members";
  39. const TEMPLATE_MEMBERSCA = "OpenTalent.OtTemplating->membersCa";
  40. const TEMPLATE_LEGAL = "OpenTalent.OtTemplating->legal";
  41. // Pages dokType values
  42. const DOK_PAGE = 1;
  43. const DOK_SHORTCUT = 4;
  44. const DOK_FOLDER = 116;
  45. // Contents CTypes
  46. const CTYPE_TEXT = 'text';
  47. const CTYPE_IMAGE = 'image';
  48. const CTYPE_TEXTPIC = 'textpic';
  49. const CTYPE_TEXTMEDIA = 'textmedia';
  50. const CTYPE_HTML = 'html';
  51. const CTYPE_HEADER = 'header';
  52. const CTYPE_UPLOADS = 'uploads';
  53. const CTYPE_LIST = 'list';
  54. const CTYPE_SITEMAP = 'menu_sitemap';
  55. // Default values
  56. const DEFAULT_THEME = 'Classic';
  57. const DEFAULT_COLOR = 'light-blue';
  58. // BE rights
  59. const BEGROUP_EDITOR_STANDARD = 10;
  60. const BEGROUP_EDITOR_PREMIUM = 20;
  61. const BEGROUP_ADMIN_STANDARD = 30;
  62. const BEGROUP_ADMIN_PREMIUM = 40;
  63. const BEGROUP_NAME = [
  64. self::BEGROUP_EDITOR_STANDARD => "Editor_Standard",
  65. self::BEGROUP_EDITOR_PREMIUM => "Editor_Premium",
  66. self::BEGROUP_ADMIN_STANDARD => "Admin_Standard",
  67. self::BEGROUP_ADMIN_PREMIUM => "Admin_Premium"
  68. ];
  69. const IS_PRODUCT_PREMIUM = [
  70. "school-standard" => false,
  71. "artist-standard" => false,
  72. "school-premium" => true,
  73. "artist-premium" => true,
  74. "manager" => true,
  75. ];
  76. // access permissions
  77. const PERM_SHOW = 1;
  78. const PERM_EDIT_CONTENT = 16;
  79. const PERM_EDIT_PAGE = 2;
  80. const PERM_DELETE = 4;
  81. const PERM_NEW = 8;
  82. // Creation mode
  83. const MODE_PROD = 1;
  84. const MODE_DEV = 1;
  85. // Domain name validation
  86. 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}))*\/?/";
  87. // Redirections creation status
  88. const REDIRECTION_UNKNOWN_STATUS = 0;
  89. const REDIRECTION_UPDATED = 1;
  90. const REDIRECTION_CREATED = 2;
  91. /**
  92. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  93. */
  94. private \TYPO3\CMS\Core\Database\ConnectionPool $connectionPool;
  95. public function injectConnectionPool(\TYPO3\CMS\Core\Database\ConnectionPool $connectionPool)
  96. {
  97. $this->connectionPool = $connectionPool;
  98. }
  99. /**
  100. * @var \TYPO3\CMS\Core\Cache\CacheManager
  101. */
  102. private \TYPO3\CMS\Core\Cache\CacheManager $cacheManager;
  103. public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager $cacheManager)
  104. {
  105. $this->cacheManager = $cacheManager;
  106. }
  107. /**
  108. * @var OtWebsiteRepository
  109. */
  110. protected OtWebsiteRepository $otWebsiteRepository;
  111. public function injectOtWebsiteRepository(OtWebsiteRepository $otWebsiteRepository) {
  112. $this->otWebsiteRepository = $otWebsiteRepository;
  113. }
  114. /**
  115. * Index of the pages created during the process
  116. * >> [slug => uid]
  117. * @var array
  118. */
  119. private array $createdPagesIndex;
  120. /**
  121. * List of the directories created in the process (for rollback purposes)
  122. * @var array
  123. */
  124. private array $createdDirs;
  125. /**
  126. * List of the files created in the process (for rollback purposes)
  127. * @var array
  128. */
  129. private array $createdFiles;
  130. public function __construct()
  131. {
  132. parent::__construct();
  133. $this->createdPagesIndex = [];
  134. $this->createdDirs = [];
  135. $this->createdFiles = [];
  136. }
  137. /**
  138. * Return the SiteInfos object for the organization's website
  139. *
  140. * @param int $organizationId
  141. * @return SiteInfos
  142. * @throws NoSuchWebsiteException
  143. */
  144. public function getSiteInfosAction(int $organizationId): SiteInfos
  145. {
  146. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  147. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  148. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  149. $rootPage = $this->otPageRepository->getPage($rootUid);
  150. $site = new SiteInfos(
  151. $rootUid,
  152. $website['organization_name'],
  153. $this->otWebsiteRepository->resolveWebsiteDomain($website),
  154. $website['template'],
  155. $website['template_preferences'],
  156. $website['matomo_id'],
  157. self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']] ?? false,
  158. (bool)$rootPage['deleted'],
  159. ($rootPage['hidden'] || $rootPage['fe_group'] < 0),
  160. null,
  161. null,
  162. $rootPage['perms_userid'],
  163. $rootPage['perms_groupid']
  164. );
  165. // Owners
  166. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  167. $queryBuilder->getRestrictions()->removeAll();
  168. $beUsers = $queryBuilder
  169. ->select('uid', 'username')
  170. ->from('be_users')
  171. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  172. ->execute()
  173. ->fetchAll();
  174. foreach ($beUsers as $beUser) {
  175. $site->addMountedForBeUser($beUser);
  176. }
  177. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  178. $queryBuilder->getRestrictions()->removeAll();
  179. $beGroups = $queryBuilder
  180. ->select('uid', 'title')
  181. ->from('be_groups')
  182. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  183. ->execute()
  184. ->fetchAll();
  185. foreach ($beGroups as $beGroup) {
  186. $site->addMountedForBeGroups($beGroup);
  187. }
  188. return $site;
  189. }
  190. /**
  191. * Creates a new website for the given organization, and
  192. * returns the root page uid of the newly created site
  193. *
  194. * @param int $organizationId
  195. * @param int $mode Can be either MODE_PROD or MODE_DEV, MODE_PROD being the normal behaviour.
  196. * If MODE_DEV is used, sites urls will be of the form 'http://host/subdomain'
  197. * instead of 'http://subdomain/host'
  198. * @return int Uid of the root page of the newly created website
  199. * @throws \RuntimeException|\Throwable
  200. */
  201. public function createSiteAction(int $organizationId, int $mode=self::MODE_PROD): int
  202. {
  203. $organization = $this->fetchOrganization($organizationId);
  204. // This extra-data can not be retrieved from the API for now, but
  205. // this shall be set up as soon as possible, to avoid requesting
  206. // the prod-back DB directly.
  207. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  208. $isNetwork = $organizationExtraData['category'] == 'NETWORK';
  209. // Is there already a website with this organization's id?
  210. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  211. $queryBuilder->getRestrictions()->removeAll();
  212. $statement = $queryBuilder
  213. ->select('uid')
  214. ->from('ot_websites')
  215. ->where($queryBuilder->expr()->eq('organization_id', $queryBuilder->createNamedParameter($organization->getId())))
  216. ->execute();
  217. if ($statement->rowCount() > 0) {
  218. 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)");
  219. }
  220. // ** Create the new website
  221. // start transactions
  222. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  223. // keep tracks of the created folders and files to be able to remove them during a rollback
  224. try {
  225. // Create the website:
  226. $websiteUid = $this->insertOtWebsite($organization);
  227. // Create the site pages:
  228. // > Root page
  229. $rootUid = $this->insertRootPage(
  230. $websiteUid,
  231. $organization->getName()
  232. );
  233. // > 'Accueil' shortcut
  234. $this->insertPage(
  235. $websiteUid,
  236. $rootUid,
  237. 'Accueil',
  238. '/accueil',
  239. '',
  240. [
  241. 'dokType' => self::DOK_SHORTCUT,
  242. 'shortcut' => $rootUid
  243. ]
  244. );
  245. // > 'Présentation' page
  246. $this->insertPage(
  247. $websiteUid,
  248. $rootUid,
  249. 'Présentation',
  250. '/presentation'
  251. );
  252. // > 'Présentation > Qui sommes nous?' page (hidden by default)
  253. $this->insertPage(
  254. $websiteUid,
  255. $this->createdPagesIndex['/presentation'],
  256. 'Qui sommes nous?',
  257. '/qui-sommes-nous',
  258. '',
  259. ['hidden' => 1]
  260. );
  261. // > 'Présentation > Les adhérents' page
  262. $this->insertPage(
  263. $websiteUid,
  264. $this->createdPagesIndex['/presentation'],
  265. 'Les adhérents',
  266. '/les-adherents',
  267. self::TEMPLATE_MEMBERS
  268. );
  269. // > 'Présentation > Les membres du CA' page
  270. $this->insertPage(
  271. $websiteUid,
  272. $this->createdPagesIndex['/presentation'],
  273. 'Les membres du CA',
  274. '/les-membres-du-ca',
  275. self::TEMPLATE_MEMBERSCA
  276. );
  277. if ($isNetwork) {
  278. // > 'Présentation > Les sociétés adhérentes' page
  279. $this->insertPage(
  280. $websiteUid,
  281. $this->createdPagesIndex['/presentation'],
  282. 'Les sociétés adhérentes',
  283. '/societes-adherentes',
  284. self::TEMPLATE_STRUCTURES
  285. );
  286. }
  287. // > 'Présentation > Historique' page (hidden by default)
  288. $this->insertPage(
  289. $websiteUid,
  290. $this->createdPagesIndex['/presentation'],
  291. 'Historique',
  292. '/historique',
  293. '',
  294. ['hidden' => 1]
  295. );
  296. // ~ Contact shortcut will be created after the contact page
  297. // > 'Actualités' page (hidden by default)
  298. $this->insertPage(
  299. $websiteUid,
  300. $rootUid,
  301. 'Actualités',
  302. '/actualites',
  303. self::TEMPLATE_NEWS,
  304. ['hidden' => 1]
  305. );
  306. // > 'Saison en cours' page
  307. $this->insertPage(
  308. $websiteUid,
  309. $rootUid,
  310. 'Saison en cours',
  311. '/saison-en-cours'
  312. );
  313. // > 'Saison en cours > Les évènements' page
  314. $this->insertPage(
  315. $websiteUid,
  316. $this->createdPagesIndex['/saison-en-cours'],
  317. 'Les évènements',
  318. '/les-evenements',
  319. self::TEMPLATE_EVENTS
  320. );
  321. if ($isNetwork) {
  322. // > 'Présentation > Les sociétés adhérentes' page
  323. $this->insertPage(
  324. $websiteUid,
  325. $this->createdPagesIndex['/presentation'],
  326. 'Évènements des structures',
  327. '/evenements-des-structures',
  328. self::TEMPLATE_STRUCTURESEVENTS
  329. );
  330. }
  331. // > 'Vie interne' page (restricted, hidden by default)
  332. $this->insertPage(
  333. $websiteUid,
  334. $rootUid,
  335. 'Vie interne',
  336. '/vie-interne',
  337. '',
  338. [
  339. 'hidden' => 1,
  340. 'fe_group' => -2
  341. ]
  342. );
  343. // > 'Footer' page (not in the menu)
  344. $this->insertPage(
  345. $websiteUid,
  346. $rootUid,
  347. 'Footer',
  348. '/footer',
  349. '',
  350. [
  351. 'dokType' => self::DOK_FOLDER,
  352. 'nav_hide' => 1
  353. ]
  354. );
  355. // > 'Footer > Contact' page
  356. $this->insertPage(
  357. $websiteUid,
  358. $this->createdPagesIndex['/footer'],
  359. 'Contact',
  360. '/contact',
  361. self::TEMPLATE_CONTACT
  362. );
  363. // > 'Footer > Plan du site' page
  364. $this->insertPage(
  365. $websiteUid,
  366. $this->createdPagesIndex['/footer'],
  367. 'Plan du site',
  368. '/plan-du-site'
  369. );
  370. // > 'Footer > Mentions légales' page
  371. $this->insertPage(
  372. $websiteUid,
  373. $this->createdPagesIndex['/footer'],
  374. 'Mentions légales',
  375. '/mentions-legales',
  376. self::TEMPLATE_LEGAL
  377. );
  378. // > 'Présentation > Contact' shortcut
  379. $this->insertPage(
  380. $websiteUid,
  381. $this->createdPagesIndex['/presentation'],
  382. 'Contact',
  383. '/ecrivez-nous',
  384. '',
  385. [
  386. 'dokType' => self::DOK_SHORTCUT,
  387. 'shortcut' => $this->createdPagesIndex['/contact']
  388. ]
  389. );
  390. // > 'Page introuvable' page (not in the menu, read-only)
  391. $this->insertPage(
  392. $websiteUid,
  393. $rootUid,
  394. 'Page introuvable',
  395. '/page-introuvable',
  396. '',
  397. [
  398. 'nav_hide' => 1,
  399. 'no_search' => 1
  400. ]
  401. );
  402. // Add content to these pages
  403. // >> root page content
  404. $this->insertContent(
  405. $rootUid,
  406. self::CTYPE_TEXTPIC,
  407. '<h1>Bienvenue sur le site de ' . $organization->getName() . '.</h1>',
  408. 0
  409. );
  410. // >> page 'qui sommes nous?'
  411. $this->insertContent(
  412. $this->createdPagesIndex['/qui-sommes-nous'],
  413. self::CTYPE_TEXT,
  414. 'Qui sommes nous ...',
  415. 0
  416. );
  417. // >> page 'historique'
  418. $this->insertContent(
  419. $this->createdPagesIndex['/historique'],
  420. self::CTYPE_TEXT,
  421. "Un peu d'histoire ...",
  422. 0
  423. );
  424. // >> page 'plan du site'
  425. $this->insertContent(
  426. $this->createdPagesIndex['/plan-du-site'],
  427. self::CTYPE_SITEMAP
  428. );
  429. // update sys_template
  430. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  431. $include = "EXT:fluid_styled_content/Configuration/TypoScript/";
  432. $include .= ",EXT:fluid_styled_content/Configuration/TypoScript/Styling/";
  433. $include .= ",EXT:form/Configuration/TypoScript/";
  434. $include .= ",EXT:news/Configuration/TypoScript";
  435. $include .= ",EXT:frontend_editing/Configuration/TypoScript";
  436. $include .= ",EXT:frontend_editing/Configuration/TypoScript/FluidStyledContent9";
  437. $include .= ",EXT:ot_templating/Configuration/TypoScript";
  438. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  439. $queryBuilder->insert('sys_template')
  440. ->values([
  441. 'pid' => $rootUid,
  442. 'title' => $organization->getName(),
  443. 'sitetitle' => $organization->getName(),
  444. 'root' => 1,
  445. 'clear' => 3,
  446. 'config' => "config.frontend_editing = 1",
  447. 'include_static_file' => $include,
  448. 'constants' => $constants
  449. ])
  450. ->execute();
  451. // ## Create the site config.yaml file
  452. $identifier = $this->writeConfigFile(
  453. $rootUid,
  454. true
  455. );
  456. // Update the ot_website identifier
  457. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  458. $queryBuilder->update('ot_websites')
  459. ->set('config_identifier', $identifier)
  460. ->where($queryBuilder->expr()->eq('uid', $websiteUid))
  461. ->execute();
  462. // Create the user_upload and form_definitions directories and update the sys_filemounts table
  463. $uploadRelPath = "/user_upload/" . $organizationId;
  464. $fileadminDir = $_ENV['TYPO3_PATH_APP'] . "/public/fileadmin";
  465. $uploadDir = $fileadminDir . "/" . $uploadRelPath;
  466. if (file_exists($uploadDir)) {
  467. throw new \RuntimeException("A directory or file " . $uploadDir . " already exists. Abort.");
  468. }
  469. $formsRelPath = '/form_definitions/' . $organizationId;
  470. $formsDir = $fileadminDir . $formsRelPath;
  471. if (file_exists($formsDir)) {
  472. throw new \RuntimeException("A directory or file " . $formsDir . " already exists. Abort.");
  473. }
  474. $this->mkDir($uploadDir);
  475. $this->mkDir($formsDir);
  476. // Insert the filemounts points (sys_filemounts)
  477. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  478. $queryBuilder->insert('sys_filemounts')
  479. ->values([
  480. 'title' => 'Documents',
  481. 'path' => rtrim($uploadRelPath, '/') . '/',
  482. 'base' => 1
  483. ])
  484. ->execute();
  485. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  486. $queryBuilder->insert('sys_filemounts')
  487. ->values([
  488. 'title' => 'Forms_' . $organizationId,
  489. 'path' => rtrim($formsRelPath, '/') . '/',
  490. 'base' => 1
  491. ])
  492. ->execute();
  493. // Create the BE Editors group
  494. // -- NB: this user will then be auto-updated by the ot_connect extension --
  495. $beGroupUid = $this->createOrUpdateBeGroup(
  496. $organizationId,
  497. $rootUid,
  498. $organizationExtraData['admin']
  499. );
  500. // Create the BE User
  501. // -- NB: this user will then be auto-updated by the ot_connect extension --
  502. $beUserUid = $this->createOrUpdateBeUser(
  503. $organizationId,
  504. $rootUid,
  505. $beGroupUid,
  506. $organizationExtraData['admin']
  507. );
  508. // Update the user TsConfig
  509. $tsconfig = "options.uploadFieldsInTopOfEB = 1\n" .
  510. "options.defaultUploadFolder=1:" . rtrim($uploadRelPath, '/') . "/\n";
  511. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  512. $queryBuilder
  513. ->update('be_users')
  514. ->where($queryBuilder->expr()->eq('uid', $beUserUid))
  515. ->set('TSconfig', $tsconfig)
  516. ->execute();
  517. // Setup user and group rights
  518. $this->setBeUserPerms($organizationId, false, $beGroupUid, $beUserUid);
  519. // Try to commit the result
  520. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  521. if (!$commitSuccess) {
  522. throw new \RuntimeException('Something went wrong while committing the result');
  523. }
  524. } catch(\Throwable $e) {
  525. // rollback
  526. $this->connectionPool->getConnectionByName('Default')->rollback();
  527. // remove created files and dirs
  528. foreach (array_reverse($this->createdFiles) as $filename) {
  529. unlink($filename);
  530. }
  531. $this->createdFiles = [];
  532. foreach (array_reverse($this->createdDirs) as $dirname) {
  533. rmdir($dirname);
  534. }
  535. $this->createdDirs = [];
  536. throw $e;
  537. }
  538. // Extra steps that do not need any rollback:
  539. $this->enableFeEditing($beUserUid);
  540. return $rootUid;
  541. }
  542. /**
  543. * Performs an update of the organization's website based on data fetched from the opentalent DB:
  544. *
  545. * - Update the pages table (structure id, structure domain)
  546. * - (hard update only) Update the config.yaml file
  547. * - Update the `sys_template`.`constants` and the `pages`.`TSConfig` fields
  548. * - (hard update only) Reset the users permissions
  549. * - Clear the Typo3 cache for the website
  550. *
  551. * @param int $organizationId
  552. * @return int
  553. * @throws NoSuchOrganizationException
  554. * @throws NoSuchRecordException
  555. * @throws NoSuchWebsiteException
  556. * @throws \Doctrine\DBAL\ConnectionException
  557. * @throws \Doctrine\DBAL\DBALException
  558. * @throws \Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException
  559. * @throws \Throwable
  560. */
  561. public function updateSiteAction(int $organizationId): int
  562. {
  563. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  564. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  565. $organization = $this->fetchOrganization($organizationId);
  566. // This extra-data can not be retrieved from the API for now, but
  567. // this shall be set up as soon as possible, to avoid requesting
  568. // the prod-back DB directly.
  569. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  570. // start transactions
  571. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  572. // keep tracks of the created folders and files to be able to remove them during a rollback
  573. try {
  574. // ## Update the ot_website table
  575. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  576. $queryBuilder->update('ot_websites')
  577. ->set('subdomain', $organization->getSubDomain())
  578. ->set('organization_name', $organization->getName())
  579. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  580. ->execute();
  581. // ## Update the subpages of the rootpage
  582. $sitePages = $this->otPageRepository->getAllSubpagesForPage($rootUid);
  583. foreach ($sitePages as $page) {
  584. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  585. $queryBuilder->update('pages')
  586. ->set('ot_website_uid', $website['uid'])
  587. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  588. ->execute();
  589. }
  590. // ## Update the `sys_template`.`constants` and the `pages`.`TSConfig` fields
  591. $constants = $this->getTemplateConstants($organizationId, $organizationExtraData);
  592. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_template');
  593. $queryBuilder
  594. ->update('sys_template')
  595. ->set('constants', $constants)
  596. ->where($queryBuilder->expr()->eq('pid', $rootUid))
  597. ->execute();
  598. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  599. $queryBuilder
  600. ->update('pages')
  601. ->set('TSconfig', 'TCAdefaults.pages.ot_website_uid=' . $website['uid'])
  602. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  603. ->execute();
  604. // ## Update the config.yaml file
  605. $identifier = $this->otWebsiteRepository->findConfigIdentifierFor($rootUid);
  606. $this->writeConfigFile($rootUid, true, $identifier);
  607. // ## Update the ot_website identifier
  608. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  609. $queryBuilder->update('ot_websites')
  610. ->set('config_identifier', $identifier)
  611. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  612. ->execute();
  613. // Try to commit the result
  614. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  615. if (!$commitSuccess) {
  616. throw new \RuntimeException('Something went wrong while committing the result');
  617. }
  618. } catch(\Throwable $e) {
  619. // rollback
  620. $this->connectionPool->getConnectionByName('Default')->rollback();
  621. throw $e;
  622. }
  623. // ## Clear the Typo3 cache for the website
  624. OtCacheManager::clearSiteCache($rootUid, true);
  625. return $rootUid;
  626. }
  627. /**
  628. * Delete the website with all its pages, contents and related records
  629. *
  630. * If the hard parameter is false, the records' `deleted` field will be set to true and
  631. * the files and directories will be renamed. This kind of 'soft' deletion can be undone.
  632. *
  633. * Otherwise, if hard is set to true, the records and files will be permanently removed,
  634. * with no possibility of undoing anything. In this case, you'll have to confirm your intention
  635. * by creating a file in the Typo3 root directory, named 'DEL####' (#### is the organization id)
  636. *
  637. * $redirectTo is the optional organization id to whom requests will be redirected
  638. *
  639. * The $force parameter, if true, will both bypass the 'DEL###' file confirmation and recursively delete the
  640. * user_upload and form_definitions of the website. <!> USE WITH CAUTION
  641. *
  642. * @param int $organizationId
  643. * @param bool $hard
  644. * @param int|null $redirectTo
  645. * @param bool $force
  646. * @return int
  647. * @throws NoSuchRecordException
  648. * @throws NoSuchWebsiteException
  649. * @throws \Doctrine\DBAL\DBALException
  650. * @throws \Throwable
  651. */
  652. public function deleteSiteAction(int $organizationId, bool $hard=false, ?int $redirectTo=null, bool $force = false): int
  653. {
  654. $website = $this->otWebsiteRepository->getWebsiteByOrganizationId($organizationId);
  655. $websiteUid = $website['uid'];
  656. $rootUid = $this->otWebsiteRepository->getWebsiteRootUid($website['uid']);
  657. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  658. $isDeleted = $queryBuilder
  659. ->select('deleted')
  660. ->from('ot_websites')
  661. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  662. ->execute()
  663. ->fetchColumn(0) == 1;
  664. $confirm_file = $_ENV['TYPO3_PATH_APP'] . "/DEL" . $organizationId;
  665. if ($hard && !file_exists($confirm_file) && !$force) {
  666. throw new \RuntimeException(
  667. "You are going to completely delete the website with root uid " . $rootUid .
  668. ", and all of its pages, files, contents...etc. If you are sure, create a file named '" .
  669. $confirm_file . "', and launch this command again."
  670. );
  671. }
  672. // Prepare the redirection
  673. if ($redirectTo) {
  674. if ($redirectTo == $organizationId) {
  675. throw new \InvalidArgumentException('redirectTo value has to be different from the organizationId');
  676. }
  677. $originDomain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  678. $targetOrganizationWebsite = $this->otWebsiteRepository->getWebsiteByOrganizationId($redirectTo);
  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 ($redirectTo) {
  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->getSiteInfosAction($organizationId)->getBaseUrl();
  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. return $rootUid;
  1196. }
  1197. /**
  1198. * Return all of the redirections from the given domain name,
  1199. * even if they have been marked as deleted.
  1200. *
  1201. * @param $domain string Domain name, without the http(s):// part
  1202. * @return array Rows from the sys_redirect table
  1203. */
  1204. protected function getRedirectionsFrom(string $domain): array
  1205. {
  1206. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1207. $queryBuilder->getRestrictions()->removeAll();
  1208. return $queryBuilder
  1209. ->select('*')
  1210. ->from('sys_redirect')
  1211. ->where($queryBuilder->expr()->eq('source_host', $queryBuilder->expr()->literal($domain)))
  1212. ->execute()
  1213. ->fetchAll();
  1214. }
  1215. /**
  1216. * Return all of the redirections to the given domain name,
  1217. * even if they have been marked as deleted.
  1218. *
  1219. * @param $domain string Domain name, without the http(s):// part
  1220. * @return array Rows from the sys_redirect table
  1221. */
  1222. protected function getRedirectionsTo(string $domain): array
  1223. {
  1224. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1225. $queryBuilder->getRestrictions()->removeAll();
  1226. return $queryBuilder
  1227. ->select('*')
  1228. ->from('sys_redirect')
  1229. ->where(
  1230. $queryBuilder->expr()->in(
  1231. 'target',
  1232. [
  1233. 'http://' . $queryBuilder->expr()->literal($domain),
  1234. 'https://' . $queryBuilder->expr()->literal($domain)
  1235. ]
  1236. )
  1237. )
  1238. ->execute()
  1239. ->fetchAll();
  1240. }
  1241. /**
  1242. * Add a new redirection from $fromDomain to $toDomain.
  1243. * If this redirection already exists but has been deleted and/or disabled, it will be restored and enabled
  1244. * If a redirection already exists but is not deleted and targets another domain, a RuntimeException will be thrown.
  1245. *
  1246. * @param $fromDomain
  1247. * @param $toDomain
  1248. * @return int Status of the operation
  1249. */
  1250. public function addRedirection($fromDomain, $toDomain): int
  1251. {
  1252. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1253. $toDomain = preg_replace('/https?:\/\//', '', $toDomain);
  1254. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1255. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1256. }
  1257. if (!preg_match(self::RX_DOMAIN, $toDomain)) {
  1258. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $toDomain);
  1259. }
  1260. $existing = $this->getRedirectionsFrom($fromDomain);
  1261. $toUpdate = null;
  1262. foreach ($existing as $redirection) {
  1263. if (!$redirection['deleted'] && !$redirection['disabled']) {
  1264. // a redirection from this domain already exists, and it is not deleted nor disabled
  1265. if (!preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1266. // the target is not the same domain
  1267. throw new \RuntimeException(
  1268. 'A redirection is already active for ' . $fromDomain . ' targeting ' . $redirection['target']
  1269. );
  1270. } else {
  1271. // else, target is already the same domain, it will be updated
  1272. $toUpdate = $redirection;
  1273. break;
  1274. }
  1275. } else {
  1276. // a redirection from this domain already exists, but it is deleted or disabled
  1277. if (preg_match('/https?:\/\/' . $toDomain . '/', $redirection['target'])) {
  1278. // the target is the same domain, we'll reactivate this record
  1279. $toUpdate = $redirection;
  1280. break;
  1281. }
  1282. }
  1283. }
  1284. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_redirect');
  1285. $data = [
  1286. 'deleted' => 0,
  1287. 'disabled' => 0,
  1288. 'source_host' => $fromDomain,
  1289. 'source_path' => '/.*/',
  1290. 'is_regexp' => 1,
  1291. 'force_https' => 0,
  1292. 'respect_query_parameters' => 0,
  1293. 'keep_query_parameters' => 1,
  1294. 'target' => 'https://' . $toDomain,
  1295. 'target_statuscode' => 301
  1296. ];
  1297. if ($toUpdate !== null) {
  1298. $q = $queryBuilder
  1299. ->update('sys_redirect')
  1300. ->where($queryBuilder->expr()->eq('uid', $toUpdate['uid']));
  1301. foreach ($data as $k => $v) {
  1302. $q->set($k, $v);
  1303. }
  1304. $q->execute();
  1305. return self::REDIRECTION_UPDATED;
  1306. } else {
  1307. $queryBuilder
  1308. ->insert('sys_redirect')
  1309. ->values($data)
  1310. ->execute();
  1311. return self::REDIRECTION_CREATED;
  1312. }
  1313. }
  1314. /**
  1315. * Remove any existing redirection from $fromDomain to any url by marking it as deleted.
  1316. * If $hard is true, delete it completely.
  1317. *
  1318. * @param $fromDomain
  1319. * @param bool $hard
  1320. * @return int Number of affected rows
  1321. */
  1322. public function removeRedirectionsFrom($fromDomain, $hard=false): int
  1323. {
  1324. $fromDomain = preg_replace('/https?:\/\//', '', $fromDomain);
  1325. if (!preg_match(self::RX_DOMAIN, $fromDomain)) {
  1326. throw new \InvalidArgumentException("The does not seems to be a valid domain: " . $fromDomain);
  1327. }
  1328. $existing = $this->getRedirectionsFrom($fromDomain);
  1329. $deleted = 0;
  1330. foreach ($existing as $redirection) {
  1331. $this->delete('sys_redirect', 'uid', $redirection['uid'], $hard);
  1332. $deleted += 1;
  1333. }
  1334. return $deleted;
  1335. }
  1336. /**
  1337. * Set the rights of admin and editors of the website
  1338. * on all of the existing pages, including deleted ones
  1339. *
  1340. * @param int $organizationId
  1341. * @param bool $createIfMissing Create the admin be user and/or the editors group if they are not found in the DB
  1342. * @param int|null $editorsGroupUid Force the editors be-group uid
  1343. * @param int|null $adminUid Force the admin be-user uid
  1344. * @return int The uid of the website root page
  1345. * @throws NoSuchWebsiteException
  1346. * @throws NoSuchRecordException
  1347. */
  1348. protected function setBeUserPerms(
  1349. int $organizationId,
  1350. bool $createIfMissing = false,
  1351. int $editorsGroupUid = null,
  1352. int $adminUid = null
  1353. ): int
  1354. {
  1355. if ($createIfMissing && ($editorsGroupUid || $adminUid)) {
  1356. throw new \InvalidArgumentException("You can not set $createIfMissing to true " .
  1357. "and force the admin or group uid at the same time.");
  1358. }
  1359. $rootUid = $this->otWebsiteRepository->findRootUidForOrganization($organizationId);
  1360. $organizationExtraData = $this->fetchOrganizationExtraData($organizationId);
  1361. $isPremium = self::IS_PRODUCT_PREMIUM[$organizationExtraData['admin']['product']];
  1362. if ($editorsGroupUid == null) {
  1363. try {
  1364. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  1365. } catch (NoSuchRecordException $e) {
  1366. if (!$createIfMissing) {
  1367. throw $e;
  1368. }
  1369. }
  1370. }
  1371. if ($adminUid == null) {
  1372. try {
  1373. $adminUid = $this->findAdminBeUserUid($rootUid);
  1374. } catch (NoSuchRecordException $e) {
  1375. if (!$createIfMissing) {
  1376. throw $e;
  1377. }
  1378. }
  1379. }
  1380. // Creates or update the admin be_group
  1381. $editorsGroupUid = $this->createOrUpdateBeGroup(
  1382. $organizationId,
  1383. $rootUid,
  1384. $organizationExtraData['admin'],
  1385. $editorsGroupUid
  1386. );
  1387. // Creates or update the admin be_user
  1388. $adminUid = $this->createOrUpdateBeUser(
  1389. $organizationId,
  1390. $rootUid,
  1391. $editorsGroupUid,
  1392. $organizationExtraData['admin'],
  1393. $adminUid
  1394. );
  1395. // Reset the appartenance to groups
  1396. $adminGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD);
  1397. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1398. $queryBuilder
  1399. ->update('be_users')
  1400. ->where($queryBuilder->expr()->eq('uid', $adminUid))
  1401. ->set('usergroup', $adminGroupUid . ',' . $editorsGroupUid)
  1402. ->execute();
  1403. $mainEditorGroupUid = $this->getBaseBeGroupUid($isPremium ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD);
  1404. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  1405. $queryBuilder
  1406. ->update('be_groups')
  1407. ->where($queryBuilder->expr()->eq('uid', $editorsGroupUid))
  1408. ->set('subgroup', $mainEditorGroupUid)
  1409. ->execute();
  1410. // setup default owner for the website
  1411. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1412. $tsConfig = $queryBuilder->select('TSconfig')
  1413. ->from('pages')
  1414. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1415. ->execute()
  1416. ->fetchColumn(0);
  1417. $tsConfig = trim(preg_replace('/TCEMAIN {[^{]*}/', '', $tsConfig));
  1418. $tsConfig .= "\nTCEMAIN {\n" .
  1419. " permissions.userid = " . $adminUid ."\n" .
  1420. " permissions.groupid = " . $editorsGroupUid . "\n" .
  1421. "}";
  1422. $queryBuilder
  1423. ->update('pages')
  1424. ->where($queryBuilder->expr()->eq('uid', $rootUid))
  1425. ->set('TSconfig', $tsConfig)
  1426. ->execute();
  1427. // fetch pages and root page
  1428. $pages = $this->otPageRepository->getPageWithSubpages($rootUid);
  1429. // To understand how the rights levels are computed:
  1430. // @see https://ressources.opentalent.fr/display/EX/Droits+des+BE+Users
  1431. foreach ($pages as $page) {
  1432. if ($page['is_siteroot']) {
  1433. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1434. if ($isPremium) {
  1435. $adminPerms += self::PERM_NEW;
  1436. }
  1437. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT;
  1438. } else if (
  1439. $page['slug'] == '/footer' ||
  1440. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->legal' ||
  1441. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->contact' ||
  1442. $page['slug'] == '/plan-du-site'
  1443. ) {
  1444. $adminPerms = self::PERM_SHOW;
  1445. if ($isPremium) {
  1446. $adminPerms += self::PERM_NEW;
  1447. }
  1448. $editorsPerms = self::PERM_SHOW;
  1449. } else if (
  1450. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->members' ||
  1451. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->membersCa' ||
  1452. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structures' ||
  1453. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->events' ||
  1454. $page['tx_fed_page_controller_action'] == 'OpenTalent.OtTemplating->structuresEvents'
  1455. ) {
  1456. $adminPerms = self::PERM_SHOW;
  1457. if ($isPremium) {
  1458. $adminPerms += self::PERM_NEW + self::PERM_EDIT_PAGE;
  1459. }
  1460. $editorsPerms = self::PERM_SHOW;
  1461. } else {
  1462. $adminPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1463. if ($isPremium) {
  1464. $adminPerms += self::PERM_DELETE + self::PERM_NEW;
  1465. }
  1466. $editorsPerms = self::PERM_SHOW + self::PERM_EDIT_CONTENT + self::PERM_EDIT_PAGE;
  1467. if ($isPremium) {
  1468. $editorsPerms += self::PERM_NEW;
  1469. }
  1470. }
  1471. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1472. $queryBuilder
  1473. ->update('pages')
  1474. ->where($queryBuilder->expr()->eq('uid', $page['uid']))
  1475. ->set('perms_userid', $adminUid)
  1476. ->set('perms_groupid', $editorsGroupUid)
  1477. ->set('perms_user', $adminPerms)
  1478. ->set('perms_group', $editorsPerms)
  1479. ->set('perms_everybody', 0)
  1480. ->execute();
  1481. }
  1482. return $rootUid;
  1483. }
  1484. /**
  1485. * Action for resetting the rights of admin and editors of the website
  1486. * on all of the existing pages, including deleted ones
  1487. *
  1488. * @param int $organizationId
  1489. * @param bool $createIfMissing
  1490. * @return int
  1491. * @throws NoSuchRecordException
  1492. * @throws NoSuchWebsiteException
  1493. * @throws \Throwable
  1494. */
  1495. public function resetBeUserPermsAction(int $organizationId, bool $createIfMissing = false): int
  1496. {
  1497. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1498. try {
  1499. $rootUid = $this->setBeUserPerms($organizationId, $createIfMissing);
  1500. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1501. if (!$commitSuccess) {
  1502. throw new \RuntimeException('Something went wrong while commiting the result');
  1503. }
  1504. return $rootUid;
  1505. }
  1506. catch (\Throwable $e) {
  1507. // rollback
  1508. $this->connectionPool->getConnectionByName('Default')->rollback();
  1509. throw $e;
  1510. }
  1511. }
  1512. /**
  1513. * Delete then regenerate all of the typo3 sites yaml config files
  1514. *
  1515. * This is a more efficient alternative to the update --all, designed to be executed on a development environment
  1516. * just after the databases cloning.
  1517. *
  1518. * @throws NoSuchRecordException
  1519. * @throws NoSuchWebsiteException
  1520. * @throws \Doctrine\DBAL\ConnectionException
  1521. * @throws \Doctrine\DBAL\DBALException
  1522. * @throws \Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException
  1523. * @throws \Throwable
  1524. */
  1525. public function regenConfigFilesAction()
  1526. {
  1527. $configRootDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/";
  1528. $backupConfigDir = $_ENV['TYPO3_PATH_APP'] . "/config/bkp_sites";
  1529. if (file_exists($backupConfigDir)) {
  1530. throw new \RuntimeException('A directory or a file with this name already exist: ' . $backupConfigDir);
  1531. }
  1532. $this->connectionPool->getConnectionByName('Default')->beginTransaction();
  1533. try {
  1534. // archive the existing files, in case a rollback is needed
  1535. rename($configRootDir, $backupConfigDir);
  1536. $this->mkDir($configRootDir);
  1537. $websites = $this->otWebsiteRepository->getAll();
  1538. foreach ($websites as $website) {
  1539. $identifier = $website['subdomain'] . '_' . $website['organization_id'];
  1540. $configDir = $configRootDir . $identifier;
  1541. $configFilename = $configDir . "/config.yaml";
  1542. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  1543. $config = $siteConfig->getConfiguration();
  1544. $yamlConfig = Yaml::dump($config, 99, 2);
  1545. $this->mkDir($configDir);
  1546. $this->writeFile($configFilename, $yamlConfig);
  1547. // ## Update the ot_website identifier
  1548. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1549. $queryBuilder->update('ot_websites')
  1550. ->set('config_identifier', $identifier)
  1551. ->where($queryBuilder->expr()->eq('uid', $website['uid']))
  1552. ->execute();
  1553. }
  1554. $commitSuccess = $this->connectionPool->getConnectionByName('Default')->commit();
  1555. if (!$commitSuccess) {
  1556. throw new \RuntimeException('Something went wrong while committing the result');
  1557. }
  1558. $this->rrmdir($backupConfigDir);
  1559. }
  1560. catch (\Throwable $e) {
  1561. // rollback
  1562. $this->rrmdir($configRootDir);
  1563. rename($backupConfigDir, $configRootDir);
  1564. $this->connectionPool->getConnectionByName('Default')->rollback();
  1565. throw $e;
  1566. }
  1567. }
  1568. /**
  1569. * Retrieve the Organization object from the repository and then,
  1570. * from the Opentalent API
  1571. *
  1572. * @param $organizationId
  1573. * @return Organization
  1574. * @throws NoSuchOrganizationException
  1575. */
  1576. private function fetchOrganization($organizationId): Organization
  1577. {
  1578. $organizationRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OrganizationRepository::class);
  1579. try {
  1580. return $organizationRepository->findById($organizationId);
  1581. } catch (ApiRequestException $e) {
  1582. throw new NoSuchOrganizationException('Unable to fetch the organization with id: ' . $organizationId);
  1583. }
  1584. }
  1585. /**
  1586. * Insert a new row in the 'pages' table of the Typo3 DB
  1587. * and return its uid
  1588. *
  1589. * @param Organization $organization
  1590. * @return int
  1591. */
  1592. private function insertOtWebsite(Organization $organization): int
  1593. {
  1594. $values = [
  1595. 'organization_id' => $organization->getId(),
  1596. 'subdomain' => $organization->getSubDomain(),
  1597. 'locale' => 'fr_FR',
  1598. 'organization_name' => $organization->getName()
  1599. ];
  1600. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
  1601. $queryBuilder->insert('ot_websites')
  1602. ->values($values)
  1603. ->execute();
  1604. return (int)$queryBuilder->getConnection()->lastInsertId();
  1605. }
  1606. /**
  1607. * Determine which folder-type Typo3 page should contain the new website
  1608. * CREATES IT if needed, and return its uid
  1609. *
  1610. * @return int
  1611. */
  1612. private function getParentFolderUid(): int
  1613. {
  1614. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1615. $siteCount = $queryBuilder
  1616. ->count('uid')
  1617. ->from('pages')
  1618. ->where('is_siteroot=1')
  1619. ->execute()
  1620. ->fetchColumn(0);
  1621. $thousand = (int)(($siteCount + 1) / 1000);
  1622. $folderName = "Web Sites " . (1000 * $thousand) . " - " . ((1000 * $thousand) + 999);
  1623. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1624. $uid = $queryBuilder
  1625. ->select('uid')
  1626. ->from('pages')
  1627. ->where($queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($folderName)))
  1628. ->andWhere('dokType=254')
  1629. ->execute()
  1630. ->fetchColumn(0);
  1631. if ($uid == null) {
  1632. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1633. $queryBuilder->insert('pages')
  1634. ->values([
  1635. 'pid' => 0,
  1636. 'title' => $folderName,
  1637. 'dokType' => 254,
  1638. 'sorting' => 11264,
  1639. 'perms_userid' => 1,
  1640. 'perms_groupid' => 31,
  1641. 'perms_group' => 27,
  1642. ])
  1643. ->execute();
  1644. $uid = $queryBuilder->getConnection()->lastInsertId();
  1645. }
  1646. return $uid;
  1647. }
  1648. /**
  1649. * Insert a new row in the 'pages' table of the Typo3 DB
  1650. * and return its uid
  1651. *
  1652. * @param Organization $organization
  1653. * @param int $pid
  1654. * @param string $title
  1655. * @param string $slug
  1656. * @param string $template
  1657. * @param array $moreValues
  1658. * @return int
  1659. */
  1660. private function insertPage(int $website_uid,
  1661. int $pid,
  1662. string $title,
  1663. string $slug,
  1664. string $template = '',
  1665. array $moreValues = []
  1666. ): int
  1667. {
  1668. $defaultValues = [
  1669. 'pid' => $pid,
  1670. 'perms_groupid' => 3,
  1671. 'perms_user' => 27,
  1672. 'cruser_id' => 1,
  1673. 'dokType' => self::DOK_PAGE,
  1674. 'title' => $title,
  1675. 'slug' => $slug,
  1676. 'backend_layout' => 'flux__grid',
  1677. 'backend_layout_next_level' => 'flux__grid',
  1678. 'ot_website_uid' => $website_uid,
  1679. ];
  1680. if ($template) {
  1681. $defaultValues['tx_fed_page_controller_action'] = $template;
  1682. $defaultValues['tx_fed_page_controller_action_sub'] = self::TEMPLATE_1COL;
  1683. }
  1684. $values = array_merge($defaultValues, $moreValues);
  1685. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
  1686. $queryBuilder->insert('pages')
  1687. ->values($values)
  1688. ->execute();
  1689. $uid = (int)$queryBuilder->getConnection()->lastInsertId();
  1690. $this->createdPagesIndex[$slug] = $uid;
  1691. return $uid;
  1692. }
  1693. /**
  1694. * Insert the root page of a new organization's website
  1695. * and return its uid
  1696. *
  1697. * @param int $website_uid
  1698. * @param string $title
  1699. * @return int
  1700. */
  1701. private function insertRootPage(int $website_uid, string $title): int
  1702. {
  1703. return $this->insertPage(
  1704. $website_uid,
  1705. $this->getParentFolderUid(),
  1706. $title,
  1707. '/',
  1708. self::TEMPLATE_HOME,
  1709. [
  1710. 'is_siteroot' => 1,
  1711. 'TSconfig' => 'TCAdefaults.pages.ot_website_uid=' . $website_uid
  1712. ]
  1713. );
  1714. }
  1715. /**
  1716. * Insert a new row in the 'tt_content' table of the Typo3 DB
  1717. *
  1718. * @param int $pid
  1719. * @param string $cType
  1720. * @param string $bodyText
  1721. * @param int $colPos
  1722. * @param array $moreValues
  1723. */
  1724. private function insertContent(int $pid,
  1725. string $cType=self::CTYPE_TEXT,
  1726. string $bodyText = '',
  1727. int $colPos=0,
  1728. array $moreValues = []) {
  1729. $defaultValues = [
  1730. 'pid' => $pid,
  1731. 'cruser_id' => 1,
  1732. 'CType' => $cType,
  1733. 'colPos' => $colPos,
  1734. 'bodyText' => $bodyText
  1735. ];
  1736. $values = array_merge($defaultValues, $moreValues);
  1737. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
  1738. $queryBuilder->insert('tt_content')
  1739. ->values($values)
  1740. ->execute();
  1741. }
  1742. private function fetchOrganizationExtraData(int $organizationId) {
  1743. $cnn = new PDO(
  1744. "mysql:host=prod-back;dbname=opentalent",
  1745. 'dbcloner',
  1746. 'wWZ4hYcrmHLW2mUK',
  1747. array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')
  1748. );
  1749. $cnn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1750. $stmt = $cnn->prepare(
  1751. "SELECT o.id, o.name, o.facebook, o.twitter, o.instagram,
  1752. o.category, o.logo_id, p.logoDonorsMove
  1753. FROM opentalent.Organization o INNER JOIN opentalent.Parameters p
  1754. ON o.parameters_id = p.id
  1755. WHERE o.id=" . $organizationId . ";"
  1756. );
  1757. $stmt->execute();
  1758. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1759. $data = $stmt->fetch();
  1760. $stmt = $cnn->prepare(
  1761. "SELECT c.email
  1762. FROM opentalent.ContactPoint c
  1763. INNER JOIN opentalent.organization_contactpoint o
  1764. ON o.contactPoint_id = c.id
  1765. WHERE c.contactType = 'PRINCIPAL'
  1766. AND o.organization_id = " . $organizationId . ";"
  1767. );
  1768. $stmt->execute();
  1769. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1770. $data['email'] = $stmt->fetch()['email'];
  1771. $stmt = $cnn->prepare(
  1772. "SELECT n.name, n.logo, n.url
  1773. FROM opentalent.Network n
  1774. INNER JOIN
  1775. (opentalent.NetworkOrganization l
  1776. INNER JOIN opentalent.Organization o
  1777. ON l.organization_id = o.id)
  1778. ON l.network_id = n.id
  1779. WHERE l.endDate is NULL
  1780. AND o.id=" . $organizationId . ";"
  1781. );
  1782. $stmt->execute();
  1783. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1784. $data['network'] = $stmt->fetch();
  1785. $stmt = $cnn->prepare(
  1786. "SELECT p.username, p.id as person_id, s.product
  1787. FROM opentalent.Person p
  1788. INNER JOIN opentalent.Access a ON p.id = a.person_id
  1789. INNER JOIN opentalent.Settings s on a.organization_id = s.organization_id
  1790. where a.organization_id=" . $organizationId . " AND a.adminAccess=1;"
  1791. );
  1792. $stmt->execute();
  1793. $stmt->setFetchMode(PDO::FETCH_ASSOC);
  1794. $data['admin'] = $stmt->fetch();
  1795. return $data;
  1796. }
  1797. /**
  1798. * Return the content of `sys_template`.`constants` of
  1799. * the website of the given organization
  1800. *
  1801. * @param int $organizationId
  1802. * @param array $organizationExtraData
  1803. * @return string
  1804. */
  1805. private function getTemplateConstants(int $organizationId, array $organizationExtraData): string
  1806. {
  1807. return "plugin.tx_ottemplating {\n" .
  1808. " settings {\n" .
  1809. " organization {\n" .
  1810. " id = " . $organizationId . "\n" .
  1811. " name = " . $organizationExtraData['name'] . "\n" .
  1812. " is_network = " . ($organizationExtraData['category'] == 'NETWORK' ? '1' : '0') . "\n" .
  1813. " email = " . $organizationExtraData['email'] . "\n" .
  1814. " logoid = " . $organizationExtraData['logo_id'] . "\n" .
  1815. " twitter = " . $organizationExtraData['twitter'] . "\n" .
  1816. " facebook = " . $organizationExtraData['facebook'] . "\n" .
  1817. " instagram = " . $organizationExtraData['instagram'] . "\n" .
  1818. " }\n" .
  1819. " network {\n" .
  1820. " logo = " . $organizationExtraData['network']['logo'] . "\n" .
  1821. " name = " . $organizationExtraData['network']['name'] . "\n" .
  1822. " url = " . $organizationExtraData['network']['url'] . "\n" .
  1823. " }\n" .
  1824. " }\n" .
  1825. "}";
  1826. }
  1827. /**
  1828. * Create the given directory, give its property to the www-data group and
  1829. * record it as a newly created dir (for an eventual rollback)
  1830. *
  1831. * @param string $dirPath
  1832. */
  1833. private function mkDir(string $dirPath) {
  1834. mkdir($dirPath);
  1835. $this->createdDirs[] = $dirPath;
  1836. chgrp($dirPath, 'www-data');
  1837. }
  1838. /**
  1839. * Write the given file with content, give its property to the www-data group and
  1840. * record it as a newly created file (for an eventual rollback)
  1841. *
  1842. * @param string $path
  1843. * @param string $content
  1844. */
  1845. private function writeFile(string $path, string $content) {
  1846. $f = fopen($path, "w");
  1847. try
  1848. {
  1849. fwrite($f, $content);
  1850. $this->createdFiles[] = $path;
  1851. chgrp($path, 'www-data');
  1852. } finally {
  1853. fclose($f);
  1854. }
  1855. }
  1856. /**
  1857. * Create or update the .../sites/.../config.yaml file of the given site
  1858. * Return the identifier of the created website
  1859. *
  1860. * @param int $rootUid
  1861. * @param bool $forceRecreate
  1862. * @param null $identifier
  1863. * @return string Identifier of the newly created configuration file
  1864. * @throws NoSuchWebsiteException
  1865. * @throws \Opentalent\OtCore\Exception\InvalidWebsiteConfigurationException
  1866. */
  1867. private function writeConfigFile(int $rootUid, bool $forceRecreate = false, $identifier = null): string
  1868. {
  1869. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  1870. $domain = $this->otWebsiteRepository->resolveWebsiteDomain($website);
  1871. try {
  1872. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid, $identifier);
  1873. } catch (\RuntimeException $e) {
  1874. // identifier might be obsolete
  1875. $existing = $this->otWebsiteRepository->findConfigFileAndContentFor($rootUid);
  1876. }
  1877. $configFilename = $existing[0];
  1878. $config = $existing[1];
  1879. if (!$configFilename) {
  1880. $identifier = $website['subdomain'] . '_' . $website['organization_id'];
  1881. $configDir = $_ENV['TYPO3_PATH_APP'] . "/config/sites/" . $identifier;
  1882. $configFilename = $configDir . "/config.yaml";
  1883. $isNew = true;
  1884. if (file_exists($configFilename)) {
  1885. throw new \RuntimeException("A file named " . $configFilename . " already exists. Abort.");
  1886. }
  1887. } else {
  1888. $configDir = dirname($configFilename);
  1889. if ($identifier == null) {
  1890. $identifier = basename($configDir);
  1891. }
  1892. $config['base'] = 'https://' . $domain;
  1893. $isNew = false;
  1894. }
  1895. if ($isNew || $forceRecreate) {
  1896. $siteConfig = $this->otWebsiteRepository->generateWebsiteConfiguration($website, $identifier);
  1897. $config = $siteConfig->getConfiguration();
  1898. }
  1899. $yamlConfig = Yaml::dump($config, 99, 2);
  1900. if (!file_exists($configDir)) {
  1901. $this->mkDir($configDir);
  1902. }
  1903. $this->writeFile($configFilename, $yamlConfig);
  1904. // Set the owner and mods, in case www-data is not the one who run this command
  1905. // @see https://www.php.net/manual/fr/function.stat.php
  1906. try {
  1907. $stats = stat($_ENV['TYPO3_PATH_APP'] . '/public/index.php');
  1908. chown($configFilename, $stats['4']);
  1909. chgrp($configFilename, $stats['5']);
  1910. chmod($configFilename, $stats['2']);
  1911. } catch (\Exception $e) {
  1912. }
  1913. // Flush cache:
  1914. try {
  1915. $cacheSystem = $this->cacheManager->getCache('cache_core');
  1916. $cacheSystem->remove('site-configuration');
  1917. $cacheSystem->remove('pseudo-sites');
  1918. } catch (NoSuchCacheException $e) {
  1919. }
  1920. return $identifier;
  1921. }
  1922. /**
  1923. * Recursively remove the target directory (! no rollback available)
  1924. */
  1925. private function rrmdir(string $dir) {
  1926. if (!is_dir($dir) || is_link($dir)) return unlink($dir);
  1927. foreach (scandir($dir) as $file) {
  1928. if ($file == '.' || $file == '..') continue;
  1929. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) {
  1930. chmod($dir . DIRECTORY_SEPARATOR . $file, 0777);
  1931. if (!$this->rrmdir($dir . DIRECTORY_SEPARATOR . $file)) return false;
  1932. };
  1933. }
  1934. return rmdir($dir);
  1935. }
  1936. /**
  1937. * Create the BE user for the website, then return its uid
  1938. * The user shall be already created in the Opentalent DB
  1939. *
  1940. * @param int $organizationId
  1941. * @param int $rootUid
  1942. * @param int $siteGroupUid
  1943. * @param array $userData
  1944. * @param int|null $updateUid If passed, this method will update this be user instead of creating a new one
  1945. * @return int The uid of the created be_user
  1946. */
  1947. private function createOrUpdateBeUser(int $organizationId,
  1948. int $rootUid,
  1949. int $siteGroupUid,
  1950. array $userData,
  1951. int $updateUid = null): int
  1952. {
  1953. if (!isset($userData['username'])) {
  1954. throw new \RuntimeException('Can not find any user with admin access in the Opentalent DB. Abort.');
  1955. }
  1956. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  1957. $randomStr = (new Random)->generateRandomHexString(20);
  1958. $adminGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_ADMIN_PREMIUM : self::BEGROUP_ADMIN_STANDARD;
  1959. $adminGroupUid = $this->getBaseBeGroupUid($adminGroup);
  1960. $values = [
  1961. 'username' => $userData['username'],
  1962. 'password' => $randomStr,
  1963. 'description' => '[Auto-generated] BE Admin for organization ' . $organizationId,
  1964. 'deleted' => 0,
  1965. 'lang' => 'fr',
  1966. 'usergroup' => $siteGroupUid . ',' . $adminGroupUid,
  1967. 'userMods' => null, // inherited from the base AdminGroup
  1968. 'db_mountpoints' => null, // inherited from the editors group
  1969. 'file_mountpoints' => null, // inherited from the editors group
  1970. 'options' => 3, // allow to inherit both db and file mountpoints from groups
  1971. 'tx_opentalent_opentalentId' => $userData['id'],
  1972. 'tx_opentalent_organizationId' => $organizationId,
  1973. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  1974. ];
  1975. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  1976. if ($updateUid != null) {
  1977. $q = $queryBuilder->update('be_users')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  1978. foreach ($values as $k => $v) {
  1979. $q->set($k, $v);
  1980. }
  1981. $q->execute();
  1982. return $updateUid;
  1983. } else {
  1984. $queryBuilder->insert('be_users')
  1985. ->values($values)
  1986. ->execute();
  1987. return (int)$queryBuilder->getConnection()->lastInsertId();
  1988. }
  1989. }
  1990. /**
  1991. * Create the BE editors group for the website, then return its uid
  1992. *
  1993. * @param int $organizationId
  1994. * @param int $rootUid
  1995. * @param array $userData
  1996. * @param int|null $updateUid If passed, this method will update this be group instead of creating a new one
  1997. * @return int The uid of the created be_group
  1998. */
  1999. private function createOrUpdateBeGroup(int $organizationId,
  2000. int $rootUid,
  2001. array $userData,
  2002. int $updateUid = null): int
  2003. {
  2004. $groupName = 'editors_' . $organizationId;
  2005. // get the existing filemounts
  2006. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_filemounts');
  2007. $queryBuilder
  2008. ->select('uid')
  2009. ->from('sys_filemounts')
  2010. ->where("path LIKE '%user_upload/" . $organizationId . "/'")
  2011. ->orWhere("path LIKE '%form_definitions/" . $organizationId . "/'");
  2012. $statement = $queryBuilder->execute();
  2013. $rows = $statement->fetchAll(3) ?: [];
  2014. $files = [];
  2015. foreach ($rows as $row) {
  2016. $files[] = $row[0];
  2017. }
  2018. $mainGroup = self::IS_PRODUCT_PREMIUM[$userData['product']] ? self::BEGROUP_EDITOR_PREMIUM : self::BEGROUP_EDITOR_STANDARD;
  2019. $mainGroupUid = $this->getBaseBeGroupUid($mainGroup);
  2020. $values = [
  2021. 'title' => $groupName,
  2022. 'deleted' => 0,
  2023. 'subgroup' => $mainGroupUid,
  2024. 'db_mountpoints' => $rootUid,
  2025. 'file_mountPoints' => join(',', $files),
  2026. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  2027. 'groupMods' => '', // inherited from the base EditorsGroup
  2028. 'pagetypes_select' => '', // inherited from the base EditorsGroup
  2029. 'tables_select' => '', // inherited from the base EditorsGroup
  2030. 'tables_modify' => '', // inherited from the base EditorsGroup
  2031. 'non_exclude_fields' => '', // inherited from the base EditorsGroup
  2032. ];
  2033. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2034. if ($updateUid !== null) {
  2035. $q = $queryBuilder->update('be_groups')->where($queryBuilder->expr()->eq('uid', $updateUid));;
  2036. foreach ($values as $k => $v) {
  2037. $q->set($k, $v);
  2038. }
  2039. $q->execute();
  2040. return $updateUid;
  2041. } else {
  2042. $queryBuilder->insert('be_groups')
  2043. ->values($values)
  2044. ->execute();
  2045. return $queryBuilder->getConnection()->lastInsertId();
  2046. }
  2047. }
  2048. /**
  2049. * Try to find and return the uid of the editors be_group
  2050. * for this website
  2051. *
  2052. * @param int $rootUid
  2053. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2054. * @return int
  2055. * @throws NoSuchRecordException
  2056. */
  2057. protected function findEditorsBeGroupUid(int $rootUid, bool $withRestrictions=true): int {
  2058. $editorsGroups = [
  2059. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_STANDARD),
  2060. $this->getBaseBeGroupUid(self::BEGROUP_EDITOR_PREMIUM)
  2061. ];
  2062. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2063. if (!$withRestrictions) {
  2064. $queryBuilder->getRestrictions()->removeAll();
  2065. }
  2066. $editorsGroupUid = $queryBuilder
  2067. ->select('uid')
  2068. ->from('be_groups')
  2069. ->where('FIND_IN_SET(' . $rootUid . ', db_mountpoints) > 0')
  2070. ->andWhere('(FIND_IN_SET(' . $editorsGroups[0] . ', subgroup) > 0 OR FIND_IN_SET(' . $editorsGroups[1] . ', subgroup) > 0)')
  2071. ->execute()
  2072. ->fetchColumn(0);
  2073. if ($editorsGroupUid == null) {
  2074. throw new NoSuchRecordException("No editors be_group found " .
  2075. "among the groups that have this website mounted (root uid: " . $rootUid . ")");
  2076. }
  2077. return $editorsGroupUid;
  2078. }
  2079. /**
  2080. * Try to find and return the uid of the admin be_user
  2081. * for this website
  2082. *
  2083. * @param int $rootUid
  2084. * @param bool $withRestrictions If false, the default restrictions won't apply, meaning this could return a deleted record
  2085. * @return int
  2086. * @throws NoSuchRecordException
  2087. * @throws NoSuchWebsiteException
  2088. */
  2089. protected function findAdminBeUserUid(int $rootUid, bool $withRestrictions=true): int {
  2090. $adminGroups = [
  2091. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_STANDARD),
  2092. $this->getBaseBeGroupUid(self::BEGROUP_ADMIN_PREMIUM)
  2093. ];
  2094. $adminUid = null;
  2095. try {
  2096. $editorsGroupUid = $this->findEditorsBeGroupUid($rootUid);
  2097. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2098. if (!$withRestrictions) {
  2099. $queryBuilder->getRestrictions()->removeAll();
  2100. }
  2101. $adminUid = $queryBuilder
  2102. ->select('uid')
  2103. ->from('be_users')
  2104. ->where('FIND_IN_SET(' . $editorsGroupUid . ', usergroup) > 0')
  2105. ->andWhere('(FIND_IN_SET(' . $adminGroups[0] . ', usergroup) > 0 OR FIND_IN_SET(' . $adminGroups[1] . ', usergroup) > 0)')
  2106. ->execute()
  2107. ->fetchColumn(0);
  2108. return $adminUid;
  2109. } catch (NoSuchRecordException $e) {
  2110. // the editors group does not exist
  2111. }
  2112. // [For retrocompatibility] Try to find if there is a be_user still in the v8.7 data format
  2113. if ($adminUid == null) {
  2114. $website = $this->otWebsiteRepository->getWebsiteByPageUid($rootUid);
  2115. $extraData = $this->fetchOrganizationExtraData($website['organization_id']);
  2116. $expectedUsername = $extraData['admin']['username'];
  2117. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_users');
  2118. if (!$withRestrictions) {
  2119. $queryBuilder->getRestrictions()->removeAll();
  2120. }
  2121. $row = $queryBuilder
  2122. ->select('uid', 'db_mountpoints')
  2123. ->from('be_users')
  2124. ->where($queryBuilder->expr()->eq('username', $queryBuilder->expr()->literal($expectedUsername)))
  2125. ->execute()
  2126. ->fetch();
  2127. if ($row['uid']) {
  2128. if ((string)$rootUid != (string)$row['db_mountpoints']) {
  2129. throw new \RuntimeException(
  2130. "The be_user named '" . $expectedUsername .
  2131. "' has unexpected mounted website(s) (expected: " . $rootUid .
  2132. ", found: " . (string)$row['db_mountpoints'] . "). Abort."
  2133. );
  2134. }
  2135. $adminUid = $row['uid'];
  2136. }
  2137. }
  2138. if ($adminUid == null) {
  2139. throw new NoSuchRecordException("No admin be_user found " .
  2140. "among the users that have this website mounted (root uid: " . $rootUid . ")");
  2141. }
  2142. return $adminUid;
  2143. }
  2144. /**
  2145. * Return the uid of one of the base groups (BEGROUP_EDITOR_STANDARD, BEGROUP_EDITOR_PREMIUM, ...)
  2146. *
  2147. * @param int $groupType
  2148. * @return int
  2149. */
  2150. protected function getBaseBeGroupUid(int $groupType): int
  2151. {
  2152. $expectedName = self::BEGROUP_NAME[$groupType];
  2153. $queryBuilder = $this->connectionPool->getQueryBuilderForTable('be_groups');
  2154. $uid = $queryBuilder
  2155. ->select('uid')
  2156. ->from('be_groups')
  2157. ->where($queryBuilder->expr()->eq('title', $queryBuilder->expr()->literal($expectedName)))
  2158. ->execute()
  2159. ->fetchColumn(0);
  2160. if (!$uid) {
  2161. throw new \RuntimeException("Expects a BE group named '" . $expectedName . "', but none was found.");
  2162. }
  2163. return $uid;
  2164. }
  2165. /**
  2166. * Enable frontend editing for user
  2167. *
  2168. * @param int $adminUid
  2169. */
  2170. private function enableFeEditing(int $adminUid) {
  2171. $BE_USER = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
  2172. $user = $BE_USER->getRawUserByUid($adminUid);
  2173. $BE_USER->user = $user;
  2174. $BE_USER->backendSetUC();
  2175. $BE_USER->uc['frontend_editing'] = 1;
  2176. $BE_USER->uc['frontend_editing_overlay'] = 1;
  2177. $BE_USER->writeUC($BE_USER->uc);
  2178. }
  2179. }