Passed
Push — master ( acacb4...0e29dc )
by John
16:32 queued 12s
created
lib/private/Preview/Generator.php 2 patches
Indentation   +517 added lines, -517 removed lines patch added patch discarded remove patch
@@ -46,535 +46,535 @@
 block discarded – undo
46 46
 
47 47
 class Generator {
48 48
 
49
-	/** @var IPreview */
50
-	private $previewManager;
51
-	/** @var IConfig */
52
-	private $config;
53
-	/** @var IAppData */
54
-	private $appData;
55
-	/** @var GeneratorHelper */
56
-	private $helper;
57
-	/** @var EventDispatcherInterface */
58
-	private $eventDispatcher;
59
-
60
-	/**
61
-	 * @param IConfig $config
62
-	 * @param IPreview $previewManager
63
-	 * @param IAppData $appData
64
-	 * @param GeneratorHelper $helper
65
-	 * @param EventDispatcherInterface $eventDispatcher
66
-	 */
67
-	public function __construct(
68
-		IConfig $config,
69
-		IPreview $previewManager,
70
-		IAppData $appData,
71
-		GeneratorHelper $helper,
72
-		EventDispatcherInterface $eventDispatcher
73
-	) {
74
-		$this->config = $config;
75
-		$this->previewManager = $previewManager;
76
-		$this->appData = $appData;
77
-		$this->helper = $helper;
78
-		$this->eventDispatcher = $eventDispatcher;
79
-	}
80
-
81
-	/**
82
-	 * Returns a preview of a file
83
-	 *
84
-	 * The cache is searched first and if nothing usable was found then a preview is
85
-	 * generated by one of the providers
86
-	 *
87
-	 * @param File $file
88
-	 * @param int $width
89
-	 * @param int $height
90
-	 * @param bool $crop
91
-	 * @param string $mode
92
-	 * @param string $mimeType
93
-	 * @return ISimpleFile
94
-	 * @throws NotFoundException
95
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
96
-	 */
97
-	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
98
-		$specification = [
99
-			'width' => $width,
100
-			'height' => $height,
101
-			'crop' => $crop,
102
-			'mode' => $mode,
103
-		];
104
-		$this->eventDispatcher->dispatch(
105
-			IPreview::EVENT,
106
-			new GenericEvent($file, $specification)
107
-		);
108
-
109
-		// since we only ask for one preview, and the generate method return the last one it created, it returns the one we want
110
-		return $this->generatePreviews($file, [$specification], $mimeType);
111
-	}
112
-
113
-	/**
114
-	 * Generates previews of a file
115
-	 *
116
-	 * @param File $file
117
-	 * @param array $specifications
118
-	 * @param string $mimeType
119
-	 * @return ISimpleFile the last preview that was generated
120
-	 * @throws NotFoundException
121
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
122
-	 */
123
-	public function generatePreviews(File $file, array $specifications, $mimeType = null) {
124
-		//Make sure that we can read the file
125
-		if (!$file->isReadable()) {
126
-			throw new NotFoundException('Cannot read file');
127
-		}
128
-
129
-		if ($mimeType === null) {
130
-			$mimeType = $file->getMimeType();
131
-		}
132
-
133
-		$previewFolder = $this->getPreviewFolder($file);
134
-
135
-		$previewVersion = '';
136
-		if ($file instanceof IVersionedPreviewFile) {
137
-			$previewVersion = $file->getPreviewVersion() . '-';
138
-		}
139
-
140
-		// If imaginary is enabled, and we request a small thumbnail,
141
-		// let's not generate the max preview for performance reasons
142
-		if (count($specifications) === 1
143
-			&& ($specifications[0]['width'] <= 256 || $specifications[0]['height'] <= 256)
144
-			&& preg_match(Imaginary::supportedMimeTypes(), $mimeType)
145
-			&& $this->config->getSystemValueString('preview_imaginary_url', 'invalid') !== 'invalid') {
146
-			$crop = $specifications[0]['crop'] ?? false;
147
-			$preview = $this->getSmallImagePreview($previewFolder, $file, $mimeType, $previewVersion, $crop);
148
-
149
-			if ($preview->getSize() === 0) {
150
-				$preview->delete();
151
-				throw new NotFoundException('Cached preview size 0, invalid!');
152
-			}
153
-
154
-			return $preview;
155
-		}
156
-
157
-		// Get the max preview and infer the max preview sizes from that
158
-		$maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType, $previewVersion);
159
-		$maxPreviewImage = null; // only load the image when we need it
160
-		if ($maxPreview->getSize() === 0) {
161
-			$maxPreview->delete();
162
-			throw new NotFoundException('Max preview size 0, invalid!');
163
-		}
164
-
165
-		[$maxWidth, $maxHeight] = $this->getPreviewSize($maxPreview, $previewVersion);
166
-
167
-		$preview = null;
168
-
169
-		foreach ($specifications as $specification) {
170
-			$width = $specification['width'] ?? -1;
171
-			$height = $specification['height'] ?? -1;
172
-			$crop = $specification['crop'] ?? false;
173
-			$mode = $specification['mode'] ?? IPreview::MODE_FILL;
174
-
175
-			// If both width and height are -1 we just want the max preview
176
-			if ($width === -1 && $height === -1) {
177
-				$width = $maxWidth;
178
-				$height = $maxHeight;
179
-			}
180
-
181
-			// Calculate the preview size
182
-			[$width, $height] = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
183
-
184
-			// No need to generate a preview that is just the max preview
185
-			if ($width === $maxWidth && $height === $maxHeight) {
186
-				// ensure correct return value if this was the last one
187
-				$preview = $maxPreview;
188
-				continue;
189
-			}
190
-
191
-			// Try to get a cached preview. Else generate (and store) one
192
-			try {
193
-				try {
194
-					$preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType(), $previewVersion);
195
-				} catch (NotFoundException $e) {
196
-					if (!$this->previewManager->isMimeSupported($mimeType)) {
197
-						throw new NotFoundException();
198
-					}
199
-
200
-					if ($maxPreviewImage === null) {
201
-						$maxPreviewImage = $this->helper->getImage($maxPreview);
202
-					}
203
-
204
-					$preview = $this->generatePreview($previewFolder, $maxPreviewImage, $width, $height, $crop, $maxWidth, $maxHeight, $previewVersion);
205
-				}
206
-			} catch (\InvalidArgumentException $e) {
207
-				throw new NotFoundException("", 0, $e);
208
-			}
209
-
210
-			if ($preview->getSize() === 0) {
211
-				$preview->delete();
212
-				throw new NotFoundException('Cached preview size 0, invalid!');
213
-			}
214
-		}
215
-
216
-		// Free memory being used by the embedded image resource.  Without this the image is kept in memory indefinitely.
217
-		// Garbage Collection does NOT free this memory.  We have to do it ourselves.
218
-		if ($maxPreviewImage instanceof \OC_Image) {
219
-			$maxPreviewImage->destroy();
220
-		}
221
-
222
-		return $preview;
223
-	}
224
-
225
-	/**
226
-	 * Generate a small image straight away without generating a max preview first
227
-	 * Preview generated is 256x256
228
-	 */
229
-	private function getSmallImagePreview(ISimpleFolder $previewFolder, File $file, string $mimeType, string $prefix, bool $crop) {
230
-		$nodes = $previewFolder->getDirectoryListing();
231
-
232
-		foreach ($nodes as $node) {
233
-			$name = $node->getName();
234
-			if (($prefix === '' || strpos($name, $prefix) === 0)
235
-				&& (str_starts_with($name, '256-256-crop') && $crop || str_starts_with($name, '256-256') && !$crop)) {
236
-				return $node;
237
-			}
238
-		}
239
-
240
-		$previewProviders = $this->previewManager->getProviders();
241
-		foreach ($previewProviders as $supportedMimeType => $providers) {
242
-			// Filter out providers that does not support this mime
243
-			if (!preg_match($supportedMimeType, $mimeType)) {
244
-				continue;
245
-			}
246
-
247
-			foreach ($providers as $providerClosure) {
248
-				$provider = $this->helper->getProvider($providerClosure);
249
-				if (!($provider instanceof IProviderV2)) {
250
-					continue;
251
-				}
252
-
253
-				if (!$provider->isAvailable($file)) {
254
-					continue;
255
-				}
256
-
257
-				$preview = $this->helper->getThumbnail($provider, $file, 256, 256, true);
258
-
259
-				if (!($preview instanceof IImage)) {
260
-					continue;
261
-				}
262
-
263
-				// Try to get the extension.
264
-				try {
265
-					$ext = $this->getExtention($preview->dataMimeType());
266
-				} catch (\InvalidArgumentException $e) {
267
-					// Just continue to the next iteration if this preview doesn't have a valid mimetype
268
-					continue;
269
-				}
270
-
271
-				$path = $this->generatePath(256, 256, $crop, $preview->dataMimeType(), $prefix);
272
-				try {
273
-					$file = $previewFolder->newFile($path);
274
-					if ($preview instanceof IStreamImage) {
275
-						$file->putContent($preview->resource());
276
-					} else {
277
-						$file->putContent($preview->data());
278
-					}
279
-				} catch (NotPermittedException $e) {
280
-					throw new NotFoundException();
281
-				}
282
-
283
-				return $file;
284
-			}
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * @param ISimpleFolder $previewFolder
290
-	 * @param File $file
291
-	 * @param string $mimeType
292
-	 * @param string $prefix
293
-	 * @return ISimpleFile
294
-	 * @throws NotFoundException
295
-	 */
296
-	private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType, $prefix) {
297
-		$nodes = $previewFolder->getDirectoryListing();
298
-
299
-		foreach ($nodes as $node) {
300
-			$name = $node->getName();
301
-			if (($prefix === '' || strpos($name, $prefix) === 0) && strpos($name, 'max')) {
302
-				return $node;
303
-			}
304
-		}
305
-
306
-		$previewProviders = $this->previewManager->getProviders();
307
-		foreach ($previewProviders as $supportedMimeType => $providers) {
308
-			// Filter out providers that does not support this mime
309
-			if (!preg_match($supportedMimeType, $mimeType)) {
310
-				continue;
311
-			}
312
-
313
-			foreach ($providers as $providerClosure) {
314
-				$provider = $this->helper->getProvider($providerClosure);
315
-				if (!($provider instanceof IProviderV2)) {
316
-					continue;
317
-				}
318
-
319
-				if (!$provider->isAvailable($file)) {
320
-					continue;
321
-				}
322
-
323
-				$maxWidth = $this->config->getSystemValueInt('preview_max_x', 4096);
324
-				$maxHeight = $this->config->getSystemValueInt('preview_max_y', 4096);
325
-
326
-				$preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
327
-
328
-				if (!($preview instanceof IImage)) {
329
-					continue;
330
-				}
331
-
332
-				// Try to get the extention.
333
-				try {
334
-					$ext = $this->getExtention($preview->dataMimeType());
335
-				} catch (\InvalidArgumentException $e) {
336
-					// Just continue to the next iteration if this preview doesn't have a valid mimetype
337
-					continue;
338
-				}
339
-
340
-				$path = $prefix . (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
341
-				try {
342
-					$file = $previewFolder->newFile($path);
343
-					if ($preview instanceof IStreamImage) {
344
-						$file->putContent($preview->resource());
345
-					} else {
346
-						$file->putContent($preview->data());
347
-					}
348
-				} catch (NotPermittedException $e) {
349
-					throw new NotFoundException();
350
-				}
351
-
352
-				return $file;
353
-			}
354
-		}
355
-
356
-		throw new NotFoundException();
357
-	}
358
-
359
-	/**
360
-	 * @param ISimpleFile $file
361
-	 * @param string $prefix
362
-	 * @return int[]
363
-	 */
364
-	private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
365
-		$size = explode('-', substr($file->getName(), strlen($prefix)));
366
-		return [(int)$size[0], (int)$size[1]];
367
-	}
368
-
369
-	/**
370
-	 * @param int $width
371
-	 * @param int $height
372
-	 * @param bool $crop
373
-	 * @param string $mimeType
374
-	 * @param string $prefix
375
-	 * @return string
376
-	 */
377
-	private function generatePath($width, $height, $crop, $mimeType, $prefix) {
378
-		$path = $prefix . (string)$width . '-' . (string)$height;
379
-		if ($crop) {
380
-			$path .= '-crop';
381
-		}
382
-
383
-		$ext = $this->getExtention($mimeType);
384
-		$path .= '.' . $ext;
385
-		return $path;
386
-	}
387
-
388
-
389
-	/**
390
-	 * @param int $width
391
-	 * @param int $height
392
-	 * @param bool $crop
393
-	 * @param string $mode
394
-	 * @param int $maxWidth
395
-	 * @param int $maxHeight
396
-	 * @return int[]
397
-	 */
398
-	private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
399
-
400
-		/*
49
+    /** @var IPreview */
50
+    private $previewManager;
51
+    /** @var IConfig */
52
+    private $config;
53
+    /** @var IAppData */
54
+    private $appData;
55
+    /** @var GeneratorHelper */
56
+    private $helper;
57
+    /** @var EventDispatcherInterface */
58
+    private $eventDispatcher;
59
+
60
+    /**
61
+     * @param IConfig $config
62
+     * @param IPreview $previewManager
63
+     * @param IAppData $appData
64
+     * @param GeneratorHelper $helper
65
+     * @param EventDispatcherInterface $eventDispatcher
66
+     */
67
+    public function __construct(
68
+        IConfig $config,
69
+        IPreview $previewManager,
70
+        IAppData $appData,
71
+        GeneratorHelper $helper,
72
+        EventDispatcherInterface $eventDispatcher
73
+    ) {
74
+        $this->config = $config;
75
+        $this->previewManager = $previewManager;
76
+        $this->appData = $appData;
77
+        $this->helper = $helper;
78
+        $this->eventDispatcher = $eventDispatcher;
79
+    }
80
+
81
+    /**
82
+     * Returns a preview of a file
83
+     *
84
+     * The cache is searched first and if nothing usable was found then a preview is
85
+     * generated by one of the providers
86
+     *
87
+     * @param File $file
88
+     * @param int $width
89
+     * @param int $height
90
+     * @param bool $crop
91
+     * @param string $mode
92
+     * @param string $mimeType
93
+     * @return ISimpleFile
94
+     * @throws NotFoundException
95
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
96
+     */
97
+    public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
98
+        $specification = [
99
+            'width' => $width,
100
+            'height' => $height,
101
+            'crop' => $crop,
102
+            'mode' => $mode,
103
+        ];
104
+        $this->eventDispatcher->dispatch(
105
+            IPreview::EVENT,
106
+            new GenericEvent($file, $specification)
107
+        );
108
+
109
+        // since we only ask for one preview, and the generate method return the last one it created, it returns the one we want
110
+        return $this->generatePreviews($file, [$specification], $mimeType);
111
+    }
112
+
113
+    /**
114
+     * Generates previews of a file
115
+     *
116
+     * @param File $file
117
+     * @param array $specifications
118
+     * @param string $mimeType
119
+     * @return ISimpleFile the last preview that was generated
120
+     * @throws NotFoundException
121
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
122
+     */
123
+    public function generatePreviews(File $file, array $specifications, $mimeType = null) {
124
+        //Make sure that we can read the file
125
+        if (!$file->isReadable()) {
126
+            throw new NotFoundException('Cannot read file');
127
+        }
128
+
129
+        if ($mimeType === null) {
130
+            $mimeType = $file->getMimeType();
131
+        }
132
+
133
+        $previewFolder = $this->getPreviewFolder($file);
134
+
135
+        $previewVersion = '';
136
+        if ($file instanceof IVersionedPreviewFile) {
137
+            $previewVersion = $file->getPreviewVersion() . '-';
138
+        }
139
+
140
+        // If imaginary is enabled, and we request a small thumbnail,
141
+        // let's not generate the max preview for performance reasons
142
+        if (count($specifications) === 1
143
+            && ($specifications[0]['width'] <= 256 || $specifications[0]['height'] <= 256)
144
+            && preg_match(Imaginary::supportedMimeTypes(), $mimeType)
145
+            && $this->config->getSystemValueString('preview_imaginary_url', 'invalid') !== 'invalid') {
146
+            $crop = $specifications[0]['crop'] ?? false;
147
+            $preview = $this->getSmallImagePreview($previewFolder, $file, $mimeType, $previewVersion, $crop);
148
+
149
+            if ($preview->getSize() === 0) {
150
+                $preview->delete();
151
+                throw new NotFoundException('Cached preview size 0, invalid!');
152
+            }
153
+
154
+            return $preview;
155
+        }
156
+
157
+        // Get the max preview and infer the max preview sizes from that
158
+        $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType, $previewVersion);
159
+        $maxPreviewImage = null; // only load the image when we need it
160
+        if ($maxPreview->getSize() === 0) {
161
+            $maxPreview->delete();
162
+            throw new NotFoundException('Max preview size 0, invalid!');
163
+        }
164
+
165
+        [$maxWidth, $maxHeight] = $this->getPreviewSize($maxPreview, $previewVersion);
166
+
167
+        $preview = null;
168
+
169
+        foreach ($specifications as $specification) {
170
+            $width = $specification['width'] ?? -1;
171
+            $height = $specification['height'] ?? -1;
172
+            $crop = $specification['crop'] ?? false;
173
+            $mode = $specification['mode'] ?? IPreview::MODE_FILL;
174
+
175
+            // If both width and height are -1 we just want the max preview
176
+            if ($width === -1 && $height === -1) {
177
+                $width = $maxWidth;
178
+                $height = $maxHeight;
179
+            }
180
+
181
+            // Calculate the preview size
182
+            [$width, $height] = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
183
+
184
+            // No need to generate a preview that is just the max preview
185
+            if ($width === $maxWidth && $height === $maxHeight) {
186
+                // ensure correct return value if this was the last one
187
+                $preview = $maxPreview;
188
+                continue;
189
+            }
190
+
191
+            // Try to get a cached preview. Else generate (and store) one
192
+            try {
193
+                try {
194
+                    $preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType(), $previewVersion);
195
+                } catch (NotFoundException $e) {
196
+                    if (!$this->previewManager->isMimeSupported($mimeType)) {
197
+                        throw new NotFoundException();
198
+                    }
199
+
200
+                    if ($maxPreviewImage === null) {
201
+                        $maxPreviewImage = $this->helper->getImage($maxPreview);
202
+                    }
203
+
204
+                    $preview = $this->generatePreview($previewFolder, $maxPreviewImage, $width, $height, $crop, $maxWidth, $maxHeight, $previewVersion);
205
+                }
206
+            } catch (\InvalidArgumentException $e) {
207
+                throw new NotFoundException("", 0, $e);
208
+            }
209
+
210
+            if ($preview->getSize() === 0) {
211
+                $preview->delete();
212
+                throw new NotFoundException('Cached preview size 0, invalid!');
213
+            }
214
+        }
215
+
216
+        // Free memory being used by the embedded image resource.  Without this the image is kept in memory indefinitely.
217
+        // Garbage Collection does NOT free this memory.  We have to do it ourselves.
218
+        if ($maxPreviewImage instanceof \OC_Image) {
219
+            $maxPreviewImage->destroy();
220
+        }
221
+
222
+        return $preview;
223
+    }
224
+
225
+    /**
226
+     * Generate a small image straight away without generating a max preview first
227
+     * Preview generated is 256x256
228
+     */
229
+    private function getSmallImagePreview(ISimpleFolder $previewFolder, File $file, string $mimeType, string $prefix, bool $crop) {
230
+        $nodes = $previewFolder->getDirectoryListing();
231
+
232
+        foreach ($nodes as $node) {
233
+            $name = $node->getName();
234
+            if (($prefix === '' || strpos($name, $prefix) === 0)
235
+                && (str_starts_with($name, '256-256-crop') && $crop || str_starts_with($name, '256-256') && !$crop)) {
236
+                return $node;
237
+            }
238
+        }
239
+
240
+        $previewProviders = $this->previewManager->getProviders();
241
+        foreach ($previewProviders as $supportedMimeType => $providers) {
242
+            // Filter out providers that does not support this mime
243
+            if (!preg_match($supportedMimeType, $mimeType)) {
244
+                continue;
245
+            }
246
+
247
+            foreach ($providers as $providerClosure) {
248
+                $provider = $this->helper->getProvider($providerClosure);
249
+                if (!($provider instanceof IProviderV2)) {
250
+                    continue;
251
+                }
252
+
253
+                if (!$provider->isAvailable($file)) {
254
+                    continue;
255
+                }
256
+
257
+                $preview = $this->helper->getThumbnail($provider, $file, 256, 256, true);
258
+
259
+                if (!($preview instanceof IImage)) {
260
+                    continue;
261
+                }
262
+
263
+                // Try to get the extension.
264
+                try {
265
+                    $ext = $this->getExtention($preview->dataMimeType());
266
+                } catch (\InvalidArgumentException $e) {
267
+                    // Just continue to the next iteration if this preview doesn't have a valid mimetype
268
+                    continue;
269
+                }
270
+
271
+                $path = $this->generatePath(256, 256, $crop, $preview->dataMimeType(), $prefix);
272
+                try {
273
+                    $file = $previewFolder->newFile($path);
274
+                    if ($preview instanceof IStreamImage) {
275
+                        $file->putContent($preview->resource());
276
+                    } else {
277
+                        $file->putContent($preview->data());
278
+                    }
279
+                } catch (NotPermittedException $e) {
280
+                    throw new NotFoundException();
281
+                }
282
+
283
+                return $file;
284
+            }
285
+        }
286
+    }
287
+
288
+    /**
289
+     * @param ISimpleFolder $previewFolder
290
+     * @param File $file
291
+     * @param string $mimeType
292
+     * @param string $prefix
293
+     * @return ISimpleFile
294
+     * @throws NotFoundException
295
+     */
296
+    private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType, $prefix) {
297
+        $nodes = $previewFolder->getDirectoryListing();
298
+
299
+        foreach ($nodes as $node) {
300
+            $name = $node->getName();
301
+            if (($prefix === '' || strpos($name, $prefix) === 0) && strpos($name, 'max')) {
302
+                return $node;
303
+            }
304
+        }
305
+
306
+        $previewProviders = $this->previewManager->getProviders();
307
+        foreach ($previewProviders as $supportedMimeType => $providers) {
308
+            // Filter out providers that does not support this mime
309
+            if (!preg_match($supportedMimeType, $mimeType)) {
310
+                continue;
311
+            }
312
+
313
+            foreach ($providers as $providerClosure) {
314
+                $provider = $this->helper->getProvider($providerClosure);
315
+                if (!($provider instanceof IProviderV2)) {
316
+                    continue;
317
+                }
318
+
319
+                if (!$provider->isAvailable($file)) {
320
+                    continue;
321
+                }
322
+
323
+                $maxWidth = $this->config->getSystemValueInt('preview_max_x', 4096);
324
+                $maxHeight = $this->config->getSystemValueInt('preview_max_y', 4096);
325
+
326
+                $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
327
+
328
+                if (!($preview instanceof IImage)) {
329
+                    continue;
330
+                }
331
+
332
+                // Try to get the extention.
333
+                try {
334
+                    $ext = $this->getExtention($preview->dataMimeType());
335
+                } catch (\InvalidArgumentException $e) {
336
+                    // Just continue to the next iteration if this preview doesn't have a valid mimetype
337
+                    continue;
338
+                }
339
+
340
+                $path = $prefix . (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
341
+                try {
342
+                    $file = $previewFolder->newFile($path);
343
+                    if ($preview instanceof IStreamImage) {
344
+                        $file->putContent($preview->resource());
345
+                    } else {
346
+                        $file->putContent($preview->data());
347
+                    }
348
+                } catch (NotPermittedException $e) {
349
+                    throw new NotFoundException();
350
+                }
351
+
352
+                return $file;
353
+            }
354
+        }
355
+
356
+        throw new NotFoundException();
357
+    }
358
+
359
+    /**
360
+     * @param ISimpleFile $file
361
+     * @param string $prefix
362
+     * @return int[]
363
+     */
364
+    private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
365
+        $size = explode('-', substr($file->getName(), strlen($prefix)));
366
+        return [(int)$size[0], (int)$size[1]];
367
+    }
368
+
369
+    /**
370
+     * @param int $width
371
+     * @param int $height
372
+     * @param bool $crop
373
+     * @param string $mimeType
374
+     * @param string $prefix
375
+     * @return string
376
+     */
377
+    private function generatePath($width, $height, $crop, $mimeType, $prefix) {
378
+        $path = $prefix . (string)$width . '-' . (string)$height;
379
+        if ($crop) {
380
+            $path .= '-crop';
381
+        }
382
+
383
+        $ext = $this->getExtention($mimeType);
384
+        $path .= '.' . $ext;
385
+        return $path;
386
+    }
387
+
388
+
389
+    /**
390
+     * @param int $width
391
+     * @param int $height
392
+     * @param bool $crop
393
+     * @param string $mode
394
+     * @param int $maxWidth
395
+     * @param int $maxHeight
396
+     * @return int[]
397
+     */
398
+    private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
399
+
400
+        /*
401 401
 		 * If we are not cropping we have to make sure the requested image
402 402
 		 * respects the aspect ratio of the original.
403 403
 		 */
