Completed
Push — master ( 5129a7...99148e )
by
unknown
26:01 queued 14s
created
lib/public/Files/Template/BeforeGetTemplatesEvent.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -15,38 +15,38 @@
 block discarded – undo
15 15
  * @since 30.0.0
16 16
  */
17 17
 class BeforeGetTemplatesEvent extends Event {
18
-	/** @var array<Template> */
19
-	private array $templates;
20
-	/** @var bool */
21
-	private bool $withFields;
22
-
23
-	/**
24
-	 * @param array<Template> $templates
25
-	 *
26
-	 * @since 30.0.0
27
-	 */
28
-	public function __construct(array $templates, bool $withFields = false) {
29
-		parent::__construct();
30
-
31
-		$this->templates = $templates;
32
-		$this->withFields = $withFields;
33
-	}
34
-
35
-	/**
36
-	 * @return array<Template>
37
-	 *
38
-	 * @since 30.0.0
39
-	 */
40
-	public function getTemplates(): array {
41
-		return $this->templates;
42
-	}
43
-
44
-	/**
45
-	 * @return bool
46
-	 *
47
-	 * @since 32.0.0
48
-	 */
49
-	public function shouldGetFields(): bool {
50
-		return $this->withFields;
51
-	}
18
+    /** @var array<Template> */
19
+    private array $templates;
20
+    /** @var bool */
21
+    private bool $withFields;
22
+
23
+    /**
24
+     * @param array<Template> $templates
25
+     *
26
+     * @since 30.0.0
27
+     */
28
+    public function __construct(array $templates, bool $withFields = false) {
29
+        parent::__construct();
30
+
31
+        $this->templates = $templates;
32
+        $this->withFields = $withFields;
33
+    }
34
+
35
+    /**
36
+     * @return array<Template>
37
+     *
38
+     * @since 30.0.0
39
+     */
40
+    public function getTemplates(): array {
41
+        return $this->templates;
42
+    }
43
+
44
+    /**
45
+     * @return bool
46
+     *
47
+     * @since 32.0.0
48
+     */
49
+    public function shouldGetFields(): bool {
50
+        return $this->withFields;
51
+    }
52 52
 }
Please login to merge, or discard this patch.
lib/public/Files/Template/ITemplateManager.php 1 patch
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -14,73 +14,73 @@
 block discarded – undo
14 14
  * @since 21.0.0
15 15
  */
16 16
 interface ITemplateManager {
17
-	/**
18
-	 * Register a template type support
19
-	 *
20
-	 * @param callable(): TemplateFileCreator $callback A callback which returns the TemplateFileCreator instance to register
21
-	 * @since 21.0.0
22
-	 */
23
-	public function registerTemplateFileCreator(callable $callback): void;
17
+    /**
18
+     * Register a template type support
19
+     *
20
+     * @param callable(): TemplateFileCreator $callback A callback which returns the TemplateFileCreator instance to register
21
+     * @since 21.0.0
22
+     */
23
+    public function registerTemplateFileCreator(callable $callback): void;
24 24
 
25
-	/**
26
-	 * Get a list of available file creators
27
-	 *
28
-	 * @return array
29
-	 * @since 21.0.0
30
-	 */
31
-	public function listCreators(): array;
25
+    /**
26
+     * Get a list of available file creators
27
+     *
28
+     * @return array
29
+     * @since 21.0.0
30
+     */
31
+    public function listCreators(): array;
32 32
 
33
-	/**
34
-	 * Get a list of available file creators and their offered templates
35
-	 *
36
-	 * @return list<array{app: string, label: string, extension: string, iconClass: ?string, iconSvgInline: ?string, mimetypes: list<string>, ratio: ?float, actionLabel: string, templates: list<Template>}>
37
-	 * @since 21.0.0
38
-	 */
39
-	public function listTemplates(): array;
33
+    /**
34
+     * Get a list of available file creators and their offered templates
35
+     *
36
+     * @return list<array{app: string, label: string, extension: string, iconClass: ?string, iconSvgInline: ?string, mimetypes: list<string>, ratio: ?float, actionLabel: string, templates: list<Template>}>
37
+     * @since 21.0.0
38
+     */
39
+    public function listTemplates(): array;
40 40
 
41
-	/**
42
-	 * Get the fields for a given template
43
-	 *
44
-	 * @param int $fileId
45
-	 * @return array
46
-	 * @since 32.0.0
47
-	 */
48
-	public function listTemplateFields(int $fileId): array;
41
+    /**
42
+     * Get the fields for a given template
43
+     *
44
+     * @param int $fileId
45
+     * @return array
46
+     * @since 32.0.0
47
+     */
48
+    public function listTemplateFields(int $fileId): array;
49 49
 
50
-	/**
51
-	 * @return bool
52
-	 * @since 21.0.0
53
-	 */
54
-	public function hasTemplateDirectory(): bool;
50
+    /**
51
+     * @return bool
52
+     * @since 21.0.0
53
+     */
54
+    public function hasTemplateDirectory(): bool;
55 55
 
56
-	/**
57
-	 * @param string $path
58
-	 * @return void
59
-	 * @since 21.0.0
60
-	 */
61
-	public function setTemplatePath(string $path): void;
56
+    /**
57
+     * @param string $path
58
+     * @return void
59
+     * @since 21.0.0
60
+     */
61
+    public function setTemplatePath(string $path): void;
62 62
 
63
-	/**
64
-	 * @return string
65
-	 * @since 21.0.0
66
-	 */
67
-	public function getTemplatePath(): string;
63
+    /**
64
+     * @return string
65
+     * @since 21.0.0
66
+     */
67
+    public function getTemplatePath(): string;
68 68
 
69
-	/**
70
-	 * @param string|null $path
71
-	 * @param string|null $userId
72
-	 * @since 21.0.0
73
-	 */
74
-	public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string;
69
+    /**
70
+     * @param string|null $path
71
+     * @param string|null $userId
72
+     * @since 21.0.0
73
+     */
74
+    public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string;
75 75
 
76
-	/**
77
-	 * @param string $filePath
78
-	 * @param string $templateId
79
-	 * @param string $templateType
80
-	 * @param array $templateFields Since 30.0.0
81
-	 * @return array
82
-	 * @throws GenericFileException
83
-	 * @since 21.0.0
84
-	 */
85
-	public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array;
76
+    /**
77
+     * @param string $filePath
78
+     * @param string $templateId
79
+     * @param string $templateType
80
+     * @param array $templateFields Since 30.0.0
81
+     * @return array
82
+     * @throws GenericFileException
83
+     * @since 21.0.0
84
+     */
85
+    public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array;
86 86
 }
Please login to merge, or discard this patch.
lib/private/Files/Template/TemplateManager.php 2 patches
Indentation   +381 added lines, -381 removed lines patch added patch discarded remove patch
@@ -35,387 +35,387 @@
 block discarded – undo
35 35
 use Psr\Log\LoggerInterface;
36 36
 
