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. $template = null;
  133. if ($templateType === 'user' && $templateId !== '') {
  134. $template = $userFolder->get($templateId);
  135. } else {
  136. $matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
  137. return $templateType === get_class($provider);
  138. });
  139. $provider = array_shift($matchingProvider);
  140. if ($provider) {
  141. $template = $provider->getCustomTemplate($templateId);
  142. }
  143. }
  144. $targetFile = $folder->newFile(basename($filePath), ($template instanceof File ? $template->fopen('rb') : null));
  145. $this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
  146. return $this->formatFile($userFolder->get($filePath));
  147. } catch (\Exception $e) {
  148. $this->logger->error($e->getMessage(), ['exception' => $e]);
  149. throw new GenericFileException($this->l10n->t('Failed to create file from template'));
  150. }
  151. }
  152. /**
  153. * @return Folder
  154. * @throws \OCP\Files\NotFoundException
  155. * @throws \OCP\Files\NotPermittedException
  156. * @throws \OC\User\NoUserException
  157. */
  158. private function getTemplateFolder(): Node {
  159. if ($this->getTemplatePath() !== '') {
  160. return $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
  161. }
  162. throw new NotFoundException();
  163. }
  164. private function getTemplateFiles(TemplateFileCreator $type): array {
  165. $templates = [];
  166. foreach ($this->getRegisteredProviders() as $provider) {
  167. foreach ($type->getMimetypes() as $mimetype) {
  168. foreach ($provider->getCustomTemplates($mimetype) as $template) {
  169. $templates[] = $template;
  170. }
  171. }
  172. }
  173. try {
  174. $userTemplateFolder = $this->getTemplateFolder();
  175. } catch (\Exception $e) {
  176. return $templates;
  177. }
  178. foreach ($type->getMimetypes() as $mimetype) {
  179. foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
  180. $template = new Template(
  181. 'user',
  182. $this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
  183. $templateFile
  184. );
  185. $template->setHasPreview($this->previewManager->isAvailable($templateFile));
  186. $templates[] = $template;
  187. }
  188. }
  189. $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates));
  190. return $templates;
  191. }
  192. /**
  193. * @param Node|File $file
  194. * @return array
  195. * @throws NotFoundException
  196. * @throws \OCP\Files\InvalidPathException
  197. */
  198. private function formatFile(Node $file): array {
  199. return [
  200. 'basename' => $file->getName(),
  201. 'etag' => $file->getEtag(),
  202. 'fileid' => $file->getId(),
  203. 'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
  204. 'lastmod' => $file->getMTime(),
  205. 'mime' => $file->getMimetype(),
  206. 'size' => $file->getSize(),
  207. 'type' => $file->getType(),
  208. 'hasPreview' => $this->previewManager->isAvailable($file),
  209. 'permissions' => $file->getPermissions(),
  210. ];
  211. }
  212. public function hasTemplateDirectory(): bool {
  213. try {
  214. $this->getTemplateFolder();
  215. return true;
  216. } catch (\Exception $e) {
  217. }
  218. return false;
  219. }
  220. public function setTemplatePath(string $path): void {
  221. $this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
  222. }
  223. public function getTemplatePath(): string {
  224. return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
  225. }
  226. public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
  227. if ($userId !== null) {
  228. $this->userId = $userId;
  229. }
  230. $defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
  231. $defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
  232. $skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
  233. $skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
  234. $isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
  235. $isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
  236. $userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
  237. if ($skeletonTemplatePath === '') {
  238. $this->setTemplatePath('');
  239. return '';
  240. }
  241. try {
  242. $l10n = $this->l10nFactory->get('lib', $userLang);
  243. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  244. $userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
  245. // Initial user setup without a provided path
  246. if ($path === null) {
  247. // All locations are default so we just need to rename the directory to the users language
  248. if ($isDefaultSkeleton && $isDefaultTemplates) {
  249. if (!$userFolder->nodeExists('Templates')) {
  250. return '';
  251. }
  252. $newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
  253. if ($newPath !== $userFolder->get('Templates')->getPath()) {
  254. $userFolder->get('Templates')->move($newPath);
  255. }
  256. $this->setTemplatePath($userTemplatePath);
  257. return $userTemplatePath;
  258. }
  259. if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
  260. $shippedSkeletonTemplates = $userFolder->get('Templates');
  261. $shippedSkeletonTemplates->delete();
  262. }
  263. }
  264. try {
  265. $folder = $userFolder->get($userTemplatePath);
  266. } catch (NotFoundException $e) {
  267. $folder = $userFolder->get(dirname($userTemplatePath));
  268. $folder = $folder->newFolder(basename($userTemplatePath));
  269. }
  270. $folderIsEmpty = count($folder->getDirectoryListing()) === 0;
  271. if (!$copyTemplates) {
  272. $this->setTemplatePath($userTemplatePath);
  273. return $userTemplatePath;
  274. }
  275. if (!$isDefaultTemplates && $folderIsEmpty) {
  276. $localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
  277. if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
  278. \OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
  279. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  280. $this->setTemplatePath($userTemplatePath);
  281. return $userTemplatePath;
  282. }
  283. }
  284. if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
  285. $localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
  286. if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
  287. \OC_Util::copyr($localizedSkeletonPath, $folder);
  288. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  289. $this->setTemplatePath($userTemplatePath);
  290. return $userTemplatePath;
  291. }
  292. }
  293. $this->setTemplatePath($path ?? '');
  294. return $this->getTemplatePath();
  295. } catch (\Throwable $e) {
  296. $this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
  297. }
  298. $this->setTemplatePath('');
  299. return $this->getTemplatePath();
  300. }
  301. private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
  302. $localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
  303. if (!file_exists($localizedSkeletonTemplatePath)) {
  304. $dialectStart = strpos($userLang, '_');
  305. if ($dialectStart !== false) {
  306. $localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
  307. }
  308. if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
  309. $localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
  310. }
  311. }
  312. return $localizedSkeletonTemplatePath;
  313. }
  314. }