404
-		if (!$crop) {
405
-			$ratio = $maxHeight / $maxWidth;
404
+        if (!$crop) {
405
+            $ratio = $maxHeight / $maxWidth;
406 406
 
407
-			if ($width === -1) {
408
-				$width = $height / $ratio;
409
-			}
410
-			if ($height === -1) {
411
-				$height = $width * $ratio;
412
-			}
407
+            if ($width === -1) {
408
+                $width = $height / $ratio;
409
+            }
410
+            if ($height === -1) {
411
+                $height = $width * $ratio;
412
+            }
413 413
 
414
-			$ratioH = $height / $maxHeight;
415
-			$ratioW = $width / $maxWidth;
414
+            $ratioH = $height / $maxHeight;
415
+            $ratioW = $width / $maxWidth;
416 416
 
417
-			/*
417
+            /*
418 418
 			 * Fill means that the $height and $width are the max
419 419
 			 * Cover means min.
420 420
 			 */
421
-			if ($mode === IPreview::MODE_FILL) {
422
-				if ($ratioH > $ratioW) {
423
-					$height = $width * $ratio;
424
-				} else {
425
-					$width = $height / $ratio;
426
-				}
427
-			} elseif ($mode === IPreview::MODE_COVER) {
428
-				if ($ratioH > $ratioW) {
429
-					$width = $height / $ratio;
430
-				} else {
431
-					$height = $width * $ratio;
432
-				}
433
-			}
434
-		}
435
-
436
-		if ($height !== $maxHeight && $width !== $maxWidth) {
437
-			/*
421
+            if ($mode === IPreview::MODE_FILL) {
422
+                if ($ratioH > $ratioW) {
423
+                    $height = $width * $ratio;
424
+                } else {
425
+                    $width = $height / $ratio;
426
+                }
427
+            } elseif ($mode === IPreview::MODE_COVER) {
428
+                if ($ratioH > $ratioW) {
429
+                    $width = $height / $ratio;
430
+                } else {
431
+                    $height = $width * $ratio;
432
+                }
433
+            }
434
+        }
435
+
436
+        if ($height !== $maxHeight && $width !== $maxWidth) {
437
+            /*
438 438
 			 * Scale to the nearest power of four
439 439
 			 */
440
-			$pow4height = 4 ** ceil(log($height) / log(4));
441
-			$pow4width = 4 ** ceil(log($width) / log(4));
442
-
443
-			// Minimum size is 64
444
-			$pow4height = max($pow4height, 64);
445
-			$pow4width = max($pow4width, 64);
446
-
447
-			$ratioH = $height / $pow4height;
448
-			$ratioW = $width / $pow4width;
449
-
450
-			if ($ratioH < $ratioW) {
451
-				$width = $pow4width;
452
-				$height /= $ratioW;
453
-			} else {
454
-				$height = $pow4height;
455
-				$width /= $ratioH;
456
-			}
457
-		}
458
-
459
-		/*
440
+            $pow4height = 4 ** ceil(log($height) / log(4));
441
+            $pow4width = 4 ** ceil(log($width) / log(4));
442
+
443
+            // Minimum size is 64
444
+            $pow4height = max($pow4height, 64);
445
+            $pow4width = max($pow4width, 64);
446
+
447
+            $ratioH = $height / $pow4height;
448
+            $ratioW = $width / $pow4width;
449
+
450
+            if ($ratioH < $ratioW) {
451
+                $width = $pow4width;
452
+                $height /= $ratioW;
453
+            } else {
454
+                $height = $pow4height;
455
+                $width /= $ratioH;
456
+            }
457
+        }
458
+
459
+        /*
460 460
 		 * Make sure the requested height and width fall within the max
461 461
 		 * of the preview.
462 462
 		 */
463
-		if ($height > $maxHeight) {
464
-			$ratio = $height / $maxHeight;
465
-			$height = $maxHeight;
466
-			$width /= $ratio;
467
-		}
468
-		if ($width > $maxWidth) {
469
-			$ratio = $width / $maxWidth;
470
-			$width = $maxWidth;
471
-			$height /= $ratio;
472
-		}
473
-
474
-		return [(int)round($width), (int)round($height)];
475
-	}
476
-
477
-	/**
478
-	 * @param ISimpleFolder $previewFolder
479
-	 * @param ISimpleFile $maxPreview
480
-	 * @param int $width
481
-	 * @param int $height
482
-	 * @param bool $crop
483
-	 * @param int $maxWidth
484
-	 * @param int $maxHeight
485
-	 * @param string $prefix
486
-	 * @return ISimpleFile
487
-	 * @throws NotFoundException
488
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
489
-	 */
490
-	private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
491
-		$preview = $maxPreview;
492
-		if (!$preview->valid()) {
493
-			throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
494
-		}
495
-
496
-		if ($crop) {
497
-			if ($height !== $preview->height() && $width !== $preview->width()) {
498
-				//Resize
499
-				$widthR = $preview->width() / $width;
500
-				$heightR = $preview->height() / $height;
501
-
502
-				if ($widthR > $heightR) {
503
-					$scaleH = $height;
504
-					$scaleW = $maxWidth / $heightR;
505
-				} else {
506
-					$scaleH = $maxHeight / $widthR;
507
-					$scaleW = $width;
508
-				}
509
-				$preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
510
-			}
511
-			$cropX = (int)floor(abs($width - $preview->width()) * 0.5);
512
-			$cropY = (int)floor(abs($height - $preview->height()) * 0.5);
513
-			$preview = $preview->cropCopy($cropX, $cropY, $width, $height);
514
-		} else {
515
-			$preview = $maxPreview->resizeCopy(max($width, $height));
516
-		}
517
-
518
-
519
-		$path = $this->generatePath($width, $height, $crop, $preview->dataMimeType(), $prefix);
520
-		try {
521
-			$file = $previewFolder->newFile($path);
522
-			$file->putContent($preview->data());
523
-		} catch (NotPermittedException $e) {
524
-			throw new NotFoundException();
525
-		}
526
-
527
-		return $file;
528
-	}
529
-
530
-	/**
531
-	 * @param ISimpleFolder $previewFolder
532
-	 * @param int $width
533
-	 * @param int $height
534
-	 * @param bool $crop
535
-	 * @param string $mimeType
536
-	 * @param string $prefix
537
-	 * @return ISimpleFile
538
-	 *
539
-	 * @throws NotFoundException
540
-	 */
541
-	private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType, $prefix) {
542
-		$path = $this->generatePath($width, $height, $crop, $mimeType, $prefix);
543
-
544
-		return $previewFolder->getFile($path);
545
-	}
546
-
547
-	/**
548
-	 * Get the specific preview folder for this file
549
-	 *
550
-	 * @param File $file
551
-	 * @return ISimpleFolder
552
-	 */
553
-	private function getPreviewFolder(File $file) {
554
-		try {
555
-			$folder = $this->appData->getFolder($file->getId());
556
-		} catch (NotFoundException $e) {
557
-			$folder = $this->appData->newFolder($file->getId());
558
-		}
559
-
560
-		return $folder;
561
-	}
562
-
563
-	/**
564
-	 * @param string $mimeType
565
-	 * @return null|string
566
-	 * @throws \InvalidArgumentException
567
-	 */
568
-	private function getExtention($mimeType) {
569
-		switch ($mimeType) {
570
-			case 'image/png':
571
-				return 'png';
572
-			case 'image/jpeg':
573
-				return 'jpg';
574
-			case 'image/gif':
575
-				return 'gif';
576
-			default:
577
-				throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
578
-		}
579
-	}
463
+        if ($height > $maxHeight) {
464
+            $ratio = $height / $maxHeight;
465
+            $height = $maxHeight;
466
+            $width /= $ratio;
467
+        }
468
+        if ($width > $maxWidth) {
469
+            $ratio = $width / $maxWidth;
470
+            $width = $maxWidth;
471
+            $height /= $ratio;
472
+        }
473
+
474
+        return [(int)round($width), (int)round($height)];
475
+    }
476
+
477
+    /**
478
+     * @param ISimpleFolder $previewFolder
479
+     * @param ISimpleFile $maxPreview
480
+     * @param int $width
481
+     * @param int $height
482
+     * @param bool $crop
483
+     * @param int $maxWidth
484
+     * @param int $maxHeight
485
+     * @param string $prefix
486
+     * @return ISimpleFile
487
+     * @throws NotFoundException
488
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
489
+     */
490
+    private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
491
+        $preview = $maxPreview;
492
+        if (!$preview->valid()) {
493
+            throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
494
+        }
495
+
496
+        if ($crop) {
497
+            if ($height !== $preview->height() && $width !== $preview->width()) {
498
+                //Resize
499
+                $widthR = $preview->width() / $width;
500
+                $heightR = $preview->height() / $height;
501
+
502
+                if ($widthR > $heightR) {
503
+                    $scaleH = $height;
504
+                    $scaleW = $maxWidth / $heightR;
505
+                } else {
506
+                    $scaleH = $maxHeight / $widthR;
507
+                    $scaleW = $width;
508
+                }
509
+                $preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
510
+            }
511
+            $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
512
+            $cropY = (int)floor(abs($height - $preview->height()) * 0.5);
513
+            $preview = $preview->cropCopy($cropX, $cropY, $width, $height);
514
+        } else {
515
+            $preview = $maxPreview->resizeCopy(max($width, $height));
516
+        }
517
+
518
+
519
+        $path = $this->generatePath($width, $height, $crop, $preview->dataMimeType(), $prefix);
520
+        try {
521
+            $file = $previewFolder->newFile($path);
522
+            $file->putContent($preview->data());
523
+        } catch (NotPermittedException $e) {
524
+            throw new NotFoundException();
525
+        }
526
+
527
+        return $file;
528
+    }
529
+
530
+    /**
531
+     * @param ISimpleFolder $previewFolder
532
+     * @param int $width
533
+     * @param int $height
534
+     * @param bool $crop
535
+     * @param string $mimeType
536
+     * @param string $prefix
537
+     * @return ISimpleFile
538
+     *
539
+     * @throws NotFoundException
540
+     */
541
+    private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType, $prefix) {
542
+        $path = $this->generatePath($width, $height, $crop, $mimeType, $prefix);
543
+
544
+        return $previewFolder->getFile($path);
545
+    }
546
+
547
+    /**
548
+     * Get the specific preview folder for this file
549
+     *
550
+     * @param File $file
551
+     * @return ISimpleFolder
552
+     */
553
+    private function getPreviewFolder(File $file) {
554
+        try {
555
+            $folder = $this->appData->getFolder($file->getId());
556
+        } catch (NotFoundException $e) {
557
+            $folder = $this->appData->newFolder($file->getId());
558
+        }
559
+
560
+        return $folder;
561
+    }
562
+
563
+    /**
564
+     * @param string $mimeType
565
+     * @return null|string
566
+     * @throws \InvalidArgumentException
567
+     */
568
+    private function getExtention($mimeType) {
569
+        switch ($mimeType) {
570
+            case 'image/png':
571
+                return 'png';
572
+            case 'image/jpeg':
573
+                return 'jpg';
574
+            case 'image/gif':
575
+                return 'gif';
576
+            default:
577
+                throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
578
+        }
579
+    }
580 580
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 
135 135
 		$previewVersion = '';