37 37
 class TemplateManager implements ITemplateManager {
38
-	private $registeredTypes = [];
39
-	private $types = [];
40
-
41
-	/** @var array|null */
42
-	private $providers = null;
43
-
44
-	private $serverContainer;
45
-	private $eventDispatcher;
46
-	private $rootFolder;
47
-	private $userManager;
48
-	private $previewManager;
49
-	private $config;
50
-	private $l10n;
51
-	private $logger;
52
-	private $userId;
53
-	private $l10nFactory;
54
-	/** @var Coordinator */
55
-	private $bootstrapCoordinator;
56
-
57
-	public function __construct(
58
-		IServerContainer $serverContainer,
59
-		IEventDispatcher $eventDispatcher,
60
-		Coordinator $coordinator,
61
-		IRootFolder $rootFolder,
62
-		IUserSession $userSession,
63
-		IUserManager $userManager,
64
-		IPreview $previewManager,
65
-		IConfig $config,
66
-		IFactory $l10nFactory,
67
-		LoggerInterface $logger,
68
-	) {
69
-		$this->serverContainer = $serverContainer;
70
-		$this->eventDispatcher = $eventDispatcher;
71
-		$this->bootstrapCoordinator = $coordinator;
72
-		$this->rootFolder = $rootFolder;
73
-		$this->userManager = $userManager;
74
-		$this->previewManager = $previewManager;
75
-		$this->config = $config;
76
-		$this->l10nFactory = $l10nFactory;
77
-		$this->l10n = $l10nFactory->get('lib');
78
-		$this->logger = $logger;
79
-		$user = $userSession->getUser();
80
-		$this->userId = $user ? $user->getUID() : null;
81
-	}
82
-
83
-	public function registerTemplateFileCreator(callable $callback): void {
84
-		$this->registeredTypes[] = $callback;
85
-	}
86
-
87
-	public function getRegisteredProviders(): array {
88
-		if ($this->providers !== null) {
89
-			return $this->providers;
90
-		}
91
-
92
-		$context = $this->bootstrapCoordinator->getRegistrationContext();
93
-
94
-		$this->providers = [];
95
-		foreach ($context->getTemplateProviders() as $provider) {
96
-			$class = $provider->getService();
97
-			$this->providers[$class] = $this->serverContainer->get($class);
98
-		}
99
-		return $this->providers;
100
-	}
101
-
102
-	public function getTypes(): array {
103
-		if (!empty($this->types)) {
104
-			return $this->types;
105
-		}
106
-		$this->eventDispatcher->dispatchTyped(new RegisterTemplateCreatorEvent($this));
107
-		foreach ($this->registeredTypes as $registeredType) {
108
-			$this->types[] = $registeredType();
109
-		}
110
-		return $this->types;
111
-	}
112
-
113
-	public function listCreators(): array {
114
-		$types = $this->getTypes();
115
-		usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
116
-			return $a->getOrder() - $b->getOrder();
117
-		});
118
-		return $types;
119
-	}
120
-
121
-	public function listTemplates(): array {
122
-		return array_values(array_map(function (TemplateFileCreator $entry) {
123
-			return array_merge($entry->jsonSerialize(), [
124
-				'templates' => $this->getTemplateFiles($entry)
125
-			]);
126
-		}, $this->listCreators()));
127
-	}
128
-
129
-	public function listTemplateFields(int $fileId): array {
130
-		foreach ($this->listCreators() as $creator) {
131
-			$fields = $this->getTemplateFields($creator, $fileId);
132
-			if (empty($fields)) {
133
-				continue;
134
-			}
135
-
136
-			return $fields;
137
-		}
138
-
139
-		return [];
140
-	}
141
-
142
-	/**
143
-	 * @param string $filePath
144
-	 * @param string $templateId
145
-	 * @param array $templateFields
146
-	 * @return array
147
-	 * @throws GenericFileException
148
-	 */
149
-	public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array {
150
-		$userFolder = $this->rootFolder->getUserFolder($this->userId);
151
-		try {
152
-			$userFolder->get($filePath);
153
-			throw new GenericFileException($this->l10n->t('File already exists'));
154
-		} catch (NotFoundException $e) {
155
-		}
156
-		try {
157
-			if (!$userFolder->nodeExists(dirname($filePath))) {
158
-				throw new GenericFileException($this->l10n->t('Invalid path'));
159
-			}
160
-			$folder = $userFolder->get(dirname($filePath));
161
-			$template = null;
162
-			if ($templateType === 'user' && $templateId !== '') {
163
-				$template = $userFolder->get($templateId);
164
-			} else {
165
-				$matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
166
-					return $templateType === get_class($provider);
167
-				});
168
-				$provider = array_shift($matchingProvider);
169
-				if ($provider) {
170
-					$template = $provider->getCustomTemplate($templateId);
171
-				}
172
-			}
173
-
174
-			$targetFile = $folder->newFile(basename($filePath), ($template instanceof File ? $template->fopen('rb') : null));
175
-
176
-			$this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
177
-			return $this->formatFile($userFolder->get($filePath));
178
-		} catch (\Exception $e) {
179
-			$this->logger->error($e->getMessage(), ['exception' => $e]);
180
-			throw new GenericFileException($this->l10n->t('Failed to create file from template'));
181
-		}
182
-	}
183
-
184
-	/**
185
-	 * @return Folder
186
-	 * @throws \OCP\Files\NotFoundException
187
-	 * @throws \OCP\Files\NotPermittedException
188
-	 * @throws \OC\User\NoUserException
189
-	 */
190
-	private function getTemplateFolder(): Folder {
191
-		if ($this->getTemplatePath() !== '') {
192
-			$path = $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
193
-			if ($path instanceof Folder) {
194
-				return $path;
195
-			}
196
-		}
197
-		throw new NotFoundException();
198
-	}
199
-
200
-	/**
201
-	 * @return list<Template>
202
-	 */
203
-	private function getTemplateFiles(TemplateFileCreator $type): array {
204
-		$templates = array_merge(
205
-			$this->getProviderTemplates($type),
206
-			$this->getUserTemplates($type)
207
-		);
208
-
209
-		$this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates, false));
210
-
211
-		return $templates;
212
-	}
213
-
214
-	/**
215
-	 * @return list<Template>
216
-	 */
217
-	private function getProviderTemplates(TemplateFileCreator $type): array {
218
-		$templates = [];
219
-		foreach ($this->getRegisteredProviders() as $provider) {
220
-			foreach ($type->getMimetypes() as $mimetype) {
221
-				foreach ($provider->getCustomTemplates($mimetype) as $template) {
222
-					$templates[] = $template;
223
-				}
224
-			}
225
-		}
226
-
227
-		return $templates;
228
-	}
229
-
230
-	/**
231
-	 * @return list<Template>
232
-	 */
233
-	private function getUserTemplates(TemplateFileCreator $type): array {
234
-		$templates = [];
235
-
236
-		try {
237
-			$userTemplateFolder = $this->getTemplateFolder();
238
-		} catch (\Exception $e) {
239
-			return $templates;
240
-		}
241
-
242
-		foreach ($type->getMimetypes() as $mimetype) {
243
-			foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
244
-				$template = new Template(
245
-					'user',
246
-					$this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
247
-					$templateFile
248
-				);
249
-				$template->setHasPreview($this->previewManager->isAvailable($templateFile));
250
-				$templates[] = $template;
251
-			}
252
-		}
253
-
254
-		return $templates;
255
-	}
256
-
257
-	/*
38
+    private $registeredTypes = [];
39
+    private $types = [];
40
+
41
+    /** @var array|null */
42
+    private $providers = null;
43
+
44
+    private $serverContainer;
45
+    private $eventDispatcher;
46
+    private $rootFolder;
47
+    private $userManager;
48
+    private $previewManager;
49
+    private $config;
50
+    private $l10n;
51
+    private $logger;
52
+    private $userId;
53
+    private $l10nFactory;
54
+    /** @var Coordinator */
55
+    private $bootstrapCoordinator;
56
+
57
+    public function __construct(
58
+        IServerContainer $serverContainer,
59
+        IEventDispatcher $eventDispatcher,
60
+        Coordinator $coordinator,
61
+        IRootFolder $rootFolder,
62
+        IUserSession $userSession,
63
+        IUserManager $userManager,
64
+        IPreview $previewManager,
65
+        IConfig $config,
66
+        IFactory $l10nFactory,
67
+        LoggerInterface $logger,
68
+    ) {
69
+        $this->serverContainer = $serverContainer;
70
+        $this->eventDispatcher = $eventDispatcher;
71
+        $this->bootstrapCoordinator = $coordinator;
72
+        $this->rootFolder = $rootFolder;
73
+        $this->userManager = $userManager;
74
+        $this->previewManager = $previewManager;
75
+        $this->config = $config;
76
+        $this->l10nFactory = $l10nFactory;
77
+        $this->l10n = $l10nFactory->get('lib');
78
+        $this->logger = $logger;
79
+        $user = $userSession->getUser();
80
+        $this->userId = $user ? $user->getUID() : null;
81
+    }
82
+
83
+    public function registerTemplateFileCreator(callable $callback): void {
84
+        $this->registeredTypes[] = $callback;
85
+    }
86
+
87
+    public function getRegisteredProviders(): array {
88
+        if ($this->providers !== null) {
89
+            return $this->providers;
90
+        }
91
+
92
+        $context = $this->bootstrapCoordinator->getRegistrationContext();
93
+
94
+        $this->providers = [];
95
+        foreach ($context->getTemplateProviders() as $provider) {
96
+            $class = $provider->getService();
97
+            $this->providers[$class] = $this->serverContainer->get($class);
98
+        }
99
+        return $this->providers;
100
+    }
101
+
102
+    public function getTypes(): array {
103
+        if (!empty($this->types)) {
104
+            return $this->types;
105
+        }
106
+        $this->eventDispatcher->dispatchTyped(new RegisterTemplateCreatorEvent($this));
107
+        foreach ($this->registeredTypes as $registeredType) {
108
+            $this->types[] = $registeredType();
109
+        }
110
+        return $this->types;
111
+    }
112
+
113
+    public function listCreators(): array {
114
+        $types = $this->getTypes();
115
+        usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
116
+            return $a->getOrder() - $b->getOrder();
117
+        });
118
+        return $types;
119
+    }
120
+
121
+    public function listTemplates(): array {
122
+        return array_values(array_map(function (TemplateFileCreator $entry) {
123
+            return array_merge($entry->jsonSerialize(), [
124
+                'templates' => $this->getTemplateFiles($entry)
125
+            ]);
126
+        }, $this->listCreators()));
127
+    }
128
+
129
+    public function listTemplateFields(int $fileId): array {
130
+        foreach ($this->listCreators() as $creator) {
131
+            $fields = $this->getTemplateFields($creator, $fileId);
132
+            if (empty($fields)) {
133
+                continue;
134
+            }
135
+
136
+            return $fields;
137
+        }
138
+
139
+        return [];
140
+    }
141
+
142
+    /**
143
+     * @param string $filePath
144
+     * @param string $templateId
145
+     * @param array $templateFields
146
+     * @return array
147
+     * @throws GenericFileException
148
+     */
149
+    public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array {
150
+        $userFolder = $this->rootFolder->getUserFolder($this->userId);
151
+        try {
152
+            $userFolder->get($filePath);
153
+            throw new GenericFileException($this->l10n->t('File already exists'));
154
+        } catch (NotFoundException $e) {
155
+        }
156
+        try {
157
+            if (!$userFolder->nodeExists(dirname($filePath))) {
158
+                throw new GenericFileException($this->l10n->t('Invalid path'));
159
+            }
160
+            $folder = $userFolder->get(dirname($filePath));
161
+            $template = null;
162
+            if ($templateType === 'user' && $templateId !== '') {
163
+                $template = $userFolder->get($templateId);
164
+            } else {
165
+                $matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
166
+                    return $templateType === get_class($provider);
167
+                });
168
+                $provider = array_shift($matchingProvider);
169
+                if ($provider) {
170
+                    $template = $provider->getCustomTemplate($templateId);
171
+                }
172
+            }
173
+
174
+            $targetFile = $folder->newFile(basename($filePath), ($template instanceof File ? $template->fopen('rb') : null));
175
+
176
+            $this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
177
+            return $this->formatFile($userFolder->get($filePath));
178
+        } catch (\Exception $e) {
179
+            $this->logger->error($e->getMessage(), ['exception' => $e]);
180
+            throw new GenericFileException($this->l10n->t('Failed to create file from template'));
181
+        }
182
+    }
183
+
184
+    /**
185
+     * @return Folder
186
+     * @throws \OCP\Files\NotFoundException
187
+     * @throws \OCP\Files\NotPermittedException
188
+     * @throws \OC\User\NoUserException
189
+     */
190
+    private function getTemplateFolder(): Folder {
191
+        if ($this->getTemplatePath() !== '') {
192
+            $path = $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
193
+            if ($path instanceof Folder) {
194
+                return $path;
195
+            }
196
+        }
197
+        throw new NotFoundException();
198
+    }
199
+
200
+    /**
201
+     * @return list<Template>
202
+     */
203
+    private function getTemplateFiles(TemplateFileCreator $type): array {
204
+        $templates = array_merge(
205
+            $this->getProviderTemplates($type),
206
+            $this->getUserTemplates($type)
207
+        );
208
+
209
+        $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates, false));
210
+
211
+        return $templates;
212
+    }
213
+
214
+    /**
215
+     * @return list<Template>
216
+     */
217
+    private function getProviderTemplates(TemplateFileCreator $type): array {
218
+        $templates = [];
219
+        foreach ($this->getRegisteredProviders() as $provider) {
220
+            foreach ($type->getMimetypes() as $mimetype) {
221
+                foreach ($provider->getCustomTemplates($mimetype) as $template) {
222
+                    $templates[] = $template;
223
+                }
224
+            }
225
+        }
226
+
227
+        return $templates;
228
+    }
229
+
230
+    /**
231
+     * @return list<Template>
232
+     */
233
+    private function getUserTemplates(TemplateFileCreator $type): array {
234
+        $templates = [];
235
+
236
+        try {
237
+            $userTemplateFolder = $this->getTemplateFolder();
238
+        } catch (\Exception $e) {
239
+            return $templates;
240
+        }
241
+
242
+        foreach ($type->getMimetypes() as $mimetype) {
243
+            foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
244
+                $template = new Template(
245
+                    'user',
246
+                    $this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
247
+                    $templateFile
248
+                );
249
+                $template->setHasPreview($this->previewManager->isAvailable($templateFile));
250
+                $templates[] = $template;
251
+            }
252
+        }
253
+
254
+        return $templates;
255
+    }
256
+
257
+    /*
258 258
 	 * @return list<Field>
259 259
 	 */
