Passed
Push — master ( 335af0...d4a44d )
by Roeland
16:33 queued 10s
created
lib/private/Preview/OpenDocument.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,10 +23,10 @@
 block discarded – undo
23 23
 
24 24
 //.odt, .ott, .oth, .odm, .odg, .otg, .odp, .otp, .ods, .ots, .odc, .odf, .odb, .odi, .oxt
25 25
 class OpenDocument extends Office {
26
-	/**
27
-	 * {@inheritDoc}
28
-	 */
29
-	public function getMimeType(): string {
30
-		return '/application\/vnd.oasis.opendocument.*/';
31
-	}
26
+    /**
27
+     * {@inheritDoc}
28
+     */
29
+    public function getMimeType(): string {
30
+        return '/application\/vnd.oasis.opendocument.*/';
31
+    }
32 32
 }
Please login to merge, or discard this patch.
lib/private/Preview/Generator.php 1 patch
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -42,403 +42,403 @@
 block discarded – undo
42 42
 
43 43
 class Generator {
44 44
 
45
-	/** @var IPreview */
46
-	private $previewManager;
47
-	/** @var IConfig */
48
-	private $config;
49
-	/** @var IAppData */
50
-	private $appData;
51
-	/** @var GeneratorHelper */
52
-	private $helper;
53
-	/** @var EventDispatcherInterface */
54
-	private $eventDispatcher;
55
-
56
-	/**
57
-	 * @param IConfig $config
58
-	 * @param IPreview $previewManager
59
-	 * @param IAppData $appData
60
-	 * @param GeneratorHelper $helper
61
-	 * @param EventDispatcherInterface $eventDispatcher
62
-	 */
63
-	public function __construct(
64
-		IConfig $config,
65
-		IPreview $previewManager,
66
-		IAppData $appData,
67
-		GeneratorHelper $helper,
68
-		EventDispatcherInterface $eventDispatcher
69
-	) {
70
-		$this->config = $config;
71
-		$this->previewManager = $previewManager;
72
-		$this->appData = $appData;
73
-		$this->helper = $helper;
74
-		$this->eventDispatcher = $eventDispatcher;
75
-	}
76
-
77
-	/**
78
-	 * Returns a preview of a file
79
-	 *
80
-	 * The cache is searched first and if nothing usable was found then a preview is
81
-	 * generated by one of the providers
82
-	 *
83
-	 * @param File $file
84
-	 * @param int $width
85
-	 * @param int $height
86
-	 * @param bool $crop
87
-	 * @param string $mode
88
-	 * @param string $mimeType
89
-	 * @return ISimpleFile
90
-	 * @throws NotFoundException
91
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
92
-	 */
93
-	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
94
-		//Make sure that we can read the file
95
-		if (!$file->isReadable()) {
96
-			throw new NotFoundException('Cannot read file');
97
-		}
98
-
99
-
100
-		$this->eventDispatcher->dispatch(
101
-			IPreview::EVENT,
102
-			new GenericEvent($file,[
103
-				'width' => $width,
104
-				'height' => $height,
105
-				'crop' => $crop,
106
-				'mode' => $mode
107
-			])
108
-		);
109
-
110
-		if ($mimeType === null) {
111
-			$mimeType = $file->getMimeType();
112
-		}
113
-		if (!$this->previewManager->isMimeSupported($mimeType)) {
114
-			throw new NotFoundException();
115
-		}
116
-
117
-		$previewFolder = $this->getPreviewFolder($file);
118
-
119
-		// Get the max preview and infer the max preview sizes from that
120
-		$maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
121
-		if ($maxPreview->getSize() === 0) {
122
-			$maxPreview->delete();
123
-			throw new NotFoundException('Max preview size 0, invalid!');
124
-		}
125
-
126
-		list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
127
-
128
-		// If both width and heigth are -1 we just want the max preview
129
-		if ($width === -1 && $height === -1) {
130
-			$width = $maxWidth;
131
-			$height = $maxHeight;
132
-		}
133
-
134
-		// Calculate the preview size
135
-		list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
136
-
137
-		// No need to generate a preview that is just the max preview
138
-		if ($width === $maxWidth && $height === $maxHeight) {
139
-			return $maxPreview;
140
-		}
141
-
142
-		// Try to get a cached preview. Else generate (and store) one
143
-		try {
144
-			try {
145
-				$preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType());
146
-			} catch (NotFoundException $e) {
147
-				$preview = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
148
-			}
149
-		} catch (\InvalidArgumentException $e) {
150
-			throw new NotFoundException();
151
-		}
152
-
153
-		if ($preview->getSize() === 0) {
154
-			$preview->delete();
155
-			throw new NotFoundException('Cached preview size 0, invalid!');
156
-		}
157
-
158
-		return $preview;
159
-	}
160
-
161
-	/**
162
-	 * @param ISimpleFolder $previewFolder
163
-	 * @param File $file
164
-	 * @param string $mimeType
165
-	 * @return ISimpleFile
166
-	 * @throws NotFoundException
167
-	 */
168
-	private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
169
-		$nodes = $previewFolder->getDirectoryListing();
170
-
171
-		foreach ($nodes as $node) {
172
-			if (strpos($node->getName(), 'max')) {
173
-				return $node;
174
-			}
175
-		}
176
-
177
-		$previewProviders = $this->previewManager->getProviders();
178
-		foreach ($previewProviders as $supportedMimeType => $providers) {
179
-			if (!preg_match($supportedMimeType, $mimeType)) {
180
-				continue;
181
-			}
182
-
183
-			foreach ($providers as $providerClosure) {
184
-				$provider = $this->helper->getProvider($providerClosure);
185
-				if (!($provider instanceof IProviderV2)) {
186
-					continue;
187
-				}
188
-
189
-				if (!$provider->isAvailable($file)) {
190
-					continue;
191
-				}
192
-
193
-				$maxWidth = (int)$this->config->getSystemValue('preview_max_x', 4096);
194
-				$maxHeight = (int)$this->config->getSystemValue('preview_max_y', 4096);
195
-
196
-				$preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
197
-
198
-				if (!($preview instanceof IImage)) {
199
-					continue;
200
-				}
201
-
202
-				// Try to get the extention.
203
-				try {
204
-					$ext = $this->getExtention($preview->dataMimeType());
205
-				} catch (\InvalidArgumentException $e) {
206
-					// Just continue to the next iteration if this preview doesn't have a valid mimetype
207
-					continue;
208
-				}
209
-
210
-				$path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
211
-				try {
212
-					$file = $previewFolder->newFile($path);
213
-					$file->putContent($preview->data());
214
-				} catch (NotPermittedException $e) {
215
-					throw new NotFoundException();
216
-				}
217
-
218
-				return $file;
219
-			}
220
-		}
221
-
222
-		throw new NotFoundException();
223
-	}
224
-
225
-	/**
226
-	 * @param ISimpleFile $file
227
-	 * @return int[]
228
-	 */
229
-	private function getPreviewSize(ISimpleFile $file) {
230
-		$size = explode('-', $file->getName());
231
-		return [(int)$size[0], (int)$size[1]];
232
-	}
233
-
234
-	/**
235
-	 * @param int $width
236
-	 * @param int $height
237
-	 * @param bool $crop
238
-	 * @param string $mimeType
239
-	 * @return string
240
-	 */
241
-	private function generatePath($width, $height, $crop, $mimeType) {
242
-		$path = (string)$width . '-' . (string)$height;
243
-		if ($crop) {
244
-			$path .= '-crop';
245
-		}
246
-
247
-		$ext = $this->getExtention($mimeType);
248
-		$path .= '.' . $ext;
249
-		return $path;
250
-	}
251
-
252
-
253
-
254
-	/**
255
-	 * @param int $width
256
-	 * @param int $height
257
-	 * @param bool $crop
258
-	 * @param string $mode
259
-	 * @param int $maxWidth
260
-	 * @param int $maxHeight
261
-	 * @return int[]
262
-	 */
263
-	private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
264
-
265
-		/*
45
+    /** @var IPreview */
46
+    private $previewManager;
47
+    /** @var IConfig */
48
+    private $config;
49
+    /** @var IAppData */
50
+    private $appData;
51
+    /** @var GeneratorHelper */
52
+    private $helper;
53
+    /** @var EventDispatcherInterface */
54
+    private $eventDispatcher;
55
+
56
+    /**
57
+     * @param IConfig $config
58
+     * @param IPreview $previewManager
59
+     * @param IAppData $appData
60
+     * @param GeneratorHelper $helper
61
+     * @param EventDispatcherInterface $eventDispatcher
62
+     */
63
+    public function __construct(
64
+        IConfig $config,
65
+        IPreview $previewManager,
66
+        IAppData $appData,
67
+        GeneratorHelper $helper,
68
+        EventDispatcherInterface $eventDispatcher
69
+    ) {
70
+        $this->config = $config;
71
+        $this->previewManager = $previewManager;
72
+        $this->appData = $appData;
73
+        $this->helper = $helper;
74
+        $this->eventDispatcher = $eventDispatcher;
75
+    }
76
+
77
+    /**
78
+     * Returns a preview of a file
79
+     *
80
+     * The cache is searched first and if nothing usable was found then a preview is
81
+     * generated by one of the providers
82
+     *
83
+     * @param File $file
84
+     * @param int $width
85
+     * @param int $height
86
+     * @param bool $crop
87
+     * @param string $mode
88
+     * @param string $mimeType
89
+     * @return ISimpleFile
90
+     * @throws NotFoundException
91
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
92
+     */
93
+    public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
94
+        //Make sure that we can read the file
95
+        if (!$file->isReadable()) {
96
+            throw new NotFoundException('Cannot read file');
97
+        }
98
+
99
+
100
+        $this->eventDispatcher->dispatch(
101
+            IPreview::EVENT,
102
+            new GenericEvent($file,[
103
+                'width' => $width,
104
+                'height' => $height,
105
+                'crop' => $crop,
106
+                'mode' => $mode
107
+            ])
108
+        );
109
+
110
+        if ($mimeType === null) {
111
+            $mimeType = $file->getMimeType();
112
+        }
113
+        if (!$this->previewManager->isMimeSupported($mimeType)) {
114
+            throw new NotFoundException();
115
+        }
116
+
117
+        $previewFolder = $this->getPreviewFolder($file);
118
+
119
+        // Get the max preview and infer the max preview sizes from that
120
+        $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
121
+        if ($maxPreview->getSize() === 0) {
122
+            $maxPreview->delete();
123
+            throw new NotFoundException('Max preview size 0, invalid!');
124
+        }
125
+
126
+        list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
127
+
128
+        // If both width and heigth are -1 we just want the max preview
129
+        if ($width === -1 && $height === -1) {
130
+            $width = $maxWidth;
131
+            $height = $maxHeight;
132
+        }
133
+
134
+        // Calculate the preview size
135
+        list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
136
+
137
+        // No need to generate a preview that is just the max preview
138
+        if ($width === $maxWidth && $height === $maxHeight) {
139
+            return $maxPreview;
140
+        }
141
+
142
+        // Try to get a cached preview. Else generate (and store) one
143
+        try {
144
+            try {
145
+                $preview = $this->getCachedPreview($previewFolder, $width, $height, $crop, $maxPreview->getMimeType());
146
+            } catch (NotFoundException $e) {
147
+                $preview = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
148
+            }
149
+        } catch (\InvalidArgumentException $e) {
150
+            throw new NotFoundException();
151
+        }
152
+
153
+        if ($preview->getSize() === 0) {
154
+            $preview->delete();
155
+            throw new NotFoundException('Cached preview size 0, invalid!');
156
+        }
157
+
158
+        return $preview;
159
+    }
160
+
161
+    /**
162
+     * @param ISimpleFolder $previewFolder
163
+     * @param File $file
164
+     * @param string $mimeType
165
+     * @return ISimpleFile
166
+     * @throws NotFoundException
167
+     */
168
+    private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
169
+        $nodes = $previewFolder->getDirectoryListing();
170
+
171
+        foreach ($nodes as $node) {
172
+            if (strpos($node->getName(), 'max')) {
173
+                return $node;
174
+            }
175
+        }
176
+
177
+        $previewProviders = $this->previewManager->getProviders();
178
+        foreach ($previewProviders as $supportedMimeType => $providers) {
179
+            if (!preg_match($supportedMimeType, $mimeType)) {
180
+                continue;
181
+            }
182
+
183
+            foreach ($providers as $providerClosure) {
184
+                $provider = $this->helper->getProvider($providerClosure);
185
+                if (!($provider instanceof IProviderV2)) {
186
+                    continue;
187
+                }
188
+
189
+                if (!$provider->isAvailable($file)) {
190
+                    continue;
191
+                }
192
+
193
+                $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 4096);
194
+                $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 4096);
195
+
196
+                $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
197
+
198
+                if (!($preview instanceof IImage)) {
199
+                    continue;
200
+                }
201
+
202
+                // Try to get the extention.
203
+                try {
204
+                    $ext = $this->getExtention($preview->dataMimeType());
205
+                } catch (\InvalidArgumentException $e) {
206
+                    // Just continue to the next iteration if this preview doesn't have a valid mimetype
207
+                    continue;
208
+                }
209
+
210
+                $path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.' . $ext;
211
+                try {
212
+                    $file = $previewFolder->newFile($path);
213
+                    $file->putContent($preview->data());
214
+                } catch (NotPermittedException $e) {
215
+                    throw new NotFoundException();
216
+                }
217
+
218
+                return $file;
219
+            }
220
+        }
221
+
222
+        throw new NotFoundException();
223
+    }
224
+
225
+    /**
226
+     * @param ISimpleFile $file
227
+     * @return int[]
228
+     */
229
+    private function getPreviewSize(ISimpleFile $file) {
230
+        $size = explode('-', $file->getName());
231
+        return [(int)$size[0], (int)$size[1]];
232
+    }
233
+
234
+    /**
235
+     * @param int $width
236
+     * @param int $height
237
+     * @param bool $crop
238
+     * @param string $mimeType
239
+     * @return string
240
+     */
241
+    private function generatePath($width, $height, $crop, $mimeType) {
242
+        $path = (string)$width . '-' . (string)$height;
243
+        if ($crop) {
244
+            $path .= '-crop';
245
+        }
246
+
247
+        $ext = $this->getExtention($mimeType);
248
+        $path .= '.' . $ext;
249
+        return $path;
250
+    }
251
+
252
+
253
+
254
+    /**
255
+     * @param int $width
256
+     * @param int $height
257
+     * @param bool $crop
258
+     * @param string $mode
259
+     * @param int $maxWidth
260
+     * @param int $maxHeight
261
+     * @return int[]
262
+     */
263
+    private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
264
+
265
+        /*
266 266
 		 * If we are not cropping we have to make sure the requested image
267 267
 		 * respects the aspect ratio of the original.
268 268
 		 */
