TemplateManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. 'permissions' => $file->getPermissions(),
  226. ];
  227. }
  228. public function hasTemplateDirectory(): bool {
  229. try {
  230. $this->getTemplateFolder();
  231. return true;
  232. } catch (\Exception $e) {
  233. }
  234. return false;
  235. }
  236. public function setTemplatePath(string $path): void {
  237. $this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
  238. }
  239. public function getTemplatePath(): string {
  240. return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
  241. }
  242. public function initializeTemplateDirectory(string $path = null, string $userId = null, $copyTemplates = true): string {
  243. if ($userId !== null) {
  244. $this->userId = $userId;
  245. }
  246. $defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
  247. $defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
  248. $skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
  249. $skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
  250. $isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
  251. $isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
  252. $userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
  253. try {
  254. $l10n = $this->l10nFactory->get('lib', $userLang);
  255. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  256. $userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
  257. // Initial user setup without a provided path
  258. if ($path === null) {
  259. // All locations are default so we just need to rename the directory to the users language
  260. if ($isDefaultSkeleton && $isDefaultTemplates) {
  261. if (!$userFolder->nodeExists('Templates')) {
  262. return '';
  263. }
  264. $newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
  265. if ($newPath !== $userFolder->get('Templates')->getPath()) {
  266. $userFolder->get('Templates')->move($newPath);
  267. }
  268. $this->setTemplatePath($userTemplatePath);
  269. return $userTemplatePath;
  270. }
  271. if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
  272. $shippedSkeletonTemplates = $userFolder->get('Templates');
  273. $shippedSkeletonTemplates->delete();
  274. }
  275. }
  276. try {
  277. $folder = $userFolder->get($userTemplatePath);
  278. } catch (NotFoundException $e) {
  279. $folder = $userFolder->get(dirname($userTemplatePath));
  280. $folder = $folder->newFolder(basename($userTemplatePath));
  281. }
  282. $folderIsEmpty = count($folder->getDirectoryListing()) === 0;
  283. if (!$copyTemplates) {
  284. $this->setTemplatePath($userTemplatePath);
  285. return $userTemplatePath;
  286. }
  287. if (!$isDefaultTemplates && $folderIsEmpty) {
  288. $localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
  289. if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
  290. \OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
  291. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  292. $this->setTemplatePath($userTemplatePath);
  293. return $userTemplatePath;
  294. }
  295. }
  296. if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
  297. $localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
  298. if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
  299. \OC_Util::copyr($localizedSkeletonPath, $folder);
  300. $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
  301. $this->setTemplatePath($userTemplatePath);
  302. return $userTemplatePath;
  303. }
  304. }
  305. $this->setTemplatePath($path ?? '');
  306. return $this->getTemplatePath();
  307. } catch (\Throwable $e) {
  308. $this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
  309. }
  310. $this->setTemplatePath('');
  311. return $this->getTemplatePath();
  312. }
  313. private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
  314. $localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
  315. if (!file_exists($localizedSkeletonTemplatePath)) {
  316. $dialectStart = strpos($userLang, '_');
  317. if ($dialectStart !== false) {
  318. $localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
  319. }
  320. if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
  321. $localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
  322. }
  323. }
  324. return $localizedSkeletonTemplatePath;
  325. }
  326. }