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