269
-		if (!$crop) {
270
-			$ratio = $maxHeight / $maxWidth;
269
+        if (!$crop) {
270
+            $ratio = $maxHeight / $maxWidth;
271 271
 
272
-			if ($width === -1) {
273
-				$width = $height / $ratio;
274
-			}
275
-			if ($height === -1) {
276
-				$height = $width * $ratio;
277
-			}
272
+            if ($width === -1) {
273
+                $width = $height / $ratio;
274
+            }
275
+            if ($height === -1) {
276
+                $height = $width * $ratio;
277
+            }
278 278
 
279
-			$ratioH = $height / $maxHeight;
280
-			$ratioW = $width / $maxWidth;
279
+            $ratioH = $height / $maxHeight;
280
+            $ratioW = $width / $maxWidth;
281 281
 
282
-			/*
282
+            /*
283 283
 			 * Fill means that the $height and $width are the max
284 284
 			 * Cover means min.
285 285
 			 */
286
-			if ($mode === IPreview::MODE_FILL) {
287
-				if ($ratioH > $ratioW) {
288
-					$height = $width * $ratio;
289
-				} else {
290
-					$width = $height / $ratio;
291
-				}
292
-			} else if ($mode === IPreview::MODE_COVER) {
293
-				if ($ratioH > $ratioW) {
294
-					$width = $height / $ratio;
295
-				} else {
296
-					$height = $width * $ratio;
297
-				}
298
-			}
299
-		}
300
-
301
-		if ($height !== $maxHeight && $width !== $maxWidth) {
302
-			/*
286
+            if ($mode === IPreview::MODE_FILL) {
287
+                if ($ratioH > $ratioW) {
288
+                    $height = $width * $ratio;
289
+                } else {
290
+                    $width = $height / $ratio;
291
+                }
292
+            } else if ($mode === IPreview::MODE_COVER) {
293
+                if ($ratioH > $ratioW) {
294
+                    $width = $height / $ratio;
295
+                } else {
296
+                    $height = $width * $ratio;
297
+                }
298
+            }
299
+        }
300
+
301
+        if ($height !== $maxHeight && $width !== $maxWidth) {
302
+            /*
303 303
 			 * Scale to the nearest power of four
304 304
 			 */
305
-			$pow4height = 4 ** ceil(log($height) / log(4));
306
-			$pow4width = 4 ** ceil(log($width) / log(4));
307
-
308
-			// Minimum size is 64
309
-			$pow4height = max($pow4height, 64);
310
-			$pow4width = max($pow4width, 64);
311
-
312
-			$ratioH = $height / $pow4height;
313
-			$ratioW = $width / $pow4width;
314
-
315
-			if ($ratioH < $ratioW) {
316
-				$width = $pow4width;
317
-				$height /= $ratioW;
318
-			} else {
319
-				$height = $pow4height;
320
-				$width /= $ratioH;
321
-			}
322
-		}
323
-
324
-		/*
305
+            $pow4height = 4 ** ceil(log($height) / log(4));
306
+            $pow4width = 4 ** ceil(log($width) / log(4));
307
+
308
+            // Minimum size is 64
309
+            $pow4height = max($pow4height, 64);
310
+            $pow4width = max($pow4width, 64);
311
+
312
+            $ratioH = $height / $pow4height;
313
+            $ratioW = $width / $pow4width;
314
+
315
+            if ($ratioH < $ratioW) {
316
+                $width = $pow4width;
317
+                $height /= $ratioW;
318
+            } else {
319
+                $height = $pow4height;
320
+                $width /= $ratioH;
321
+            }
322
+        }
323
+
324
+        /*
325 325
  		 * Make sure the requested height and width fall within the max
326 326
  		 * of the preview.
327 327
  		 */
328
-		if ($height > $maxHeight) {
329
-			$ratio = $height / $maxHeight;
330
-			$height = $maxHeight;
331
-			$width /= $ratio;
332
-		}
333
-		if ($width > $maxWidth) {
334
-			$ratio = $width / $maxWidth;
335
-			$width = $maxWidth;
336
-			$height /= $ratio;
337
-		}
338
-
339
-		return [(int)round($width), (int)round($height)];
340
-	}
341
-
342
-	/**
343
-	 * @param ISimpleFolder $previewFolder
344
-	 * @param ISimpleFile $maxPreview
345
-	 * @param int $width
346
-	 * @param int $height
347
-	 * @param bool $crop
348
-	 * @param int $maxWidth
349
-	 * @param int $maxHeight
350
-	 * @return ISimpleFile
351
-	 * @throws NotFoundException
352
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
353
-	 */
354
-	private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
355
-		$preview = $this->helper->getImage($maxPreview);
356
-
357
-		if (!$preview->valid()) {
358
-			throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
359
-		}
360
-
361
-		if ($crop) {
362
-			if ($height !== $preview->height() && $width !== $preview->width()) {
363
-				//Resize
364
-				$widthR = $preview->width() / $width;
365
-				$heightR = $preview->height() / $height;
366
-
367
-				if ($widthR > $heightR) {
368
-					$scaleH = $height;
369
-					$scaleW = $maxWidth / $heightR;
370
-				} else {
371
-					$scaleH = $maxHeight / $widthR;
372
-					$scaleW = $width;
373
-				}
374
-				$preview->preciseResize((int)round($scaleW), (int)round($scaleH));
375
-			}
376
-			$cropX = (int)floor(abs($width - $preview->width()) * 0.5);
377
-			$cropY = 0;
378
-			$preview->crop($cropX, $cropY, $width, $height);
379
-		} else {
380
-			$preview->resize(max($width, $height));
381
-		}
382
-
383
-
384
-		$path = $this->generatePath($width, $height, $crop, $preview->dataMimeType());
385
-		try {
386
-			$file = $previewFolder->newFile($path);
387
-			$file->putContent($preview->data());
388
-		} catch (NotPermittedException $e) {
389
-			throw new NotFoundException();
390
-		}
391
-
392
-		return $file;
393
-	}
394
-
395
-	/**
396
-	 * @param ISimpleFolder $previewFolder
397
-	 * @param int $width
398
-	 * @param int $height
399
-	 * @param bool $crop
400
-	 * @param string $mimeType
401
-	 * @return ISimpleFile
402
-	 *
403
-	 * @throws NotFoundException
404
-	 */
405
-	private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType) {
406
-		$path = $this->generatePath($width, $height, $crop, $mimeType);
407
-
408
-		return $previewFolder->getFile($path);
409
-	}
410
-
411
-	/**
412
-	 * Get the specific preview folder for this file
413
-	 *
414
-	 * @param File $file
415
-	 * @return ISimpleFolder
416
-	 */
417
-	private function getPreviewFolder(File $file) {
418
-		try {
419
-			$folder = $this->appData->getFolder($file->getId());
420
-		} catch (NotFoundException $e) {
421
-			$folder = $this->appData->newFolder($file->getId());
422
-		}
423
-
424
-		return $folder;
425
-	}
426
-
427
-	/**
428
-	 * @param string $mimeType
429
-	 * @return null|string
430
-	 * @throws \InvalidArgumentException
431
-	 */
432
-	private function getExtention($mimeType) {
433
-		switch ($mimeType) {
434
-			case 'image/png':
435
-				return 'png';
436
-			case 'image/jpeg':
437
-				return 'jpg';
438
-			case 'image/gif':
439
-				return 'gif';
440
-			default:
441
-				throw new \InvalidArgumentException('Not a valid mimetype');
442
-		}
443
-	}
328
+        if ($height > $maxHeight) {
329
+            $ratio = $height / $maxHeight;
330
+            $height = $maxHeight;
331
+            $width /= $ratio;
332
+        }
333
+        if ($width > $maxWidth) {
334
+            $ratio = $width / $maxWidth;
335
+            $width = $maxWidth;
336
+            $height /= $ratio;
337
+        }
338
+
339
+        return [(int)round($width), (int)round($height)];
340
+    }
341
+
342
+    /**
343
+     * @param ISimpleFolder $previewFolder
344
+     * @param ISimpleFile $maxPreview
345
+     * @param int $width
346
+     * @param int $height
347
+     * @param bool $crop
348
+     * @param int $maxWidth
349
+     * @param int $maxHeight
350
+     * @return ISimpleFile
351
+     * @throws NotFoundException
352
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
353
+     */
354
+    private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
355
+        $preview = $this->helper->getImage($maxPreview);
356
+
357
+        if (!$preview->valid()) {
358
+            throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
359
+        }
360
+
361
+        if ($crop) {
362
+            if ($height !== $preview->height() && $width !== $preview->width()) {
363
+                //Resize
364
+                $widthR = $preview->width() / $width;
365
+                $heightR = $preview->height() / $height;
366
+
367
+                if ($widthR > $heightR) {
368
+                    $scaleH = $height;
369
+                    $scaleW = $maxWidth / $heightR;
370
+                } else {
371
+                    $scaleH = $maxHeight / $widthR;
372
+                    $scaleW = $width;
373
+                }
374
+                $preview->preciseResize((int)round($scaleW), (int)round($scaleH));
375
+            }
376
+            $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
377
+            $cropY = 0;
378
+            $preview->crop($cropX, $cropY, $width, $height);
379
+        } else {
380
+            $preview->resize(max($width, $height));
381
+        }
382
+
383
+
384
+        $path = $this->generatePath($width, $height, $crop, $preview->dataMimeType());
385
+        try {
386
+            $file = $previewFolder->newFile($path);
387
+            $file->putContent($preview->data());
388
+        } catch (NotPermittedException $e) {
389
+            throw new NotFoundException();
390
+        }
391
+
392
+        return $file;
393
+    }
394
+
395
+    /**
396
+     * @param ISimpleFolder $previewFolder
397
+     * @param int $width
398
+     * @param int $height
399
+     * @param bool $crop
400
+     * @param string $mimeType
401
+     * @return ISimpleFile
402
+     *
403
+     * @throws NotFoundException
404
+     */
405
+    private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop, $mimeType) {
406
+        $path = $this->generatePath($width, $height, $crop, $mimeType);
407
+
408
+        return $previewFolder->getFile($path);
409
+    }
410
+
411
+    /**
412
+     * Get the specific preview folder for this file
413
+     *
414
+     * @param File $file
415
+     * @return ISimpleFolder
416
+     */
417
+    private function getPreviewFolder(File $file) {
418
+        try {
419
+            $folder = $this->appData->getFolder($file->getId());
420
+        } catch (NotFoundException $e) {
421
+            $folder = $this->appData->newFolder($file->getId());
422
+        }
423
+
424
+        return $folder;
425
+    }
426
+
427
+    /**
428
+     * @param string $mimeType
429
+     * @return null|string
430
+     * @throws \InvalidArgumentException
431
+     */
432
+    private function getExtention($mimeType) {
433
+        switch ($mimeType) {
434
+            case 'image/png':
435
+                return 'png';
436
+            case 'image/jpeg':
437
+                return 'jpg';
438
+            case 'image/gif':
439
+                return 'gif';
440
+            default:
441
+                throw new \InvalidArgumentException('Not a valid mimetype');
442
+        }
443
+    }
444 444
 }