260
-	private function getTemplateFields(TemplateFileCreator $type, int $fileId): array {
261
-		$providerTemplates = $this->getProviderTemplates($type);
262
-		$userTemplates = $this->getUserTemplates($type);
263
-
264
-		$matchedTemplates = array_filter(
265
-			array_merge($providerTemplates, $userTemplates),
266
-			function (Template $template) use ($fileId) {
267
-				return $template->jsonSerialize()['fileid'] === $fileId;
268
-			});
269
-
270
-		if (empty($matchedTemplates)) {
271
-			return [];
272
-		}
273
-
274
-		$this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($matchedTemplates, true));
275
-
276
-		return array_values(array_map(function (Template $template) {
277
-			return $template->jsonSerialize()['fields'] ?? [];
278
-		}, $matchedTemplates));
279
-	}
280
-
281
-	/**
282
-	 * @param Node|File $file
283
-	 * @return array
284
-	 * @throws NotFoundException
285
-	 * @throws \OCP\Files\InvalidPathException
286
-	 */
287
-	private function formatFile(Node $file): array {
288
-		return [
289
-			'basename' => $file->getName(),
290
-			'etag' => $file->getEtag(),
291
-			'fileid' => $file->getId(),
292
-			'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
293
-			'lastmod' => $file->getMTime(),
294
-			'mime' => $file->getMimetype(),
295
-			'size' => $file->getSize(),
296
-			'type' => $file->getType(),
297
-			'hasPreview' => $this->previewManager->isAvailable($file),
298
-			'permissions' => $file->getPermissions(),
299
-		];
300
-	}
301
-
302
-	public function hasTemplateDirectory(): bool {
303
-		try {
304
-			$this->getTemplateFolder();
305
-			return true;
306
-		} catch (\Exception $e) {
307
-		}
308
-		return false;
309
-	}
310
-
311
-	public function setTemplatePath(string $path): void {
312
-		$this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
313
-	}
314
-
315
-	public function getTemplatePath(): string {
316
-		return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
317
-	}
318
-
319
-	public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
320
-		if ($userId !== null) {
321
-			$this->userId = $userId;
322
-		}
323
-
324
-		$defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
325
-		$defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
326
-		$skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
327
-		$skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
328
-		$isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
329
-		$isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
330
-		$userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
331
-
332
-		if ($skeletonTemplatePath === '') {
333
-			$this->setTemplatePath('');
334
-			return '';
335
-		}
336
-
337
-		try {
338
-			$l10n = $this->l10nFactory->get('lib', $userLang);
339
-			$userFolder = $this->rootFolder->getUserFolder($this->userId);
340
-			$userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
341
-
342
-			// Initial user setup without a provided path
343
-			if ($path === null) {
344
-				// All locations are default so we just need to rename the directory to the users language
345
-				if ($isDefaultSkeleton && $isDefaultTemplates) {
346
-					if (!$userFolder->nodeExists('Templates')) {
347
-						return '';
348
-					}
349
-					$newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
350
-					if ($newPath !== $userFolder->get('Templates')->getPath()) {
351
-						$userFolder->get('Templates')->move($newPath);
352
-					}
353
-					$this->setTemplatePath($userTemplatePath);
354
-					return $userTemplatePath;
355
-				}
356
-
357
-				if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
358
-					$shippedSkeletonTemplates = $userFolder->get('Templates');
359
-					$shippedSkeletonTemplates->delete();
360
-				}
361
-			}
362
-
363
-			try {
364
-				$folder = $userFolder->get($userTemplatePath);
365
-			} catch (NotFoundException $e) {
366
-				$folder = $userFolder->get(dirname($userTemplatePath));
367
-				$folder = $folder->newFolder(basename($userTemplatePath));
368
-			}
369
-
370
-			$folderIsEmpty = count($folder->getDirectoryListing()) === 0;
371
-
372
-			if (!$copyTemplates) {
373
-				$this->setTemplatePath($userTemplatePath);
374
-				return $userTemplatePath;
375
-			}
376
-
377
-			if (!$isDefaultTemplates && $folderIsEmpty) {
378
-				$localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
379
-				if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
380
-					\OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
381
-					$userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
382
-					$this->setTemplatePath($userTemplatePath);
383
-					return $userTemplatePath;
384
-				}
385
-			}
386
-
387
-			if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
388
-				$localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
389
-				if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
390
-					\OC_Util::copyr($localizedSkeletonPath, $folder);
391
-					$userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
392
-					$this->setTemplatePath($userTemplatePath);
393
-					return $userTemplatePath;
394
-				}
395
-			}
396
-
397
-			$this->setTemplatePath($path ?? '');
398
-			return $this->getTemplatePath();
399
-		} catch (\Throwable $e) {
400
-			$this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
401
-		}
402
-		$this->setTemplatePath('');
403
-		return $this->getTemplatePath();
404
-	}
405
-
406
-	private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
407
-		$localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
408
-
409
-		if (!file_exists($localizedSkeletonTemplatePath)) {
410
-			$dialectStart = strpos($userLang, '_');
411
-			if ($dialectStart !== false) {
412
-				$localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
413
-			}
414
-			if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
415
-				$localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
416
-			}
417
-		}
418
-
419
-		return $localizedSkeletonTemplatePath;
420
-	}
260
+    private function getTemplateFields(TemplateFileCreator $type, int $fileId): array {
261
+        $providerTemplates = $this->getProviderTemplates($type);
262
+        $userTemplates = $this->getUserTemplates($type);
263
+
264
+        $matchedTemplates = array_filter(
265
+            array_merge($providerTemplates, $userTemplates),
266
+            function (Template $template) use ($fileId) {
267
+                return $template->jsonSerialize()['fileid'] === $fileId;
268
+            });
269
+
270
+        if (empty($matchedTemplates)) {
271
+            return [];
272
+        }
273
+
274
+        $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($matchedTemplates, true));
275
+
276
+        return array_values(array_map(function (Template $template) {
277
+            return $template->jsonSerialize()['fields'] ?? [];
278
+        }, $matchedTemplates));
279
+    }
280
+
281
+    /**
282
+     * @param Node|File $file
283
+     * @return array
284
+     * @throws NotFoundException
285
+     * @throws \OCP\Files\InvalidPathException
286
+     */
287
+    private function formatFile(Node $file): array {
288
+        return [
289
+            'basename' => $file->getName(),
290
+            'etag' => $file->getEtag(),
291
+            'fileid' => $file->getId(),
292
+            'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
293
+            'lastmod' => $file->getMTime(),
294
+            'mime' => $file->getMimetype(),
295
+            'size' => $file->getSize(),
296
+            'type' => $file->getType(),
297
+            'hasPreview' => $this->previewManager->isAvailable($file),
298
+            'permissions' => $file->getPermissions(),
299
+        ];
300
+    }
301
+
302
+    public function hasTemplateDirectory(): bool {
303
+        try {
304
+            $this->getTemplateFolder();
305
+            return true;
306
+        } catch (\Exception $e) {
307
+        }
308
+        return false;
309
+    }
310
+
311
+    public function setTemplatePath(string $path): void {
312
+        $this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
313
+    }
314
+
315
+    public function getTemplatePath(): string {
316
+        return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
317
+    }
318
+
319
+    public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
320
+        if ($userId !== null) {
321
+            $this->userId = $userId;
322
+        }
323
+
324
+        $defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
325
+        $defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
326
+        $skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
327
+        $skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
328
+        $isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
329
+        $isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
330
+        $userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
331
+
332
+        if ($skeletonTemplatePath === '') {
333
+            $this->setTemplatePath('');
334
+            return '';
335
+        }
336
+
337
+        try {
338
+            $l10n = $this->l10nFactory->get('lib', $userLang);
339
+            $userFolder = $this->rootFolder->getUserFolder($this->userId);
340
+            $userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
341
+
342
+            // Initial user setup without a provided path
343
+            if ($path === null) {
344
+                // All locations are default so we just need to rename the directory to the users language
345
+                if ($isDefaultSkeleton && $isDefaultTemplates) {
346
+                    if (!$userFolder->nodeExists('Templates')) {
347
+                        return '';
348
+                    }
349
+                    $newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
350
+                    if ($newPath !== $userFolder->get('Templates')->getPath()) {
351
+                        $userFolder->get('Templates')->move($newPath);
352
+                    }
353
+                    $this->setTemplatePath($userTemplatePath);
354
+                    return $userTemplatePath;
355
+                }
356
+
357
+                if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
358
+                    $shippedSkeletonTemplates = $userFolder->get('Templates');
359
+                    $shippedSkeletonTemplates->delete();
360
+                }
361
+            }
362
+
363
+            try {
364
+                $folder = $userFolder->get($userTemplatePath);
365
+            } catch (NotFoundException $e) {
366
+                $folder = $userFolder->get(dirname($userTemplatePath));
367
+                $folder = $folder->newFolder(basename($userTemplatePath));
368
+            }
369
+
370
+            $folderIsEmpty = count($folder->getDirectoryListing()) === 0;
371
+
372
+            if (!$copyTemplates) {
373
+                $this->setTemplatePath($userTemplatePath);
374
+                return $userTemplatePath;
375
+            }
376
+
377
+            if (!$isDefaultTemplates && $folderIsEmpty) {
378
+                $localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
379
+                if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
380
+                    \OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
381
+                    $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
382
+                    $this->setTemplatePath($userTemplatePath);
383
+                    return $userTemplatePath;
384
+                }
385
+            }
386
+
387
+            if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
388
+                $localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
389
+                if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
390
+                    \OC_Util::copyr($localizedSkeletonPath, $folder);
391
+                    $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
392
+                    $this->setTemplatePath($userTemplatePath);
393
+                    return $userTemplatePath;
394
+                }
395
+            }
396
+
397
+            $this->setTemplatePath($path ?? '');
398
+            return $this->getTemplatePath();
399
+        } catch (\Throwable $e) {
400
+            $this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
401
+        }
402
+        $this->setTemplatePath('');
403
+        return $this->getTemplatePath();
404
+    }
405
+
406
+    private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
407
+        $localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
408
+
409
+        if (!file_exists($localizedSkeletonTemplatePath)) {
410
+            $dialectStart = strpos($userLang, '_');
411
+            if ($dialectStart !== false) {
412
+                $localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
413
+            }
414
+            if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
415
+                $localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
416
+            }
417
+        }
418
+
419
+        return $localizedSkeletonTemplatePath;
420
+    }
421 421
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -112,14 +112,14 @@  discard block
 block discarded – undo
