TemplateManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Files\Template;
  8. use OC\AppFramework\Bootstrap\Coordinator;
  9. use OC\Files\Cache\Scanner;
  10. use OC\Files\Filesystem;
  11. use OCP\EventDispatcher\IEventDispatcher;
  12. use OCP\Files\File;
  13. use OCP\Files\Folder;
  14. use OCP\Files\GenericFileException;
  15. use OCP\Files\IRootFolder;
  16. use OCP\Files\Node;
  17. use OCP\Files\NotFoundException;
  18. use OCP\Files\Template\BeforeGetTemplatesEvent;
  19. use OCP\Files\Template\FileCreatedFromTemplateEvent;
  20. use OCP\Files\Template\ICustomTemplateProvider;
  21. use OCP\Files\Template\ITemplateManager;
  22. use OCP\Files\Template\RegisterTemplateCreatorEvent;
  23. use OCP\Files\Template\Template;
  24. use OCP\Files\Template\TemplateFileCreator;
  25. use OCP\IConfig;
  26. use OCP\IPreview;
  27. use OCP\IServerContainer;
  28. use OCP\IUserManager;
  29. use OCP\IUserSession;
  30. use OCP\L10N\IFactory;
  31. use Psr\Log\LoggerInterface;
  32. class TemplateManager implements ITemplateManager {
  33. private $registeredTypes = [];
  34. private $types = [];
  35. /** @var array|null */
  36. private $providers = null;
  37. private $serverContainer;
  38. private $eventDispatcher;
  39. private $rootFolder;
  40. private $userManager;
  41. private $previewManager;
  42. private $config;
  43. private $l10n;
  44. private $logger;
  45. private $userId;
  46. private $l10nFactory;
  47. /** @var Coordinator */
  48. private $bootstrapCoordinator;
  49. public function __construct(
  50. IServerContainer $serverContainer,
  51. IEventDispatcher $eventDispatcher,
  52. Coordinator $coordinator,
  53. IRootFolder $rootFolder,
  54. IUserSession $userSession,
  55. IUserManager $userManager,
  56. IPreview $previewManager,
  57. IConfig $config,
  58. IFactory $l10nFactory,
  59. LoggerInterface $logger
  60. ) {
  61. $this->serverContainer = $serverContainer;
  62. $this->eventDispatcher = $eventDispatcher;
  63. $this->bootstrapCoordinator = $coordinator;
  64. $this->rootFolder = $rootFolder;
  65. $this->userManager = $userManager;
  66. $this->previewManager = $previewManager;
  67. $this->config = $config;
  68. $this->l10nFactory = $l10nFactory;
  69. $this->l10n = $l10nFactory->get('lib');
  70. $this->logger = $logger;
  71. $user = $userSession->getUser();
  72. $this->userId = $user ? $user->getUID() : null;
  73. }
  74. public function registerTemplateFileCreator(callable $callback): void {
  75. $this->registeredTypes[] = $callback;
  76. }
  77. public function getRegisteredProviders(): array {
  78. if ($this->providers !== null) {
  79. return $this->providers;
  80. }
  81. $context = $this->bootstrapCoordinator->getRegistrationContext();
  82. $this->providers = [];
  83. foreach ($context->getTemplateProviders() as $provider) {
  84. $class = $provider->getService();
  85. $this->providers[$class] = $this->serverContainer->get($class);
  86. }
  87. return $this->providers;
  88. }
  89. public function getTypes(): array {
  90. if (!empty($this->types)) {
  91. return $this->types;
  92. }
  93. $this->eventDispatcher->dispatchTyped(new RegisterTemplateCreatorEvent($this));
  94. foreach ($this->registeredTypes as $registeredType) {
  95. $this->types[] = $registeredType();
  96. }
  97. return $this->types;
  98. }
  99. public function listCreators(): array {
  100. $types = $this->getTypes();
  101. usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
  102. return $a->getOrder() - $b->getOrder();
  103. });
  104. return $types;
  105. }
  106. public function listTemplates(): array {
  107. return array_map(function (TemplateFileCreator $entry) {
  108. return array_merge($entry->jsonSerialize(), [
  109. 'templates' => $this->getTemplateFiles($entry)
  110. ]);
  111. }, $this->listCreators());
  112. }
  113. /**
  114. * @param string $filePath
  115. * @param string $templateId
  116. * @param array $templateFields
  117. * @return array
  118. * @throws GenericFileException
  119. */
  120. public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array {
  121. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  122. try {
  123. $userFolder->get($filePath);
  124. throw new GenericFileException($this->l10n->t('File already exists'));
  125. } catch (NotFoundException $e) {
  126. }
  127. try {
  128. if (!$userFolder->nodeExists(dirname($filePath))) {
  129. throw new GenericFileException($this->l10n->t('Invalid path'));
  130. }
  131. $folder = $userFolder->get(dirname($filePath));
  132. $targetFile = $folder->newFile(basename($filePath));
  133. $template = null;
  134. if ($templateType === 'user' && $templateId !== '') {
  135. $template = $userFolder->get($templateId);
  136. $template->copy($targetFile->getPath());
  137. } else {
  138. $matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
  139. return $templateType === get_class($provider);
  140. });
  141. $provider = array_shift($matchingProvider);
  142. if ($provider) {
  143. $template = $provider->getCustomTemplate($templateId);
  144. $template->copy($targetFile->getPath());
  145. }
  146. }
  147. $this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
  148. return $this->formatFile($userFolder->get($filePath));
  149. } catch (\Exception $e) {
  150. $this->logger->error($e->getMessage(), ['exception' => $e]);
  151. throw new GenericFileException($this->l10n->t('Failed to create file from template'));
  152. }
  153. }
  154. /**
  155. * @return Folder
  156. * @throws \OCP\Files\NotFoundException
  157. * @throws \OCP\Files\NotPermittedException
  158. * @throws \OC\User\NoUserException
  159. */
  160. private function getTemplateFolder(): Node {
  161. if ($this->getTemplatePath() !== '') {
  162. return $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
  163. }
  164. throw new NotFoundException();
  165. }
  166. private function getTemplateFiles(TemplateFileCreator $type): array {
  167. $templates = [];
  168. foreach ($this->getRegisteredProviders() as $provider) {
  169. foreach ($type->getMimetypes() as $mimetype) {
  170. foreach ($provider->getCustomTemplates($mimetype) as $template) {
  171. $templates[] = $template;
  172. }
  173. }
  174. }
  175. try {
  176. $userTemplateFolder = $this->getTemplateFolder();
  177. } catch (\Exception $e) {
  178. return $templates;
  179. }
  180. foreach ($type->getMimetypes() as $mimetype) {
  181. foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
  182. $template = new Template(
  183. 'user',
  184. $this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
  185. $templateFile
  186. );
  187. $template->setHasPreview($this->previewManager->isAvailable($templateFile));
  188. $templates[] = $template;
  189. }
  190. }
  191. $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates));
  192. return $templates;
  193. }
  194. /**
  195. * @param Node|File $file
  196. * @return array
  197. * @throws NotFoundException
  198. * @throws \OCP\Files\InvalidPathException
  199. */
  200. private function formatFile(Node $file): array {
  201. return [
  202. 'basename' => $file->getName(),
  203. 'etag' => $file->getEtag(),
  204. 'fileid' => $file->getId(),
  205. 'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
  206. 'lastmod' => $file->getMTime(),
  207. 'mime' => $file->getMimetype(),
  208. 'size' => $file->getSize(),
  209. 'type' => $file->getType(),
  210. 'hasPreview' => $this->previewManager->isAvailable($file),
  211. 'permissions' => $file->getPermissions(),
  212. ];
  213. }
  214. public function hasTemplateDirectory(): bool {
  215. try {
  216. $this->getTemplateFolder();
  217. return true;
  218. } catch (\Exception $e) {
  219. }
  220. return false;
  221. }
  222. public function setTemplatePath(string $path): void {
  223. $this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
  224. }
  225. public function getTemplatePath(): string {
  226. return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
  227. }
  228. public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
  229. if ($userId !== null) {
  230. $this->userId = $userId;
  231. }
  232. $defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
  233. $defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
  234. $skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
  235. $skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
  236. $isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
  237. $isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
  238. $userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
  239. if ($skeletonTemplatePath === '') {
  240. $this->setTemplatePath('');
  241. return '';
  242. }
  243. try {
  244. $l10n = $this->l10nFactory->get('lib', $userLang);
  245. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  246. $userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
  247. // Initial user setup without a provided path
  248. if ($path === null) {
  249. // All locations are default so we just need to rename the directory to the users language
  250. if ($isDefaultSkeleton && $isDefaultTemplates) {
  251. if (!$userFolder->nodeExists('Templates')) {
  252. return '';
  253. }
  254. $newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
  255. if ($newPath !== $userFolder->get('Templates')->getPath()) {
  256. $userFolder->get('Templates')->move($newPath);
  257. }
  258. $this->setTemplatePath($userTemplatePath);
  259. return $userTemplatePath;
  260. }
  261. if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
  262. $shippedSkeletonTemplates = $userFolder->get('Templates');
  263. $shippedSkeletonTemplates->delete();
  264. }
  265. }
  266. try {
  267. $folder = $userFolder->get($userTemplatePath);
  268. } catch (NotFoundException $e) {
  269. $folder = $userFolder->get(dirname($userTemplatePath));
  270. $folder = $folder->newFolder(basename($userTemplatePath));
  271. }
  272. $folderIsEmpty = count($folder->getDirectoryListing()) === 0;
  273. if (!$copyTemplates) {
  274. $this->setTemplatePath($userTemplatePath);
  275. return $userTemplatePath;
  276. }
  277. if (!$isDefaultTemplates && $folderIsEmpty) {
  278. $localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
  279. if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
  280. \OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
  281. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  282. $this->setTemplatePath($userTemplatePath);
  283. return $userTemplatePath;
  284. }
  285. }
  286. if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
  287. $localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
  288. if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
  289. \OC_Util::copyr($localizedSkeletonPath, $folder);
  290. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  291. $this->setTemplatePath($userTemplatePath);
  292. return $userTemplatePath;
  293. }
  294. }
  295. $this->setTemplatePath($path ?? '');
  296. return $this->getTemplatePath();
  297. } catch (\Throwable $e) {
  298. $this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
  299. }
  300. $this->setTemplatePath('');
  301. return $this->getTemplatePath();
  302. }
  303. private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
  304. $localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
  305. if (!file_exists($localizedSkeletonTemplatePath)) {
  306. $dialectStart = strpos($userLang, '_');
  307. if ($dialectStart !== false) {
  308. $localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
  309. }
  310. if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
  311. $localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
  312. }
  313. }
  314. return $localizedSkeletonTemplatePath;
  315. }
  316. }