Please login to merge, or discard this patch.
lib/private/Preview/MP3.php 2 patches
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -32,38 +32,38 @@
 block discarded – undo
32 32
 use OCP\IImage;
33 33
 
34 34
 class MP3 extends ProviderV2 {
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function getMimeType(): string {
39
-		return '/audio\/mpeg/';
40
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function getMimeType(): string {
39
+        return '/audio\/mpeg/';
40
+    }
41 41
 
42
-	/**
43
-	 * {@inheritDoc}
44
-	 */
45
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
46
-		$getID3 = new ID3Parser();
42
+    /**
43
+     * {@inheritDoc}
44
+     */
45
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
46
+        $getID3 = new ID3Parser();
47 47
 
48
-		$tmpPath = $this->getLocalFile($file);
49
-		$tags = $getID3->analyze($tmpPath);
50
-		$this->cleanTmpFiles();
51
-		$picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null;
52
-		if(is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) {
53
-			$picture = $tags['id3v2']['PIC'][0]['data'];
54
-		}
48
+        $tmpPath = $this->getLocalFile($file);
49
+        $tags = $getID3->analyze($tmpPath);
50
+        $this->cleanTmpFiles();
51
+        $picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null;
52
+        if(is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) {
53
+            $picture = $tags['id3v2']['PIC'][0]['data'];
54
+        }
55 55
 
56
-		if(!is_null($picture)) {
57
-			$image = new \OC_Image();
58
-			$image->loadFromData($picture);
56
+        if(!is_null($picture)) {
57
+            $image = new \OC_Image();
58
+            $image->loadFromData($picture);
59 59
 
60
-			if ($image->valid()) {
61
-				$image->scaleDownToFit($maxX, $maxY);
60
+            if ($image->valid()) {
61
+                $image->scaleDownToFit($maxX, $maxY);
62 62
 
63
-				return $image;
64
-			}
65
-		}
63
+                return $image;
64
+            }
65
+        }
66 66
 
67
-		return null;
68
-	}
67
+        return null;
68
+    }
69 69
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -49,11 +49,11 @@
 block discarded – undo
