TemplateManager.php 12 KB

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