TemplateManager.php 12 KB

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