49 49
 		$tags = $getID3->analyze($tmpPath);
50 50
 		$this->cleanTmpFiles();
51 51
 		$picture = isset($tags['id3v2']['APIC'][0]['data']) ? $tags['id3v2']['APIC'][0]['data'] : null;
52
-		if(is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) {
52
+		if (is_null($picture) && isset($tags['id3v2']['PIC'][0]['data'])) {
53 53
 			$picture = $tags['id3v2']['PIC'][0]['data'];
54 54
 		}
55 55
 
56
-		if(!is_null($picture)) {
56
+		if (!is_null($picture)) {
57 57
 			$image = new \OC_Image();
58 58
 			$image->loadFromData($picture);
59 59
 
Please login to merge, or discard this patch.
lib/private/Preview/TIFF.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -25,10 +25,10 @@
 block discarded – undo
25 25
 
26 26
 //.tiff
27 27
 class TIFF extends Bitmap {
28
-	/**
29
-	 * {@inheritDoc}
30
-	 */
31
-	public function getMimeType(): string {
32
-		return '/image\/tiff/';
33
-	}
28
+    /**
29
+     * {@inheritDoc}
30
+     */
31
+    public function getMimeType(): string {
32
+        return '/image\/tiff/';
33
+    }
34 34
 }
Please login to merge, or discard this patch.
lib/private/Preview/BMP.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,10 +23,10 @@
 block discarded – undo
23 23
 namespace OC\Preview;
24 24
 
25 25
 class BMP extends Image {
26
-	/**
27
-	 * {@inheritDoc}
28
-	 */
29
-	public function getMimeType(): string {
30
-		return '/image\/bmp/';
31
-	}
26
+    /**
27
+     * {@inheritDoc}
28
+     */
29
+    public function getMimeType(): string {
30
+        return '/image\/bmp/';
31
+    }
32 32
 }
Please login to merge, or discard this patch.
lib/private/Preview/TXT.php 2 patches
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -31,74 +31,74 @@
 block discarded – undo
31 31
 use OCP\IImage;
32 32
 
33 33
 class TXT extends ProviderV2 {
34
-	/**
35
-	 * {@inheritDoc}
36
-	 */
37
-	public function getMimeType(): string {
38
-		return '/text\/plain/';
39
-	}
40
-
41
-	/**
42
-	 * {@inheritDoc}
43
-	 */
44
-	public function isAvailable(FileInfo $file): bool {
45
-		return $file->getSize() > 0;
46
-	}
47
-
48
-	/**
49
-	 * {@inheritDoc}
50
-	 */
51
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
52
-		$content = $file->fopen('r');
53
-
54
-		if ($content === false) {
55
-			return null;
56
-		}
57
-
58
-		$content = stream_get_contents($content,3000);
59
-
60
-		//don't create previews of empty text files
61
-		if(trim($content) === '') {
62
-			return null;
63
-		}
64
-
65
-		$lines = preg_split("/\r\n|\n|\r/", $content);
66
-
67
-		// Define text size of text file preview
68
-		$fontSize = $maxX ? (int) ((2 / 32) * $maxX) : 5; //5px
69
-		$lineSize = ceil($fontSize * 1.5);
70
-
71
-		$image = imagecreate($maxX, $maxY);
72
-		imagecolorallocate($image, 255, 255, 255);
73
-		$textColor = imagecolorallocate($image, 0, 0, 0);
74
-
75
-		$fontFile  = __DIR__;
76
-		$fontFile .= '/../../../core';
77
-		$fontFile .= '/fonts/Nunito-Regular.ttf';
78
-
79
-		$canUseTTF = function_exists('imagettftext');
80
-
81
-		foreach($lines as $index => $line) {
82
-			$index = $index + 1;
83
-
84
-			$x = (int) 1;
85
-			$y = (int) ($index * $lineSize);
86
-
87
-			if ($canUseTTF === true) {
88
-				imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $line);
89
-			} else {
90
-				$y -= $fontSize;
91
-				imagestring($image, 1, $x, $y, $line, $textColor);
92
-			}
93
-
94
-			if(($index * $lineSize) >= $maxY) {
95
-				break;
96
-			}
97
-		}
98
-
99
-		$imageObject = new \OC_Image();
100
-		$imageObject->setResource($image);
101
-
102
-		return $imageObject->valid() ? $imageObject : null;
103
-	}
34
+    /**
35
+     * {@inheritDoc}
36
+     */
37
+    public function getMimeType(): string {
38
+        return '/text\/plain/';
39
+    }
40
+
41
+    /**
42
+     * {@inheritDoc}
43
+     */
44
+    public function isAvailable(FileInfo $file): bool {
45
+        return $file->getSize() > 0;
46
+    }
47
+
48
+    /**
49
+     * {@inheritDoc}
50
+     */
51
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
52
+        $content = $file->fopen('r');
53
+
54
+        if ($content === false) {
55
+            return null;
56
+        }
57
+
58
+        $content = stream_get_contents($content,3000);
59
+
60
+        //don't create previews of empty text files
61
+        if(trim($content) === '') {
62
+            return null;
63
+        }
64
+
65
+        $lines = preg_split("/\r\n|\n|\r/", $content);
66
+
67
+        // Define text size of text file preview
68
+        $fontSize = $maxX ? (int) ((2 / 32) * $maxX) : 5; //5px
69
+        $lineSize = ceil($fontSize * 1.5);
70
+
71
+        $image = imagecreate($maxX, $maxY);
72
+        imagecolorallocate($image, 255, 255, 255);
73
+        $textColor = imagecolorallocate($image, 0, 0, 0);
74
+
75
+        $fontFile  = __DIR__;
76
+        $fontFile .= '/../../../core';
77
+        $fontFile .= '/fonts/Nunito-Regular.ttf';
78
+
79
+        $canUseTTF = function_exists('imagettftext');
80
+
81
+        foreach($lines as $index => $line) {
82
+            $index = $index + 1;
83
+
84
+            $x = (int) 1;
85
+            $y = (int) ($index * $lineSize);
86
+
87
+            if ($canUseTTF === true) {
88
+                imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontFile, $line);
89
+            } else {
90
+                $y -= $fontSize;
91
+                imagestring($image, 1, $x, $y, $line, $textColor);
92
+            }
93
+
94
+            if(($index * $lineSize) >= $maxY) {
95
+                break;
96
+            }
97
+        }
98
+
99
+        $imageObject = new \OC_Image();
100
+        $imageObject->setResource($image);
101
+
102
+        return $imageObject->valid() ? $imageObject : null;
103
+    }
104 104
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -55,10 +55,10 @@  discard block
 block discarded – undo
