1
0

TemplateManager.php 11 KB

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