136 136
 		if ($file instanceof IVersionedPreviewFile) {
137
-			$previewVersion = $file->getPreviewVersion() . '-';
137
+			$previewVersion = $file->getPreviewVersion().'-';
138 138
 		}
139 139
 
140 140
 		// If imaginary is enabled, and we request a small thumbnail,
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 					continue;
338 338
 				}
339 339
 
340
-				$path = $prefix . (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
340
+				$path = $prefix.(string) $preview->width().'-'.(string) $preview->height().'-max.'.$ext;
341 341
 				try {
342 342
 					$file = $previewFolder->newFile($path);
343 343
 					if ($preview instanceof IStreamImage) {
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 	 */
364 364
 	private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
365 365
 		$size = explode('-', substr($file->getName(), strlen($prefix)));
366
-		return [(int)$size[0], (int)$size[1]];
366
+		return [(int) $size[0], (int) $size[1]];
367 367
 	}
368 368
 
369 369
 	/**
@@ -375,13 +375,13 @@  discard block
 block discarded – undo
375 375
 	 * @return string
376 376
 	 */
377 377
 	private function generatePath($width, $height, $crop, $mimeType, $prefix) {
378
-		$path = $prefix . (string)$width . '-' . (string)$height;
378
+		$path = $prefix.(string) $width.'-'.(string) $height;
379 379
 		if ($crop) {
380 380
 			$path .= '-crop';
381 381
 		}
382 382
 
383 383
 		$ext = $this->getExtention($mimeType);
384
-		$path .= '.' . $ext;
384
+		$path .= '.'.$ext;
385 385
 		return $path;
386 386
 	}
387 387
 
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 			$height /= $ratio;
472 472
 		}
473 473
 
474
-		return [(int)round($width), (int)round($height)];
474
+		return [(int) round($width), (int) round($height)];
475 475
 	}
476 476
 
477 477
 	/**
@@ -506,10 +506,10 @@  discard block
 block discarded – undo
506 506
 					$scaleH = $maxHeight / $widthR;
507 507
 					$scaleW = $width;
508 508
 				}
509
-				$preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
509
+				$preview = $preview->preciseResizeCopy((int) round($scaleW), (int) round($scaleH));
510 510
 			}
511
-			$cropX = (int)floor(abs($width - $preview->width()) * 0.5);
512
-			$cropY = (int)floor(abs($height - $preview->height()) * 0.5);
511
+			$cropX = (int) floor(abs($width - $preview->width()) * 0.5);
512
+			$cropY = (int) floor(abs($height - $preview->height()) * 0.5);
513 513
 			$preview = $preview->cropCopy($cropX, $cropY, $width, $height);
514 514
 		} else {
515 515
 			$preview = $maxPreview->resizeCopy(max($width, $height));
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
 			case 'image/gif':
575 575
 				return 'gif';
576 576
 			default:
577
-				throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
577
+				throw new \InvalidArgumentException('Not a valid mimetype: "'.$mimeType.'"');
578 578
 		}
579 579
 	}
580 580
 }
Please login to merge, or discard this patch.