55 55
 			return null;
56 56
 		}
57 57
 
58
-		$content = stream_get_contents($content,3000);
58
+		$content = stream_get_contents($content, 3000);
59 59
 
60 60
 		//don't create previews of empty text files
61
-		if(trim($content) === '') {
61
+		if (trim($content) === '') {
62 62
 			return null;
63 63
 		}
64 64
 
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 
79 79
 		$canUseTTF = function_exists('imagettftext');
80 80
 
81
-		foreach($lines as $index => $line) {
81
+		foreach ($lines as $index => $line) {
82 82
 			$index = $index + 1;
83 83
 
84 84
 			$x = (int) 1;
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 				imagestring($image, 1, $x, $y, $line, $textColor);
92 92
 			}
93 93
 
94
-			if(($index * $lineSize) >= $maxY) {
94
+			if (($index * $lineSize) >= $maxY) {
95 95
 				break;
96 96
 			}
97 97
 		}
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 2 patches
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -30,83 +30,83 @@
 block discarded – undo
30 30
 use OCP\Files\File;
31 31
 
32 32
 abstract class Office extends ProviderV2 {
33
-	private $cmd;
33
+    private $cmd;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
39
-		$this->initCmd();
40
-		if (is_null($this->cmd)) {
41
-			return null;
42
-		}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
39
+        $this->initCmd();
40
+        if (is_null($this->cmd)) {
41
+            return null;
42
+        }
43 43
 
44
-		$absPath = $this->getLocalFile($file);
44
+        $absPath = $this->getLocalFile($file);
45 45
 
46
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
46
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
47 47
 
48
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
49
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
48
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
49
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
50 50
 
51
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
51
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
52 52
 
53
-		shell_exec($exec);
53
+        shell_exec($exec);
54 54
 
55
-		//create imagick object from png
56
-		$pngPreview = null;
57
-		try {
58
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
59
-			$pngPreview = $dirname . '/' . $filename . '.png';
55
+        //create imagick object from png
56
+        $pngPreview = null;
57
+        try {
58
+            list($dirname, , , $filename) = array_values(pathinfo($absPath));
59
+            $pngPreview = $dirname . '/' . $filename . '.png';
60 60
 
61
-			$png = new \imagick($pngPreview . '[0]');
62
-			$png->setImageFormat('jpg');
63
-		} catch (\Exception $e) {
64
-			$this->cleanTmpFiles();
65
-			unlink($pngPreview);
66
-			\OC::$server->getLogger()->logException($e, [
67
-				'level' => ILogger::ERROR,
68
-				'app' => 'core',
69
-			]);
70
-			return null;
71
-		}
61
+            $png = new \imagick($pngPreview . '[0]');
62
+            $png->setImageFormat('jpg');
63
+        } catch (\Exception $e) {
64
+            $this->cleanTmpFiles();
65
+            unlink($pngPreview);
66
+            \OC::$server->getLogger()->logException($e, [
67
+                'level' => ILogger::ERROR,
68
+                'app' => 'core',
69
+            ]);
70
+            return null;
71
+        }
72 72
 
73
-		$image = new \OC_Image();
74
-		$image->loadFromData($png);
73
+        $image = new \OC_Image();
74
+        $image->loadFromData($png);
75 75
 
76
-		$this->cleanTmpFiles();
77
-		unlink($pngPreview);
76
+        $this->cleanTmpFiles();
77
+        unlink($pngPreview);
78 78
 
79
-		if ($image->valid()) {
80
-			$image->scaleDownToFit($maxX, $maxY);
79
+        if ($image->valid()) {
80
+            $image->scaleDownToFit($maxX, $maxY);
81 81
 
82
-			return $image;
83
-		}
84
-		return null;
82
+            return $image;
83
+        }
84
+        return null;
85 85
 
86
-	}
86
+    }
87 87
 
88
-	private function initCmd() {
89
-		$cmd = '';
88
+    private function initCmd() {
89
+        $cmd = '';
90 90
 
91
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
92
-		if (is_string($libreOfficePath)) {
93
-			$cmd = $libreOfficePath;
94
-		}
91
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
92
+        if (is_string($libreOfficePath)) {
93
+            $cmd = $libreOfficePath;
94
+        }
95 95
 
96
-		$whichLibreOffice = shell_exec('command -v libreoffice');
97
-		if ($cmd === '' && !empty($whichLibreOffice)) {
98
-			$cmd = 'libreoffice';
99
-		}
96
+        $whichLibreOffice = shell_exec('command -v libreoffice');
97
+        if ($cmd === '' && !empty($whichLibreOffice)) {
98
+            $cmd = 'libreoffice';
99
+        }
100 100
 
101
-		$whichOpenOffice = shell_exec('command -v openoffice');
102
-		if ($cmd === '' && !empty($whichOpenOffice)) {
103
-			$cmd = 'openoffice';
104
-		}
101
+        $whichOpenOffice = shell_exec('command -v openoffice');
102
+        if ($cmd === '' && !empty($whichOpenOffice)) {
103
+            $cmd = 'openoffice';
104
+        }
105 105
 
106
-		if ($cmd === '') {
107
-			$cmd = null;
108
-		}
106
+        if ($cmd === '') {
107
+            $cmd = null;
108
+        }
109 109
 
110
-		$this->cmd = $cmd;
111
-	}
110
+        $this->cmd = $cmd;
111
+    }
112 112
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -45,20 +45,20 @@
 block discarded – undo
45 45
 
46 46
 		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
47 47
 
48
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
48
+		$defaultParameters = ' -env:UserInstallation=file://'.escapeshellarg($tmpDir.'/owncloud-'.\OC_Util::getInstanceId().'/').' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to png --outdir ';
49 49
 		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
50 50
 
51
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
51
+		$exec = $this->cmd.$clParameters.escapeshellarg($tmpDir).' '.escapeshellarg($absPath);
52 52
 
53 53
 		shell_exec($exec);
54 54
 
55 55
 		//create imagick object from png
56 56
 		$pngPreview = null;
57 57
 		try {
58
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
59
-			$pngPreview = $dirname . '/' . $filename . '.png';
58
+			list($dirname,,, $filename) = array_values(pathinfo($absPath));
59
+			$pngPreview = $dirname.'/'.$filename.'.png';
60 60
 
61
-			$png = new \imagick($pngPreview . '[0]');
61
+			$png = new \imagick($pngPreview.'[0]');
62 62
 			$png->setImageFormat('jpg');
63 63
 		} catch (\Exception $e) {
64 64
 			$this->cleanTmpFiles();
Please login to merge, or discard this patch.
lib/private/Preview/Illustrator.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -25,10 +25,10 @@
 block discarded – undo
25 25
 
26 26
 //.ai
27 27
 class Illustrator extends Bitmap {
28
-	/**
29
-	 * {@inheritDoc}
30
-	 */
31
-	public function getMimeType(): string {
32
-		return '/application\/illustrator/';
33
-	}
28
+    /**
29
+     * {@inheritDoc}
30
+     */
31
+    public function getMimeType(): string {
32
+        return '/application\/illustrator/';
33
+    }
34 34
 }
Please login to merge, or discard this patch.
lib/private/Preview/Postscript.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -25,10 +25,10 @@
 block discarded – undo
25 25
 
26 26
 //.eps
27 27
 class Postscript extends Bitmap {
28
-	/**
29
-	 * {@inheritDoc}
30
-	 */
31
-	public function getMimeType(): string {
32
-		return '/application\/postscript/';
33
-	}
28
+    /**
29
+     * {@inheritDoc}
30
+     */
31
+    public function getMimeType(): string {
32
+        return '/application\/postscript/';
33
+    }
34 34
 }
Please login to merge, or discard this patch.