SiteController.php 94 KB

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