112 112
 
113 113
 	public function listCreators(): array {
114 114
 		$types = $this->getTypes();
115
-		usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
115
+		usort($types, function(TemplateFileCreator $a, TemplateFileCreator $b) {
116 116
 			return $a->getOrder() - $b->getOrder();
117 117
 		});
118 118
 		return $types;
119 119
 	}
120 120
 
121 121
 	public function listTemplates(): array {
122
-		return array_values(array_map(function (TemplateFileCreator $entry) {
122
+		return array_values(array_map(function(TemplateFileCreator $entry) {
123 123
 			return array_merge($entry->jsonSerialize(), [
124 124
 				'templates' => $this->getTemplateFiles($entry)
125 125
 			]);
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 			if ($templateType === 'user' && $templateId !== '') {
163 163
 				$template = $userFolder->get($templateId);
164 164
 			} else {
165
-				$matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
165
+				$matchingProvider = array_filter($this->getRegisteredProviders(), function(ICustomTemplateProvider $provider) use ($templateType) {
166 166
 					return $templateType === get_class($provider);
167 167
 				});
168 168
 				$provider = array_shift($matchingProvider);
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 
264 264
 		$matchedTemplates = array_filter(
265 265
 			array_merge($providerTemplates, $userTemplates),
266
-			function (Template $template) use ($fileId) {
266
+			function(Template $template) use ($fileId) {
267 267
 				return $template->jsonSerialize()['fileid'] === $fileId;
268 268
 			});
269 269
 
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 
274 274
 		$this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($matchedTemplates, true));
275 275
 
276
-		return array_values(array_map(function (Template $template) {
276
+		return array_values(array_map(function(Template $template) {
277 277
 			return $template->jsonSerialize()['fields'] ?? [];
278 278
 		}, $matchedTemplates));
279 279
 	}
@@ -321,8 +321,8 @@  discard block
 block discarded – undo
321 321
 			$this->userId = $userId;
322 322
 		}
323 323
 
324
-		$defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
325
-		$defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
324
+		$defaultSkeletonDirectory = \OC::$SERVERROOT.'/core/skeleton';
325
+		$defaultTemplateDirectory = \OC::$SERVERROOT.'/core/skeleton/Templates';
326 326
 		$skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
327 327
 		$skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
328 328
 		$isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		try {
338 338
 			$l10n = $this->l10nFactory->get('lib', $userLang);
339 339
 			$userFolder = $this->rootFolder->getUserFolder($this->userId);
340
-			$userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
340
+			$userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')).'/';
341 341
 
342 342
 			// Initial user setup without a provided path
343 343
 			if ($path === null) {
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 					if (!$userFolder->nodeExists('Templates')) {
347 347
 						return '';
348 348
 					}
349
-					$newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
349
+					$newPath = Filesystem::normalizePath($userFolder->getPath().'/'.$userTemplatePath);
350 350
 					if ($newPath !== $userFolder->get('Templates')->getPath()) {
351 351
 						$userFolder->get('Templates')->move($newPath);
352 352
 					}
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 			}
386 386
 
387 387
 			if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
388
-				$localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
388
+				$localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath.'/Templates', $userLang);
389 389
 				if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
390 390
 					\OC_Util::copyr($localizedSkeletonPath, $folder);
391 391
 					$userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
 			$this->setTemplatePath($path ?? '');
398 398
 			return $this->getTemplatePath();
399 399
 		} catch (\Throwable $e) {
400
-			$this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
400
+			$this->logger->error('Failed to initialize templates directory to user language '.$userLang.' for '.$userId, ['app' => 'files_templates', 'exception' => $e]);
401 401
 		}
402 402
 		$this->setTemplatePath('');
403 403
 		return $this->getTemplatePath();
Please login to merge, or discard this patch.
apps/files/lib/Controller/TemplateController.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -28,101 +28,101 @@
 block discarded – undo
28 28
  * @psalm-import-type FilesTemplate from ResponseDefinitions
29 29
  */
30 30
 class TemplateController extends OCSController {
31
-	public function __construct(
32
-		$appName,
33
-		IRequest $request,
34
-		protected ITemplateManager $templateManager,
35
-	) {
36
-		parent::__construct($appName, $request);
37
-	}
31
+    public function __construct(
32
+        $appName,
33
+        IRequest $request,
34
+        protected ITemplateManager $templateManager,
35
+    ) {
36
+        parent::__construct($appName, $request);
37
+    }
38 38
 
39
-	/**
40
-	 * List the available templates
41
-	 *
42
-	 * @return DataResponse<Http::STATUS_OK, list<FilesTemplateFileCreatorWithTemplates>, array{}>
43
-	 *
44
-	 * 200: Available templates returned
45
-	 */
46
-	#[NoAdminRequired]
47
-	public function list(): DataResponse {
48
-		/* Convert embedded Template instances to arrays to match return type */
49
-		return new DataResponse(array_map(static function (array $templateFileCreator) {
50
-			$templateFileCreator['templates'] = array_map(static fn (Template $template) => $template->jsonSerialize(), $templateFileCreator['templates']);
51
-			return $templateFileCreator;
52
-		}, $this->templateManager->listTemplates()));
53
-	}
39
+    /**
40
+     * List the available templates
41
+     *
42
+     * @return DataResponse<Http::STATUS_OK, list<FilesTemplateFileCreatorWithTemplates>, array{}>
43
+     *
44
+     * 200: Available templates returned
45
+     */
46
+    #[NoAdminRequired]
47
+    public function list(): DataResponse {
48
+        /* Convert embedded Template instances to arrays to match return type */
49
+        return new DataResponse(array_map(static function (array $templateFileCreator) {
50
+            $templateFileCreator['templates'] = array_map(static fn (Template $template) => $template->jsonSerialize(), $templateFileCreator['templates']);
51
+            return $templateFileCreator;
52
+        }, $this->templateManager->listTemplates()));
53
+    }
54 54
 
55
-	/**
56
-	 * List the fields for the template specified by the given file ID
57
-	 *
58
-	 * @param int $fileId File ID of the template
59
-	 * @return DataResponse<Http::STATUS_OK, array<string, FilesTemplateField>, array{}>
60
-	 *
61
-	 * 200: Fields returned
62
-	 */
63
-	#[NoAdminRequired]
64
-	public function listTemplateFields(int $fileId): DataResponse {
65
-		$fields = $this->templateManager->listTemplateFields($fileId);
55
+    /**
56
+     * List the fields for the template specified by the given file ID
57
+     *
58
+     * @param int $fileId File ID of the template
59
+     * @return DataResponse<Http::STATUS_OK, array<string, FilesTemplateField>, array{}>
60
+     *
61
+     * 200: Fields returned
62
+     */
63
+    #[NoAdminRequired]
64
+    public function listTemplateFields(int $fileId): DataResponse {
65
+        $fields = $this->templateManager->listTemplateFields($fileId);
66 66
 
67
-		return new DataResponse(
68
-			array_merge([], ...$fields),
69
-			Http::STATUS_OK
70
-		);
71
-	}
67
+        return new DataResponse(
68
+            array_merge([], ...$fields),
69
+            Http::STATUS_OK
70
+        );
71
+    }
72 72
 
73
-	/**
74
-	 * Create a template
75
-	 *
76
-	 * @param string $filePath Path of the file
77
-	 * @param string $templatePath Name of the template
78
-	 * @param string $templateType Type of the template
79
-	 * @param list<FilesTemplateField> $templateFields Fields of the template
80
-	 *
81
-	 * @return DataResponse<Http::STATUS_OK, FilesTemplateFile, array{}>
82
-	 * @throws OCSForbiddenException Creating template is not allowed
83
-	 *
84
-	 * 200: Template created successfully
85
-	 */
86
-	#[NoAdminRequired]
87
-	public function create(
88
-		string $filePath,
89
-		string $templatePath = '',
90
-		string $templateType = 'user',
91
-		array $templateFields = [],
92
-	): DataResponse {
93
-		try {
94
-			return new DataResponse($this->templateManager->createFromTemplate(
95
-				$filePath,
96
-				$templatePath,
97
-				$templateType,
98
-				$templateFields));
99
-		} catch (GenericFileException $e) {
100
-			throw new OCSForbiddenException($e->getMessage());
101
-		}
102
-	}
73
+    /**
74
+     * Create a template
75
+     *
76
+     * @param string $filePath Path of the file
77
+     * @param string $templatePath Name of the template
78
+     * @param string $templateType Type of the template
79
+     * @param list<FilesTemplateField> $templateFields Fields of the template
80
+     *
81
+     * @return DataResponse<Http::STATUS_OK, FilesTemplateFile, array{}>
82
+     * @throws OCSForbiddenException Creating template is not allowed
83
+     *
84
+     * 200: Template created successfully
85
+     */
86
+    #[NoAdminRequired]
87
+    public function create(
88
+        string $filePath,
89
+        string $templatePath = '',
90
+        string $templateType = 'user',
91
+        array $templateFields = [],
92
+    ): DataResponse {
93
+        try {
94
+            return new DataResponse($this->templateManager->createFromTemplate(
95
+                $filePath,
96
+                $templatePath,
97
+                $templateType,
98
+                $templateFields));
99
+        } catch (GenericFileException $e) {
100
+            throw new OCSForbiddenException($e->getMessage());
101
+        }
102
+    }
103 103
 
104
-	/**
105
-	 * Initialize the template directory
106
-	 *
107
-	 * @param string $templatePath Path of the template directory
108
-	 * @param bool $copySystemTemplates Whether to copy the system templates to the template directory
109
-	 *
110
-	 * @return DataResponse<Http::STATUS_OK, array{template_path: string, templates: list<FilesTemplateFileCreator>}, array{}>
111
-	 * @throws OCSForbiddenException Initializing the template directory is not allowed
112
-	 *
113
-	 * 200: Template directory initialized successfully
114
-	 */
115
-	#[NoAdminRequired]
116
-	public function path(string $templatePath = '', bool $copySystemTemplates = false) {
117
-		try {
118
-			/** @var string $templatePath */
119
-			$templatePath = $this->templateManager->initializeTemplateDirectory($templatePath, null, $copySystemTemplates);
120
-			return new DataResponse([
121
-				'template_path' => $templatePath,
122
-				'templates' => array_values(array_map(fn (TemplateFileCreator $creator) => $creator->jsonSerialize(), $this->templateManager->listCreators())),
123
-			]);
124
-		} catch (\Exception $e) {
125
-			throw new OCSForbiddenException($e->getMessage());
126
-		}
127
-	}
104
+    /**
105
+     * Initialize the template directory
106
+     *
107
+     * @param string $templatePath Path of the template directory
108
+     * @param bool $copySystemTemplates Whether to copy the system templates to the template directory
109
+     *
110
+     * @return DataResponse<Http::STATUS_OK, array{template_path: string, templates: list<FilesTemplateFileCreator>}, array{}>
111
+     * @throws OCSForbiddenException Initializing the template directory is not allowed
112
+     *
113
+     * 200: Template directory initialized successfully
114
+     */
115
+    #[NoAdminRequired]
116
+    public function path(string $templatePath = '', bool $copySystemTemplates = false) {
117
+        try {
118
+            /** @var string $templatePath */
119
+            $templatePath = $this->templateManager->initializeTemplateDirectory($templatePath, null, $copySystemTemplates);
120
+            return new DataResponse([
121
+                'template_path' => $templatePath,
122
+                'templates' => array_values(array_map(fn (TemplateFileCreator $creator) => $creator->jsonSerialize(), $this->templateManager->listCreators())),
123
+            ]);
124
+        } catch (\Exception $e) {
125
+            throw new OCSForbiddenException($e->getMessage());
126
+        }
127
+    }
128 128
 }
Please login to merge, or discard this patch.
apps/files/appinfo/routes.php 1 patch
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -10,173 +10,173 @@
 block discarded – undo
10 10
 namespace OCA\Files\AppInfo;
11 11
 
12 12
 return [
13
-	'routes' => [
14
-		[
15
-			'name' => 'view#index',
16
-			'url' => '/',
17
-			'verb' => 'GET',
18
-		],
19
-		[
20
-			'name' => 'View#showFile',
21
-			'url' => '/f/{fileid}',
22
-			'verb' => 'GET',
23
-			'root' => '',
24
-		],
25
-		[
26
-			'name' => 'Api#getThumbnail',
27
-			'url' => '/api/v1/thumbnail/{x}/{y}/{file}',
28
-			'verb' => 'GET',
29
-			'requirements' => ['file' => '.+']
30
-		],
31
-		[
32
-			'name' => 'Api#updateFileTags',
33
-			'url' => '/api/v1/files/{path}',
34
-			'verb' => 'POST',
35
-			'requirements' => ['path' => '.+'],
36
-		],
37
-		[
38
-			'name' => 'Api#getRecentFiles',
39
-			'url' => '/api/v1/recent/',
40
-			'verb' => 'GET'
41
-		],
42
-		[
43
-			'name' => 'Api#getStorageStats',
44
-			'url' => '/api/v1/stats',
45
-			'verb' => 'GET'
46
-		],
47
-		[
48
-			'name' => 'Api#setViewConfig',
49
-			'url' => '/api/v1/views/{view}/{key}',
50
-			'verb' => 'PUT'
51
-		],
52
-		[
53
-			'name' => 'Api#setViewConfig',
54
-			'url' => '/api/v1/views',
55
-			'verb' => 'PUT'
56
-		],
57
-		[
58
-			'name' => 'Api#getViewConfigs',
59
-			'url' => '/api/v1/views',
60
-			'verb' => 'GET'
61
-		],
62
-		[
63
-			'name' => 'Api#setConfig',
64
-			'url' => '/api/v1/config/{key}',
65
-			'verb' => 'PUT'
66
-		],
67
-		[
68
-			'name' => 'Api#getConfigs',
69
-			'url' => '/api/v1/configs',
70
-			'verb' => 'GET'
71
-		],
72
-		[
73
-			'name' => 'Api#showHiddenFiles',
74
-			'url' => '/api/v1/showhidden',
75
-			'verb' => 'POST'
76
-		],
77
-		[
78
-			'name' => 'Api#cropImagePreviews',
79
-			'url' => '/api/v1/cropimagepreviews',
80
-			'verb' => 'POST'
81
-		],
82
-		[
83
-			'name' => 'Api#showGridView',
84
-			'url' => '/api/v1/showgridview',
85
-			'verb' => 'POST'
86
-		],
87
-		[
88
-			'name' => 'Api#getGridView',
89
-			'url' => '/api/v1/showgridview',
90
-			'verb' => 'GET'
91
-		],
92
-		[
93
-			'name' => 'DirectEditingView#edit',
94
-			'url' => '/directEditing/{token}',
95
-			'verb' => 'GET'
96
-		],
97
-		[
98
-			'name' => 'Api#serviceWorker',
99
-			'url' => '/preview-service-worker.js',
100
-			'verb' => 'GET'
101
-		],
102
-		[
103
-			'name' => 'view#indexView',
104
-			'url' => '/{view}',
105
-			'verb' => 'GET',
106
-		],
107
-		[
108
-			'name' => 'view#indexViewFileid',
109
-			'url' => '/{view}/{fileid}',
110
-			'verb' => 'GET',
111
-		],
112
-	],
113
-	'ocs' => [
114
-		[
115
-			'name' => 'DirectEditing#info',
116
-			'url' => '/api/v1/directEditing',
117
-			'verb' => 'GET'
118
-		],
119
-		[
120
-			'name' => 'DirectEditing#templates',
121
-			'url' => '/api/v1/directEditing/templates/{editorId}/{creatorId}',
122
-			'verb' => 'GET'
123
-		],
124
-		[
125
-			'name' => 'DirectEditing#open',
126
-			'url' => '/api/v1/directEditing/open',
127
-			'verb' => 'POST'
128
-		],
129
-		[
130
-			'name' => 'DirectEditing#create',
131
-			'url' => '/api/v1/directEditing/create',
132
-			'verb' => 'POST'
133
-		],
134
-		[
135
-			'name' => 'Template#list',
136
-			'url' => '/api/v1/templates',
137
-			'verb' => 'GET'
138
-		],
139
-		[
140
-			'name' => 'Template#listTemplateFields',
141
-			'url' => '/api/v1/templates/fields/{fileId}',
142
-			'verb' => 'GET'
143
-		],
144
-		[
145
-			'name' => 'Template#create',
146
-			'url' => '/api/v1/templates/create',
147
-			'verb' => 'POST'
148
-		],
149
-		[
150
-			'name' => 'Template#path',
151
-			'url' => '/api/v1/templates/path',
152
-			'verb' => 'POST'
153
-		],
154
-		[
155
-			'name' => 'TransferOwnership#transfer',
156
-			'url' => '/api/v1/transferownership',
157
-			'verb' => 'POST',
158
-		],
159
-		[
160
-			'name' => 'TransferOwnership#accept',
161
-			'url' => '/api/v1/transferownership/{id}',
162
-			'verb' => 'POST',
163
-		],
164
-		[
165
-			'name' => 'TransferOwnership#reject',
166
-			'url' => '/api/v1/transferownership/{id}',
167
-			'verb' => 'DELETE',
168
-		],
169
-		[
170
-			/** @see OpenLocalEditorController::create() */
171
-			'name' => 'OpenLocalEditor#create',
172
-			'url' => '/api/v1/openlocaleditor',
173
-			'verb' => 'POST',
174
-		],
175
-		[
176
-			/** @see OpenLocalEditorController::validate() */
177
-			'name' => 'OpenLocalEditor#validate',
178
-			'url' => '/api/v1/openlocaleditor/{token}',
179
-			'verb' => 'POST',
180
-		],
181
-	]
13
+    'routes' => [
14
+        [
15
+            'name' => 'view#index',
16
+            'url' => '/',
17
+            'verb' => 'GET',
18
+        ],
19
+        [
20
+            'name' => 'View#showFile',
21
+            'url' => '/f/{fileid}',
22
+            'verb' => 'GET',
23
+            'root' => '',
24
+        ],
25
+        [
26
+            'name' => 'Api#getThumbnail',
27
+            'url' => '/api/v1/thumbnail/{x}/{y}/{file}',
28
+            'verb' => 'GET',
29
+            'requirements' => ['file' => '.+']
30
+        ],
31
+        [
32
+            'name' => 'Api#updateFileTags',
33
+            'url' => '/api/v1/files/{path}',
34
+            'verb' => 'POST',
35
+            'requirements' => ['path' => '.+'],
36
+        ],
37
+        [
38
+            'name' => 'Api#getRecentFiles',
39
+            'url' => '/api/v1/recent/',
40
+            'verb' => 'GET'
41
+        ],
42
+        [
43
+            'name' => 'Api#getStorageStats',
44
+            'url' => '/api/v1/stats',
45
+            'verb' => 'GET'
46
+        ],
47
+        [
48
+            'name' => 'Api#setViewConfig',
49
+            'url' => '/api/v1/views/{view}/{key}',
50
+            'verb' => 'PUT'
51
+        ],
52
+        [
53
+            'name' => 'Api#setViewConfig',
54
+            'url' => '/api/v1/views',
55
+            'verb' => 'PUT'
56
+        ],
57
+        [
58
+            'name' => 'Api#getViewConfigs',
59
+            'url' => '/api/v1/views',
60
+            'verb' => 'GET'
61
+        ],
62
+        [
63
+            'name' => 'Api#setConfig',
64
+            'url' => '/api/v1/config/{key}',
65
+            'verb' => 'PUT'
66
+        ],
67
+        [
68
+            'name' => 'Api#getConfigs',
69
+            'url' => '/api/v1/configs',
70
+            'verb' => 'GET'
71
+        ],
72
+        [
73
+            'name' => 'Api#showHiddenFiles',
74
+            'url' => '/api/v1/showhidden',
75
+            'verb' => 'POST'
76
+        ],
77
+        [
78
+            'name' => 'Api#cropImagePreviews',
79
+            'url' => '/api/v1/cropimagepreviews',
80
+            'verb' => 'POST'
81
+        ],
82
+        [
83
+            'name' => 'Api#showGridView',
84
+            'url' => '/api/v1/showgridview',
85
+            'verb' => 'POST'
86
+        ],
87
+        [
88
+            'name' => 'Api#getGridView',
89
+            'url' => '/api/v1/showgridview',
90
+            'verb' => 'GET'
91
+        ],
92
+        [
93
+            'name' => 'DirectEditingView#edit',
94
+            'url' => '/directEditing/{token}',
95
+            'verb' => 'GET'
96
+        ],
97
+        [
98
+            'name' => 'Api#serviceWorker',
99
+            'url' => '/preview-service-worker.js',
100
+            'verb' => 'GET'
101
+        ],
102
+        [
103
+            'name' => 'view#indexView',
104
+            'url' => '/{view}',
105
+            'verb' => 'GET',
106
+        ],
107
+        [
108
+            'name' => 'view#indexViewFileid',
109
+            'url' => '/{view}/{fileid}',
110
+            'verb' => 'GET',
111
+        ],
112
+    ],
113
+    'ocs' => [
114
+        [
115
+            'name' => 'DirectEditing#info',
116
+            'url' => '/api/v1/directEditing',
117
+            'verb' => 'GET'
118
+        ],
119
+        [
120
+            'name' => 'DirectEditing#templates',
121
+            'url' => '/api/v1/directEditing/templates/{editorId}/{creatorId}',
122
+            'verb' => 'GET'
123
+        ],
124
+        [
125
+            'name' => 'DirectEditing#open',
126
+            'url' => '/api/v1/directEditing/open',
127
+            'verb' => 'POST'
128
+        ],
129
+        [
130
+            'name' => 'DirectEditing#create',
131
+            'url' => '/api/v1/directEditing/create',
132
+            'verb' => 'POST'
133
+        ],
134
+        [
135
+            'name' => 'Template#list',
136
+            'url' => '/api/v1/templates',
137
+            'verb' => 'GET'
138
+        ],
139
+        [
140
+            'name' => 'Template#listTemplateFields',
141
+            'url' => '/api/v1/templates/fields/{fileId}',
142
+            'verb' => 'GET'
143
+        ],
144
+        [
145
+            'name' => 'Template#create',
146
+            'url' => '/api/v1/templates/create',
147
+            'verb' => 'POST'
148
+        ],
149
+        [
150
+            'name' => 'Template#path',
151
+            'url' => '/api/v1/templates/path',
152
+            'verb' => 'POST'
153
+        ],
154
+        [
155
+            'name' => 'TransferOwnership#transfer',
156
+            'url' => '/api/v1/transferownership',
157
+            'verb' => 'POST',
158
+        ],
159
+        [
160
+            'name' => 'TransferOwnership#accept',
161
+            'url' => '/api/v1/transferownership/{id}',
162
+            'verb' => 'POST',
163
+        ],
164
+        [
165
+            'name' => 'TransferOwnership#reject',
166
+            'url' => '/api/v1/transferownership/{id}',
167
+            'verb' => 'DELETE',
168
+        ],
169
+        [
170
+            /** @see OpenLocalEditorController::create() */
171
+            'name' => 'OpenLocalEditor#create',
172
+            'url' => '/api/v1/openlocaleditor',
173
+            'verb' => 'POST',
174
+        ],
175
+        [
176
+            /** @see OpenLocalEditorController::validate() */
177
+            'name' => 'OpenLocalEditor#validate',
178
+            'url' => '/api/v1/openlocaleditor/{token}',
179
+            'verb' => 'POST',
180
+        ],
181
+    ]
182 182
 ];
Please login to merge, or discard this patch.