TemplateManager.php 12 KB

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