Completed
Pull Request — master (#4620)
by Robin
15:01
created
lib/private/legacy/image.php 2 patches
Indentation   +1072 added lines, -1072 removed lines patch added patch discarded remove patch
@@ -40,565 +40,565 @@  discard block
 block discarded – undo
40 40
  * Class for basic image manipulation
41 41
  */
42 42
 class OC_Image implements \OCP\IImage {
43
-	/** @var false|resource */
44
-	protected $resource = false; // tmp resource.
45
-	/** @var int */
46
-	protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
47
-	/** @var string */
48
-	protected $mimeType = 'image/png'; // Default to png
49
-	/** @var int */
50
-	protected $bitDepth = 24;
51
-	/** @var null|string */
52
-	protected $filePath = null;
53
-	/** @var finfo */
54
-	private $fileInfo;
55
-	/** @var \OCP\ILogger */
56
-	private $logger;
57
-	/** @var \OCP\IConfig */
58
-	private $config;
59
-	/** @var array */
60
-	private $exif;
43
+    /** @var false|resource */
44
+    protected $resource = false; // tmp resource.
45
+    /** @var int */
46
+    protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
47
+    /** @var string */
48
+    protected $mimeType = 'image/png'; // Default to png
49
+    /** @var int */
50
+    protected $bitDepth = 24;
51
+    /** @var null|string */
52
+    protected $filePath = null;
53
+    /** @var finfo */
54
+    private $fileInfo;
55
+    /** @var \OCP\ILogger */
56
+    private $logger;
57
+    /** @var \OCP\IConfig */
58
+    private $config;
59
+    /** @var array */
60
+    private $exif;
61 61
 
62
-	/**
63
-	 * Get mime type for an image file.
64
-	 *
65
-	 * @param string|null $filePath The path to a local image file.
66
-	 * @return string The mime type if the it could be determined, otherwise an empty string.
67
-	 */
68
-	static public function getMimeTypeForFile($filePath) {
69
-		// exif_imagetype throws "read error!" if file is less than 12 byte
70
-		if ($filePath !== null && filesize($filePath) > 11) {
71
-			$imageType = exif_imagetype($filePath);
72
-		} else {
73
-			$imageType = false;
74
-		}
75
-		return $imageType ? image_type_to_mime_type($imageType) : '';
76
-	}
62
+    /**
63
+     * Get mime type for an image file.
64
+     *
65
+     * @param string|null $filePath The path to a local image file.
66
+     * @return string The mime type if the it could be determined, otherwise an empty string.
67
+     */
68
+    static public function getMimeTypeForFile($filePath) {
69
+        // exif_imagetype throws "read error!" if file is less than 12 byte
70
+        if ($filePath !== null && filesize($filePath) > 11) {
71
+            $imageType = exif_imagetype($filePath);
72
+        } else {
73
+            $imageType = false;
74
+        }
75
+        return $imageType ? image_type_to_mime_type($imageType) : '';
76
+    }
77 77
 
78
-	/**
79
-	 * Constructor.
80
-	 *
81
-	 * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
82
-	 * an imagecreate* function.
83
-	 * @param \OCP\ILogger $logger
84
-	 * @param \OCP\IConfig $config
85
-	 */
86
-	public function __construct($imageRef = null, \OCP\ILogger $logger = null, \OCP\IConfig $config = null) {
87
-		$this->logger = $logger;
88
-		if ($logger === null) {
89
-			$this->logger = \OC::$server->getLogger();
90
-		}
91
-		$this->config = $config;
92
-		if ($config === null) {
93
-			$this->config = \OC::$server->getConfig();
94
-		}
78
+    /**
79
+     * Constructor.
80
+     *
81
+     * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
82
+     * an imagecreate* function.
83
+     * @param \OCP\ILogger $logger
84
+     * @param \OCP\IConfig $config
85
+     */
86
+    public function __construct($imageRef = null, \OCP\ILogger $logger = null, \OCP\IConfig $config = null) {
87
+        $this->logger = $logger;
88
+        if ($logger === null) {
89
+            $this->logger = \OC::$server->getLogger();
90
+        }
91
+        $this->config = $config;
92
+        if ($config === null) {
93
+            $this->config = \OC::$server->getConfig();
94
+        }
95 95
 
96
-		if (\OC_Util::fileInfoLoaded()) {
97
-			$this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
98
-		}
96
+        if (\OC_Util::fileInfoLoaded()) {
97
+            $this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
98
+        }
99 99
 
100
-		if ($imageRef !== null) {
101
-			$this->load($imageRef);
102
-		}
103
-	}
100
+        if ($imageRef !== null) {
101
+            $this->load($imageRef);
102
+        }
103
+    }
104 104
 
105
-	/**
106
-	 * Determine whether the object contains an image resource.
107
-	 *
108
-	 * @return bool
109
-	 */
110
-	public function valid() { // apparently you can't name a method 'empty'...
111
-		return is_resource($this->resource);
112
-	}
105
+    /**
106
+     * Determine whether the object contains an image resource.
107
+     *
108
+     * @return bool
109
+     */
110
+    public function valid() { // apparently you can't name a method 'empty'...
111
+        return is_resource($this->resource);
112
+    }
113 113
 
114
-	/**
115
-	 * Returns the MIME type of the image or an empty string if no image is loaded.
116
-	 *
117
-	 * @return string
118
-	 */
119
-	public function mimeType() {
120
-		return $this->valid() ? $this->mimeType : '';
121
-	}
114
+    /**
115
+     * Returns the MIME type of the image or an empty string if no image is loaded.
116
+     *
117
+     * @return string
118
+     */
119
+    public function mimeType() {
120
+        return $this->valid() ? $this->mimeType : '';
121
+    }
122 122
 
123
-	/**
124
-	 * Returns the width of the image or -1 if no image is loaded.
125
-	 *
126
-	 * @return int
127
-	 */
128
-	public function width() {
129
-		return $this->valid() ? imagesx($this->resource) : -1;
130
-	}
123
+    /**
124
+     * Returns the width of the image or -1 if no image is loaded.
125
+     *
126
+     * @return int
127
+     */
128
+    public function width() {
129
+        return $this->valid() ? imagesx($this->resource) : -1;
130
+    }
131 131
 
132
-	/**
133
-	 * Returns the height of the image or -1 if no image is loaded.
134
-	 *
135
-	 * @return int
136
-	 */
137
-	public function height() {
138
-		return $this->valid() ? imagesy($this->resource) : -1;
139
-	}
132
+    /**
133
+     * Returns the height of the image or -1 if no image is loaded.
134
+     *
135
+     * @return int
136
+     */
137
+    public function height() {
138
+        return $this->valid() ? imagesy($this->resource) : -1;
139
+    }
140 140
 
141
-	/**
142
-	 * Returns the width when the image orientation is top-left.
143
-	 *
144
-	 * @return int
145
-	 */
146
-	public function widthTopLeft() {
147
-		$o = $this->getOrientation();
148
-		$this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
149
-		switch ($o) {
150
-			case -1:
151
-			case 1:
152
-			case 2: // Not tested
153
-			case 3:
154
-			case 4: // Not tested
155
-				return $this->width();
156
-			case 5: // Not tested
157
-			case 6:
158
-			case 7: // Not tested
159
-			case 8:
160
-				return $this->height();
161
-		}
162
-		return $this->width();
163
-	}
141
+    /**
142
+     * Returns the width when the image orientation is top-left.
143
+     *
144
+     * @return int
145
+     */
146
+    public function widthTopLeft() {
147
+        $o = $this->getOrientation();
148
+        $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
149
+        switch ($o) {
150
+            case -1:
151
+            case 1:
152
+            case 2: // Not tested
153
+            case 3:
154
+            case 4: // Not tested
155
+                return $this->width();
156
+            case 5: // Not tested
157
+            case 6:
158
+            case 7: // Not tested
159
+            case 8:
160
+                return $this->height();
161
+        }
162
+        return $this->width();
163
+    }
164 164
 
165
-	/**
166
-	 * Returns the height when the image orientation is top-left.
167
-	 *
168
-	 * @return int
169
-	 */
170
-	public function heightTopLeft() {
171
-		$o = $this->getOrientation();
172
-		$this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
173
-		switch ($o) {
174
-			case -1:
175
-			case 1:
176
-			case 2: // Not tested
177
-			case 3:
178
-			case 4: // Not tested
179
-				return $this->height();
180
-			case 5: // Not tested
181
-			case 6:
182
-			case 7: // Not tested
183
-			case 8:
184
-				return $this->width();
185
-		}
186
-		return $this->height();
187
-	}
165
+    /**
166
+     * Returns the height when the image orientation is top-left.
167
+     *
168
+     * @return int
169
+     */
170
+    public function heightTopLeft() {
171
+        $o = $this->getOrientation();
172
+        $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
173
+        switch ($o) {
174
+            case -1:
175
+            case 1:
176
+            case 2: // Not tested
177
+            case 3:
178
+            case 4: // Not tested
179
+                return $this->height();
180
+            case 5: // Not tested
181
+            case 6:
182
+            case 7: // Not tested
183
+            case 8:
184
+                return $this->width();
185
+        }
186
+        return $this->height();
187
+    }
188 188
 
189
-	/**
190
-	 * Outputs the image.
191
-	 *
192
-	 * @param string $mimeType
193
-	 * @return bool
194
-	 */
195
-	public function show($mimeType = null) {
196
-		if ($mimeType === null) {
197
-			$mimeType = $this->mimeType();
198
-		}
199
-		header('Content-Type: ' . $mimeType);
200
-		return $this->_output(null, $mimeType);
201
-	}
189
+    /**
190
+     * Outputs the image.
191
+     *
192
+     * @param string $mimeType
193
+     * @return bool
194
+     */
195
+    public function show($mimeType = null) {
196
+        if ($mimeType === null) {
197
+            $mimeType = $this->mimeType();
198
+        }
199
+        header('Content-Type: ' . $mimeType);
200
+        return $this->_output(null, $mimeType);
201
+    }
202 202
 
203
-	/**
204
-	 * Saves the image.
205
-	 *
206
-	 * @param string $filePath
207
-	 * @param string $mimeType
208
-	 * @return bool
209
-	 */
203
+    /**
204
+     * Saves the image.
205
+     *
206
+     * @param string $filePath
207
+     * @param string $mimeType
208
+     * @return bool
209
+     */
210 210
 
211
-	public function save($filePath = null, $mimeType = null) {
212
-		if ($mimeType === null) {
213
-			$mimeType = $this->mimeType();
214
-		}
215
-		if ($filePath === null) {
216
-			if ($this->filePath === null) {
217
-				$this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
218
-				return false;
219
-			} else {
220
-				$filePath = $this->filePath;
221
-			}
222
-		}
223
-		return $this->_output($filePath, $mimeType);
224
-	}
211
+    public function save($filePath = null, $mimeType = null) {
212
+        if ($mimeType === null) {
213
+            $mimeType = $this->mimeType();
214
+        }
215
+        if ($filePath === null) {
216
+            if ($this->filePath === null) {
217
+                $this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
218
+                return false;
219
+            } else {
220
+                $filePath = $this->filePath;
221
+            }
222
+        }
223
+        return $this->_output($filePath, $mimeType);
224
+    }
225 225
 
226
-	/**
227
-	 * Outputs/saves the image.
228
-	 *
229
-	 * @param string $filePath
230
-	 * @param string $mimeType
231
-	 * @return bool
232
-	 * @throws Exception
233
-	 */
234
-	private function _output($filePath = null, $mimeType = null) {
235
-		if ($filePath) {
236
-			if (!file_exists(dirname($filePath))) {
237
-				mkdir(dirname($filePath), 0777, true);
238
-			}
239
-			$isWritable = is_writable(dirname($filePath));
240
-			if (!$isWritable) {
241
-				$this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
242
-				return false;
243
-			} elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
244
-				$this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
245
-				return false;
246
-			}
247
-		}
248
-		if (!$this->valid()) {
249
-			return false;
250
-		}
226
+    /**
227
+     * Outputs/saves the image.
228
+     *
229
+     * @param string $filePath
230
+     * @param string $mimeType
231
+     * @return bool
232
+     * @throws Exception
233
+     */
234
+    private function _output($filePath = null, $mimeType = null) {
235
+        if ($filePath) {
236
+            if (!file_exists(dirname($filePath))) {
237
+                mkdir(dirname($filePath), 0777, true);
238
+            }
239
+            $isWritable = is_writable(dirname($filePath));
240
+            if (!$isWritable) {
241
+                $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
242
+                return false;
243
+            } elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
244
+                $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
245
+                return false;
246
+            }
247
+        }
248
+        if (!$this->valid()) {
249
+            return false;
250
+        }
251 251
 
252
-		$imageType = $this->imageType;
253
-		if ($mimeType !== null) {
254
-			switch ($mimeType) {
255
-				case 'image/gif':
256
-					$imageType = IMAGETYPE_GIF;
257
-					break;
258
-				case 'image/jpeg':
259
-					$imageType = IMAGETYPE_JPEG;
260
-					break;
261
-				case 'image/png':
262
-					$imageType = IMAGETYPE_PNG;
263
-					break;
264
-				case 'image/x-xbitmap':
265
-					$imageType = IMAGETYPE_XBM;
266
-					break;
267
-				case 'image/bmp':
268
-				case 'image/x-ms-bmp':
269
-					$imageType = IMAGETYPE_BMP;
270
-					break;
271
-				default:
272
-					throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
273
-			}
274
-		}
252
+        $imageType = $this->imageType;
253
+        if ($mimeType !== null) {
254
+            switch ($mimeType) {
255
+                case 'image/gif':
256
+                    $imageType = IMAGETYPE_GIF;
257
+                    break;
258
+                case 'image/jpeg':
259
+                    $imageType = IMAGETYPE_JPEG;
260
+                    break;
261
+                case 'image/png':
262
+                    $imageType = IMAGETYPE_PNG;
263
+                    break;
264
+                case 'image/x-xbitmap':
265
+                    $imageType = IMAGETYPE_XBM;
266
+                    break;
267
+                case 'image/bmp':
268
+                case 'image/x-ms-bmp':
269
+                    $imageType = IMAGETYPE_BMP;
270
+                    break;
271
+                default:
272
+                    throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
273
+            }
274
+        }
275 275
 
276
-		switch ($imageType) {
277
-			case IMAGETYPE_GIF:
278
-				$retVal = imagegif($this->resource, $filePath);
279
-				break;
280
-			case IMAGETYPE_JPEG:
281
-				$retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());
282
-				break;
283
-			case IMAGETYPE_PNG:
284
-				$retVal = imagepng($this->resource, $filePath);
285
-				break;
286
-			case IMAGETYPE_XBM:
287
-				if (function_exists('imagexbm')) {
288
-					$retVal = imagexbm($this->resource, $filePath);
289
-				} else {
290
-					throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
291
-				}
276
+        switch ($imageType) {
277
+            case IMAGETYPE_GIF:
278
+                $retVal = imagegif($this->resource, $filePath);
279
+                break;
280
+            case IMAGETYPE_JPEG:
281
+                $retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());
282
+                break;
283
+            case IMAGETYPE_PNG:
284
+                $retVal = imagepng($this->resource, $filePath);
285
+                break;
286
+            case IMAGETYPE_XBM:
287
+                if (function_exists('imagexbm')) {
288
+                    $retVal = imagexbm($this->resource, $filePath);
289
+                } else {
290
+                    throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
291
+                }
292 292
 
293
-				break;
294
-			case IMAGETYPE_WBMP:
295
-				$retVal = imagewbmp($this->resource, $filePath);
296
-				break;
297
-			case IMAGETYPE_BMP:
298
-				$retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
299
-				break;
300
-			default:
301
-				$retVal = imagepng($this->resource, $filePath);
302
-		}
303
-		return $retVal;
304
-	}
293
+                break;
294
+            case IMAGETYPE_WBMP:
295
+                $retVal = imagewbmp($this->resource, $filePath);
296
+                break;
297
+            case IMAGETYPE_BMP:
298
+                $retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
299
+                break;
300
+            default:
301
+                $retVal = imagepng($this->resource, $filePath);
302
+        }
303
+        return $retVal;
304
+    }
305 305
 
306
-	/**
307
-	 * Prints the image when called as $image().
308
-	 */
309
-	public function __invoke() {
310
-		return $this->show();
311
-	}
306
+    /**
307
+     * Prints the image when called as $image().
308
+     */
309
+    public function __invoke() {
310
+        return $this->show();
311
+    }
312 312
 
313
-	/**
314
-	 * @return resource Returns the image resource in any.
315
-	 */
316
-	public function resource() {
317
-		return $this->resource;
318
-	}
313
+    /**
314
+     * @return resource Returns the image resource in any.
315
+     */
316
+    public function resource() {
317
+        return $this->resource;
318
+    }
319 319
 
320
-	/**
321
-	 * @return null|string Returns the raw image data.
322
-	 */
323
-	public function data() {
324
-		if (!$this->valid()) {
325
-			return null;
326
-		}
327
-		ob_start();
328
-		switch ($this->mimeType) {
329
-			case "image/png":
330
-				$res = imagepng($this->resource);
331
-				break;
332
-			case "image/jpeg":
333
-				$quality = $this->getJpegQuality();
334
-				if ($quality !== null) {
335
-					$res = imagejpeg($this->resource, null, $quality);
336
-				} else {
337
-					$res = imagejpeg($this->resource);
338
-				}
339
-				break;
340
-			case "image/gif":
341
-				$res = imagegif($this->resource);
342
-				break;
343
-			default:
344
-				$res = imagepng($this->resource);
345
-				$this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
346
-				break;
347
-		}
348
-		if (!$res) {
349
-			$this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
350
-		}
351
-		return ob_get_clean();
352
-	}
320
+    /**
321
+     * @return null|string Returns the raw image data.
322
+     */
323
+    public function data() {
324
+        if (!$this->valid()) {
325
+            return null;
326
+        }
327
+        ob_start();
328
+        switch ($this->mimeType) {
329
+            case "image/png":
330
+                $res = imagepng($this->resource);
331
+                break;
332
+            case "image/jpeg":
333
+                $quality = $this->getJpegQuality();
334
+                if ($quality !== null) {
335
+                    $res = imagejpeg($this->resource, null, $quality);
336
+                } else {
337
+                    $res = imagejpeg($this->resource);
338
+                }
339
+                break;
340
+            case "image/gif":
341
+                $res = imagegif($this->resource);
342
+                break;
343
+            default:
344
+                $res = imagepng($this->resource);
345
+                $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
346
+                break;
347
+        }
348
+        if (!$res) {
349
+            $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
350
+        }
351
+        return ob_get_clean();
352
+    }
353 353
 
354
-	/**
355
-	 * @return string - base64 encoded, which is suitable for embedding in a VCard.
356
-	 */
357
-	public function __toString() {
358
-		return base64_encode($this->data());
359
-	}
354
+    /**
355
+     * @return string - base64 encoded, which is suitable for embedding in a VCard.
356
+     */
357
+    public function __toString() {
358
+        return base64_encode($this->data());
359
+    }
360 360
 
361
-	/**
362
-	 * @return int|null
363
-	 */
364
-	protected function getJpegQuality() {
365
-		$quality = $this->config->getAppValue('preview', 'jpeg_quality', 90);
366
-		if ($quality !== null) {
367
-			$quality = min(100, max(10, (int) $quality));
368
-		}
369
-		return $quality;
370
-	}
361
+    /**
362
+     * @return int|null
363
+     */
364
+    protected function getJpegQuality() {
365
+        $quality = $this->config->getAppValue('preview', 'jpeg_quality', 90);
366
+        if ($quality !== null) {
367
+            $quality = min(100, max(10, (int) $quality));
368
+        }
369
+        return $quality;
370
+    }
371 371
 
372
-	/**
373
-	 * (I'm open for suggestions on better method name ;)
374
-	 * Get the orientation based on EXIF data.
375
-	 *
376
-	 * @return int The orientation or -1 if no EXIF data is available.
377
-	 */
378
-	public function getOrientation() {
379
-		if ($this->exif !== null) {
380
-			return $this->exif['Orientation'];
381
-		}
372
+    /**
373
+     * (I'm open for suggestions on better method name ;)
374
+     * Get the orientation based on EXIF data.
375
+     *
376
+     * @return int The orientation or -1 if no EXIF data is available.
377
+     */
378
+    public function getOrientation() {
379
+        if ($this->exif !== null) {
380
+            return $this->exif['Orientation'];
381
+        }
382 382
 
383
-		if ($this->imageType !== IMAGETYPE_JPEG) {
384
-			$this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
385
-			return -1;
386
-		}
387
-		if (!is_callable('exif_read_data')) {
388
-			$this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
389
-			return -1;
390
-		}
391
-		if (!$this->valid()) {
392
-			$this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
393
-			return -1;
394
-		}
395
-		if (is_null($this->filePath) || !is_readable($this->filePath)) {
396
-			$this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
397
-			return -1;
398
-		}
399
-		$exif = @exif_read_data($this->filePath, 'IFD0');
400
-		if (!$exif) {
401
-			return -1;
402
-		}
403
-		if (!isset($exif['Orientation'])) {
404
-			return -1;
405
-		}
406
-		$this->exif = $exif;
407
-		return $exif['Orientation'];
408
-	}
383
+        if ($this->imageType !== IMAGETYPE_JPEG) {
384
+            $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
385
+            return -1;
386
+        }
387
+        if (!is_callable('exif_read_data')) {
388
+            $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
389
+            return -1;
390
+        }
391
+        if (!$this->valid()) {
392
+            $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
393
+            return -1;
394
+        }
395
+        if (is_null($this->filePath) || !is_readable($this->filePath)) {
396
+            $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
397
+            return -1;
398
+        }
399
+        $exif = @exif_read_data($this->filePath, 'IFD0');
400
+        if (!$exif) {
401
+            return -1;
402
+        }
403
+        if (!isset($exif['Orientation'])) {
404
+            return -1;
405
+        }
406
+        $this->exif = $exif;
407
+        return $exif['Orientation'];
408
+    }
409 409
 
410
-	public function readExif($data) {
411
-		if (!is_callable('exif_read_data')) {
412
-			$this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
413
-			return;
414
-		}
415
-		if (!$this->valid()) {
416
-			$this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
417
-			return;
418
-		}
410
+    public function readExif($data) {
411
+        if (!is_callable('exif_read_data')) {
412
+            $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
413
+            return;
414
+        }
415
+        if (!$this->valid()) {
416
+            $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
417
+            return;
418
+        }
419 419
 
420
-		$exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
421
-		if (!$exif) {
422
-			return;
423
-		}
424
-		if (!isset($exif['Orientation'])) {
425
-			return;
426
-		}
427
-		$this->exif = $exif;
428
-	}
420
+        $exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
421
+        if (!$exif) {
422
+            return;
423
+        }
424
+        if (!isset($exif['Orientation'])) {
425
+            return;
426
+        }
427
+        $this->exif = $exif;
428
+    }
429 429
 
430
-	/**
431
-	 * (I'm open for suggestions on better method name ;)
432
-	 * Fixes orientation based on EXIF data.
433
-	 *
434
-	 * @return bool.
435
-	 */
436
-	public function fixOrientation() {
437
-		$o = $this->getOrientation();
438
-		$this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
439
-		$rotate = 0;
440
-		$flip = false;
441
-		switch ($o) {
442
-			case -1:
443
-				return false; //Nothing to fix
444
-			case 1:
445
-				$rotate = 0;
446
-				break;
447
-			case 2:
448
-				$rotate = 0;
449
-				$flip = true;
450
-				break;
451
-			case 3:
452
-				$rotate = 180;
453
-				break;
454
-			case 4:
455
-				$rotate = 180;
456
-				$flip = true;
457
-				break;
458
-			case 5:
459
-				$rotate = 90;
460
-				$flip = true;
461
-				break;
462
-			case 6:
463
-				$rotate = 270;
464
-				break;
465
-			case 7:
466
-				$rotate = 270;
467
-				$flip = true;
468
-				break;
469
-			case 8:
470
-				$rotate = 90;
471
-				break;
472
-		}
473
-		if($flip && function_exists('imageflip')) {
474
-			imageflip($this->resource, IMG_FLIP_HORIZONTAL);
475
-		}
476
-		if ($rotate) {
477
-			$res = imagerotate($this->resource, $rotate, 0);
478
-			if ($res) {
479
-				if (imagealphablending($res, true)) {
480
-					if (imagesavealpha($res, true)) {
481
-						imagedestroy($this->resource);
482
-						$this->resource = $res;
483
-						return true;
484
-					} else {
485
-						$this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core'));
486
-						return false;
487
-					}
488
-				} else {
489
-					$this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
490
-					return false;
491
-				}
492
-			} else {
493
-				$this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core'));
494
-				return false;
495
-			}
496
-		}
497
-		return false;
498
-	}
430
+    /**
431
+     * (I'm open for suggestions on better method name ;)
432
+     * Fixes orientation based on EXIF data.
433
+     *
434
+     * @return bool.
435
+     */
436
+    public function fixOrientation() {
437
+        $o = $this->getOrientation();
438
+        $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
439
+        $rotate = 0;
440
+        $flip = false;
441
+        switch ($o) {
442
+            case -1:
443
+                return false; //Nothing to fix
444
+            case 1:
445
+                $rotate = 0;
446
+                break;
447
+            case 2:
448
+                $rotate = 0;
449
+                $flip = true;
450
+                break;
451
+            case 3:
452
+                $rotate = 180;
453
+                break;
454
+            case 4:
455
+                $rotate = 180;
456
+                $flip = true;
457
+                break;
458
+            case 5:
459
+                $rotate = 90;
460
+                $flip = true;
461
+                break;
462
+            case 6:
463
+                $rotate = 270;
464
+                break;
465
+            case 7:
466
+                $rotate = 270;
467
+                $flip = true;
468
+                break;
469
+            case 8:
470
+                $rotate = 90;
471
+                break;
472
+        }
473
+        if($flip && function_exists('imageflip')) {
474
+            imageflip($this->resource, IMG_FLIP_HORIZONTAL);
475
+        }
476
+        if ($rotate) {
477
+            $res = imagerotate($this->resource, $rotate, 0);
478
+            if ($res) {
479
+                if (imagealphablending($res, true)) {
480
+                    if (imagesavealpha($res, true)) {
481
+                        imagedestroy($this->resource);
482
+                        $this->resource = $res;
483
+                        return true;
484
+                    } else {
485
+                        $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core'));
486
+                        return false;
487
+                    }
488
+                } else {
489
+                    $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
490
+                    return false;
491
+                }
492
+            } else {
493
+                $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core'));
494
+                return false;
495
+            }
496
+        }
497
+        return false;
498
+    }
499 499
 
500
-	/**
501
-	 * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function.
502
-	 *
503
-	 * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle    ).
504
-	 * @return resource|false An image resource or false on error
505
-	 */
506
-	public function load($imageRef) {
507
-		if (is_resource($imageRef)) {
508
-			if (get_resource_type($imageRef) === 'gd') {
509
-				$this->resource = $imageRef;
510
-				return $this->resource;
511
-			} elseif (in_array(get_resource_type($imageRef), array('file', 'stream'))) {
512
-				return $this->loadFromFileHandle($imageRef);
513
-			}
514
-		} elseif ($this->loadFromBase64($imageRef) !== false) {
515
-			return $this->resource;
516
-		} elseif ($this->loadFromFile($imageRef) !== false) {
517
-			return $this->resource;
518
-		} elseif ($this->loadFromData($imageRef) !== false) {
519
-			return $this->resource;
520
-		}
521
-		$this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
522
-		return false;
523
-	}
500
+    /**
501
+     * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function.
502
+     *
503
+     * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle    ).
504
+     * @return resource|false An image resource or false on error
505
+     */
506
+    public function load($imageRef) {
507
+        if (is_resource($imageRef)) {
508
+            if (get_resource_type($imageRef) === 'gd') {
509
+                $this->resource = $imageRef;
510
+                return $this->resource;
511
+            } elseif (in_array(get_resource_type($imageRef), array('file', 'stream'))) {
512
+                return $this->loadFromFileHandle($imageRef);
513
+            }
514
+        } elseif ($this->loadFromBase64($imageRef) !== false) {
515
+            return $this->resource;
516
+        } elseif ($this->loadFromFile($imageRef) !== false) {
517
+            return $this->resource;
518
+        } elseif ($this->loadFromData($imageRef) !== false) {
519
+            return $this->resource;
520
+        }
521
+        $this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
522
+        return false;
523
+    }
524 524
 
525
-	/**
526
-	 * Loads an image from an open file handle.
527
-	 * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
528
-	 *
529
-	 * @param resource $handle
530
-	 * @return resource|false An image resource or false on error
531
-	 */
532
-	public function loadFromFileHandle($handle) {
533
-		$contents = stream_get_contents($handle);
534
-		if ($this->loadFromData($contents)) {
535
-			return $this->resource;
536
-		}
537
-		return false;
538
-	}
525
+    /**
526
+     * Loads an image from an open file handle.
527
+     * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
528
+     *
529
+     * @param resource $handle
530
+     * @return resource|false An image resource or false on error
531
+     */
532
+    public function loadFromFileHandle($handle) {
533
+        $contents = stream_get_contents($handle);
534
+        if ($this->loadFromData($contents)) {
535
+            return $this->resource;
536
+        }
537
+        return false;
538
+    }
539 539
 
540
-	/**
541
-	 * Loads an image from a local file.
542
-	 *
543
-	 * @param bool|string $imagePath The path to a local file.
544
-	 * @return bool|resource An image resource or false on error
545
-	 */
546
-	public function loadFromFile($imagePath = false) {
547
-		// exif_imagetype throws "read error!" if file is less than 12 byte
548
-		if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
549
-			return false;
550
-		}
551
-		$iType = exif_imagetype($imagePath);
552
-		switch ($iType) {
553
-			case IMAGETYPE_GIF:
554
-				if (imagetypes() & IMG_GIF) {
555
-					$this->resource = imagecreatefromgif($imagePath);
556
-					// Preserve transparency
557
-					imagealphablending($this->resource, true);
558
-					imagesavealpha($this->resource, true);
559
-				} else {
560
-					$this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
561
-				}
562
-				break;
563
-			case IMAGETYPE_JPEG:
564
-				if (imagetypes() & IMG_JPG) {
565
-					if (getimagesize($imagePath) !== false) {
566
-						$this->resource = @imagecreatefromjpeg($imagePath);
567
-					} else {
568
-						$this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
569
-					}
570
-				} else {
571
-					$this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
572
-				}
573
-				break;
574
-			case IMAGETYPE_PNG:
575
-				if (imagetypes() & IMG_PNG) {
576
-					$this->resource = @imagecreatefrompng($imagePath);
577
-					// Preserve transparency
578
-					imagealphablending($this->resource, true);
579
-					imagesavealpha($this->resource, true);
580
-				} else {
581
-					$this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
582
-				}
583
-				break;
584
-			case IMAGETYPE_XBM:
585
-				if (imagetypes() & IMG_XPM) {
586
-					$this->resource = @imagecreatefromxbm($imagePath);
587
-				} else {
588
-					$this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
589
-				}
590
-				break;
591
-			case IMAGETYPE_WBMP:
592
-				if (imagetypes() & IMG_WBMP) {
593
-					$this->resource = @imagecreatefromwbmp($imagePath);
594
-				} else {
595
-					$this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
596
-				}
597
-				break;
598
-			case IMAGETYPE_BMP:
599
-				$this->resource = $this->imagecreatefrombmp($imagePath);
600
-				break;
601
-			/*
540
+    /**
541
+     * Loads an image from a local file.
542
+     *
543
+     * @param bool|string $imagePath The path to a local file.
544
+     * @return bool|resource An image resource or false on error
545
+     */
546
+    public function loadFromFile($imagePath = false) {
547
+        // exif_imagetype throws "read error!" if file is less than 12 byte
548
+        if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
549
+            return false;
550
+        }
551
+        $iType = exif_imagetype($imagePath);
552
+        switch ($iType) {
553
+            case IMAGETYPE_GIF:
554
+                if (imagetypes() & IMG_GIF) {
555
+                    $this->resource = imagecreatefromgif($imagePath);
556
+                    // Preserve transparency
557
+                    imagealphablending($this->resource, true);
558
+                    imagesavealpha($this->resource, true);
559
+                } else {
560
+                    $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
561
+                }
562
+                break;
563
+            case IMAGETYPE_JPEG:
564
+                if (imagetypes() & IMG_JPG) {
565
+                    if (getimagesize($imagePath) !== false) {
566
+                        $this->resource = @imagecreatefromjpeg($imagePath);
567
+                    } else {
568
+                        $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
569
+                    }
570
+                } else {
571
+                    $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
572
+                }
573
+                break;
574
+            case IMAGETYPE_PNG:
575
+                if (imagetypes() & IMG_PNG) {
576
+                    $this->resource = @imagecreatefrompng($imagePath);
577
+                    // Preserve transparency
578
+                    imagealphablending($this->resource, true);
579
+                    imagesavealpha($this->resource, true);
580
+                } else {
581
+                    $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
582
+                }
583
+                break;
584
+            case IMAGETYPE_XBM:
585
+                if (imagetypes() & IMG_XPM) {
586
+                    $this->resource = @imagecreatefromxbm($imagePath);
587
+                } else {
588
+                    $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
589
+                }
590
+                break;
591
+            case IMAGETYPE_WBMP:
592
+                if (imagetypes() & IMG_WBMP) {
593
+                    $this->resource = @imagecreatefromwbmp($imagePath);
594
+                } else {
595
+                    $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
596
+                }
597
+                break;
598
+            case IMAGETYPE_BMP:
599
+                $this->resource = $this->imagecreatefrombmp($imagePath);
600
+                break;
601
+            /*
602 602
 			case IMAGETYPE_TIFF_II: // (intel byte order)
603 603
 				break;
604 604
 			case IMAGETYPE_TIFF_MM: // (motorola byte order)
@@ -622,581 +622,581 @@  discard block
 block discarded – undo
622 622
 			case IMAGETYPE_PSD:
623 623
 				break;
624 624
 			*/
625
-			default:
625
+            default:
626 626
 
627
-				// this is mostly file created from encrypted file
628
-				$this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
629
-				$iType = IMAGETYPE_PNG;
630
-				$this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
631
-				break;
632
-		}
633
-		if ($this->valid()) {
634
-			$this->imageType = $iType;
635
-			$this->mimeType = image_type_to_mime_type($iType);
636
-			$this->filePath = $imagePath;
637
-		}
638
-		return $this->resource;
639
-	}
627
+                // this is mostly file created from encrypted file
628
+                $this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
629
+                $iType = IMAGETYPE_PNG;
630
+                $this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
631
+                break;
632
+        }
633
+        if ($this->valid()) {
634
+            $this->imageType = $iType;
635
+            $this->mimeType = image_type_to_mime_type($iType);
636
+            $this->filePath = $imagePath;
637
+        }
638
+        return $this->resource;
639
+    }
640 640
 
641
-	/**
642
-	 * Loads an image from a string of data.
643
-	 *
644
-	 * @param string $str A string of image data as read from a file.
645
-	 * @return bool|resource An image resource or false on error
646
-	 */
647
-	public function loadFromData($str) {
648
-		if (is_resource($str)) {
649
-			return false;
650
-		}
651
-		$this->resource = @imagecreatefromstring($str);
652
-		if ($this->fileInfo) {
653
-			$this->mimeType = $this->fileInfo->buffer($str);
654
-		}
655
-		if (is_resource($this->resource)) {
656
-			imagealphablending($this->resource, false);
657
-			imagesavealpha($this->resource, true);
658
-		}
641
+    /**
642
+     * Loads an image from a string of data.
643
+     *
644
+     * @param string $str A string of image data as read from a file.
645
+     * @return bool|resource An image resource or false on error
646
+     */
647
+    public function loadFromData($str) {
648
+        if (is_resource($str)) {
649
+            return false;
650
+        }
651
+        $this->resource = @imagecreatefromstring($str);
652
+        if ($this->fileInfo) {
653
+            $this->mimeType = $this->fileInfo->buffer($str);
654
+        }
655
+        if (is_resource($this->resource)) {
656
+            imagealphablending($this->resource, false);
657
+            imagesavealpha($this->resource, true);
658
+        }
659 659
 
660
-		if (!$this->resource) {
661
-			$this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
662
-			return false;
663
-		}
664
-		return $this->resource;
665
-	}
660
+        if (!$this->resource) {
661
+            $this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
662
+            return false;
663
+        }
664
+        return $this->resource;
665
+    }
666 666
 
667
-	/**
668
-	 * Loads an image from a base64 encoded string.
669
-	 *
670
-	 * @param string $str A string base64 encoded string of image data.
671
-	 * @return bool|resource An image resource or false on error
672
-	 */
673
-	public function loadFromBase64($str) {
674
-		if (!is_string($str)) {
675
-			return false;
676
-		}
677
-		$data = base64_decode($str);
678
-		if ($data) { // try to load from string data
679
-			$this->resource = @imagecreatefromstring($data);
680
-			if ($this->fileInfo) {
681
-				$this->mimeType = $this->fileInfo->buffer($data);
682
-			}
683
-			if (!$this->resource) {
684
-				$this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
685
-				return false;
686
-			}
687
-			return $this->resource;
688
-		} else {
689
-			return false;
690
-		}
691
-	}
667
+    /**
668
+     * Loads an image from a base64 encoded string.
669
+     *
670
+     * @param string $str A string base64 encoded string of image data.
671
+     * @return bool|resource An image resource or false on error
672
+     */
673
+    public function loadFromBase64($str) {
674
+        if (!is_string($str)) {
675
+            return false;
676
+        }
677
+        $data = base64_decode($str);
678
+        if ($data) { // try to load from string data
679
+            $this->resource = @imagecreatefromstring($data);
680
+            if ($this->fileInfo) {
681
+                $this->mimeType = $this->fileInfo->buffer($data);
682
+            }
683
+            if (!$this->resource) {
684
+                $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
685
+                return false;
686
+            }
687
+            return $this->resource;
688
+        } else {
689
+            return false;
690
+        }
691
+    }
692 692
 
693
-	/**
694
-	 * Create a new image from file or URL
695
-	 *
696
-	 * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
697
-	 * @version 1.00
698
-	 * @param string $fileName <p>
699
-	 * Path to the BMP image.
700
-	 * </p>
701
-	 * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
702
-	 */
703
-	private function imagecreatefrombmp($fileName) {
704
-		if (!($fh = fopen($fileName, 'rb'))) {
705
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
706
-			return false;
707
-		}
708
-		// read file header
709
-		$meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
710
-		// check for bitmap
711
-		if ($meta['type'] != 19778) {
712
-			fclose($fh);
713
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
714
-			return false;
715
-		}
716
-		// read image header
717
-		$meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
718
-		// read additional 16bit header
719
-		if ($meta['bits'] == 16) {
720
-			$meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
721
-		}
722
-		// set bytes and padding
723
-		$meta['bytes'] = $meta['bits'] / 8;
724
-		$this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
725
-		$meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
726
-		if ($meta['decal'] == 4) {
727
-			$meta['decal'] = 0;
728
-		}
729
-		// obtain imagesize
730
-		if ($meta['imagesize'] < 1) {
731
-			$meta['imagesize'] = $meta['filesize'] - $meta['offset'];
732
-			// in rare cases filesize is equal to offset so we need to read physical size
733
-			if ($meta['imagesize'] < 1) {
734
-				$meta['imagesize'] = @filesize($fileName) - $meta['offset'];
735
-				if ($meta['imagesize'] < 1) {
736
-					fclose($fh);
737
-					$this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
738
-					return false;
739
-				}
740
-			}
741
-		}
742
-		// calculate colors
743
-		$meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
744
-		// read color palette
745
-		$palette = array();
746
-		if ($meta['bits'] < 16) {
747
-			$palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
748
-			// in rare cases the color value is signed
749
-			if ($palette[1] < 0) {
750
-				foreach ($palette as $i => $color) {
751
-					$palette[$i] = $color + 16777216;
752
-				}
753
-			}
754
-		}
755
-		// create gd image
756
-		$im = imagecreatetruecolor($meta['width'], $meta['height']);
757
-		if ($im == false) {
758
-			fclose($fh);
759
-			$this->logger->warning(
760
-				'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
761
-				array('app' => 'core'));
762
-			return false;
763
-		}
693
+    /**
694
+     * Create a new image from file or URL
695
+     *
696
+     * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
697
+     * @version 1.00
698
+     * @param string $fileName <p>
699
+     * Path to the BMP image.
700
+     * </p>
701
+     * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
702
+     */
703
+    private function imagecreatefrombmp($fileName) {
704
+        if (!($fh = fopen($fileName, 'rb'))) {
705
+            $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
706
+            return false;
707
+        }
708
+        // read file header
709
+        $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
710
+        // check for bitmap
711
+        if ($meta['type'] != 19778) {
712
+            fclose($fh);
713
+            $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
714
+            return false;
715
+        }
716
+        // read image header
717
+        $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
718
+        // read additional 16bit header
719
+        if ($meta['bits'] == 16) {
720
+            $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
721
+        }
722
+        // set bytes and padding
723
+        $meta['bytes'] = $meta['bits'] / 8;
724
+        $this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
725
+        $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
726
+        if ($meta['decal'] == 4) {
727
+            $meta['decal'] = 0;
728
+        }
729
+        // obtain imagesize
730
+        if ($meta['imagesize'] < 1) {
731
+            $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
732
+            // in rare cases filesize is equal to offset so we need to read physical size
733
+            if ($meta['imagesize'] < 1) {
734
+                $meta['imagesize'] = @filesize($fileName) - $meta['offset'];
735
+                if ($meta['imagesize'] < 1) {
736
+                    fclose($fh);
737
+                    $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
738
+                    return false;
739
+                }
740
+            }
741
+        }
742
+        // calculate colors
743
+        $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
744
+        // read color palette
745
+        $palette = array();
746
+        if ($meta['bits'] < 16) {
747
+            $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
748
+            // in rare cases the color value is signed
749
+            if ($palette[1] < 0) {
750
+                foreach ($palette as $i => $color) {
751
+                    $palette[$i] = $color + 16777216;
752
+                }
753
+            }
754
+        }
755
+        // create gd image
756
+        $im = imagecreatetruecolor($meta['width'], $meta['height']);
757
+        if ($im == false) {
758
+            fclose($fh);
759
+            $this->logger->warning(
760
+                'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
761
+                array('app' => 'core'));
762
+            return false;
763
+        }
764 764
 
765
-		$data = fread($fh, $meta['imagesize']);
766
-		$p = 0;
767
-		$vide = chr(0);
768
-		$y = $meta['height'] - 1;
769
-		$error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
770
-		// loop through the image data beginning with the lower left corner
771
-		while ($y >= 0) {
772
-			$x = 0;
773
-			while ($x < $meta['width']) {
774
-				switch ($meta['bits']) {
775
-					case 32:
776
-					case 24:
777
-						if (!($part = substr($data, $p, 3))) {
778
-							$this->logger->warning($error, array('app' => 'core'));
779
-							return $im;
780
-						}
781
-						$color = @unpack('V', $part . $vide);
782
-						break;
783
-					case 16:
784
-						if (!($part = substr($data, $p, 2))) {
785
-							fclose($fh);
786
-							$this->logger->warning($error, array('app' => 'core'));
787
-							return $im;
788
-						}
789
-						$color = @unpack('v', $part);
790
-						$color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
791
-						break;
792
-					case 8:
793
-						$color = @unpack('n', $vide . substr($data, $p, 1));
794
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
795
-						break;
796
-					case 4:
797
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
798
-						$color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
799
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
800
-						break;
801
-					case 1:
802
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
803
-						switch (($p * 8) % 8) {
804
-							case 0:
805
-								$color[1] = $color[1] >> 7;
806
-								break;
807
-							case 1:
808
-								$color[1] = ($color[1] & 0x40) >> 6;
809
-								break;
810
-							case 2:
811
-								$color[1] = ($color[1] & 0x20) >> 5;
812
-								break;
813
-							case 3:
814
-								$color[1] = ($color[1] & 0x10) >> 4;
815
-								break;
816
-							case 4:
817
-								$color[1] = ($color[1] & 0x8) >> 3;
818
-								break;
819
-							case 5:
820
-								$color[1] = ($color[1] & 0x4) >> 2;
821
-								break;
822
-							case 6:
823
-								$color[1] = ($color[1] & 0x2) >> 1;
824
-								break;
825
-							case 7:
826
-								$color[1] = ($color[1] & 0x1);
827
-								break;
828
-						}
829
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
830
-						break;
831
-					default:
832
-						fclose($fh);
833
-						$this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
834
-						return false;
835
-				}
836
-				imagesetpixel($im, $x, $y, $color[1]);
837
-				$x++;
838
-				$p += $meta['bytes'];
839
-			}
840
-			$y--;
841
-			$p += $meta['decal'];
842
-		}
843
-		fclose($fh);
844
-		return $im;
845
-	}
765
+        $data = fread($fh, $meta['imagesize']);
766
+        $p = 0;
767
+        $vide = chr(0);
768
+        $y = $meta['height'] - 1;
769
+        $error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
770
+        // loop through the image data beginning with the lower left corner
771
+        while ($y >= 0) {
772
+            $x = 0;
773
+            while ($x < $meta['width']) {
774
+                switch ($meta['bits']) {
775
+                    case 32:
776
+                    case 24:
777
+                        if (!($part = substr($data, $p, 3))) {
778
+                            $this->logger->warning($error, array('app' => 'core'));
779
+                            return $im;
780
+                        }
781
+                        $color = @unpack('V', $part . $vide);
782
+                        break;
783
+                    case 16:
784
+                        if (!($part = substr($data, $p, 2))) {
785
+                            fclose($fh);
786
+                            $this->logger->warning($error, array('app' => 'core'));
787
+                            return $im;
788
+                        }
789
+                        $color = @unpack('v', $part);
790
+                        $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
791
+                        break;
792
+                    case 8:
793
+                        $color = @unpack('n', $vide . substr($data, $p, 1));
794
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
795
+                        break;
796
+                    case 4:
797
+                        $color = @unpack('n', $vide . substr($data, floor($p), 1));
798
+                        $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
799
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
800
+                        break;
801
+                    case 1:
802
+                        $color = @unpack('n', $vide . substr($data, floor($p), 1));
803
+                        switch (($p * 8) % 8) {
804
+                            case 0:
805
+                                $color[1] = $color[1] >> 7;
806
+                                break;
807
+                            case 1:
808
+                                $color[1] = ($color[1] & 0x40) >> 6;
809
+                                break;
810
+                            case 2:
811
+                                $color[1] = ($color[1] & 0x20) >> 5;
812
+                                break;
813
+                            case 3:
814
+                                $color[1] = ($color[1] & 0x10) >> 4;
815
+                                break;
816
+                            case 4:
817
+                                $color[1] = ($color[1] & 0x8) >> 3;
818
+                                break;
819
+                            case 5:
820
+                                $color[1] = ($color[1] & 0x4) >> 2;
821
+                                break;
822
+                            case 6:
823
+                                $color[1] = ($color[1] & 0x2) >> 1;
824
+                                break;
825
+                            case 7:
826
+                                $color[1] = ($color[1] & 0x1);
827
+                                break;
828
+                        }
829
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
830
+                        break;
831
+                    default:
832
+                        fclose($fh);
833
+                        $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
834
+                        return false;
835
+                }
836
+                imagesetpixel($im, $x, $y, $color[1]);
837
+                $x++;
838
+                $p += $meta['bytes'];
839
+            }
840
+            $y--;
841
+            $p += $meta['decal'];
842
+        }
843
+        fclose($fh);
844
+        return $im;
845
+    }
846 846
 
847
-	/**
848
-	 * Resizes the image preserving ratio.
849
-	 *
850
-	 * @param integer $maxSize The maximum size of either the width or height.
851
-	 * @return bool
852
-	 */
853
-	public function resize($maxSize) {
854
-		if (!$this->valid()) {
855
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
856
-			return false;
857
-		}
858
-		$widthOrig = imagesx($this->resource);
859
-		$heightOrig = imagesy($this->resource);
860
-		$ratioOrig = $widthOrig / $heightOrig;
847
+    /**
848
+     * Resizes the image preserving ratio.
849
+     *
850
+     * @param integer $maxSize The maximum size of either the width or height.
851
+     * @return bool
852
+     */
853
+    public function resize($maxSize) {
854
+        if (!$this->valid()) {
855
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
856
+            return false;
857
+        }
858
+        $widthOrig = imagesx($this->resource);
859
+        $heightOrig = imagesy($this->resource);
860
+        $ratioOrig = $widthOrig / $heightOrig;
861 861
 
862
-		if ($ratioOrig > 1) {
863
-			$newHeight = round($maxSize / $ratioOrig);
864
-			$newWidth = $maxSize;
865
-		} else {
866
-			$newWidth = round($maxSize * $ratioOrig);
867
-			$newHeight = $maxSize;
868
-		}
862
+        if ($ratioOrig > 1) {
863
+            $newHeight = round($maxSize / $ratioOrig);
864
+            $newWidth = $maxSize;
865
+        } else {
866
+            $newWidth = round($maxSize * $ratioOrig);
867
+            $newHeight = $maxSize;
868
+        }
869 869
 
870
-		$this->preciseResize(round($newWidth), round($newHeight));
871
-		return true;
872
-	}
870
+        $this->preciseResize(round($newWidth), round($newHeight));
871
+        return true;
872
+    }
873 873
 
874
-	/**
875
-	 * @param int $width
876
-	 * @param int $height
877
-	 * @return bool
878
-	 */
879
-	public function preciseResize($width, $height) {
880
-		if (!$this->valid()) {
881
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
882
-			return false;
883
-		}
884
-		$widthOrig = imagesx($this->resource);
885
-		$heightOrig = imagesy($this->resource);
886
-		$process = imagecreatetruecolor($width, $height);
874
+    /**
875
+     * @param int $width
876
+     * @param int $height
877
+     * @return bool
878
+     */
879
+    public function preciseResize($width, $height) {
880
+        if (!$this->valid()) {
881
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
882
+            return false;
883
+        }
884
+        $widthOrig = imagesx($this->resource);
885
+        $heightOrig = imagesy($this->resource);
886
+        $process = imagecreatetruecolor($width, $height);
887 887
 
888
-		if ($process == false) {
889
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
890
-			imagedestroy($process);
891
-			return false;
892
-		}
888
+        if ($process == false) {
889
+            $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
890
+            imagedestroy($process);
891
+            return false;
892
+        }
893 893
 
894
-		// preserve transparency
895
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
896
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
897
-			imagealphablending($process, false);
898
-			imagesavealpha($process, true);
899
-		}
894
+        // preserve transparency
895
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
896
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
897
+            imagealphablending($process, false);
898
+            imagesavealpha($process, true);
899
+        }
900 900
 
901
-		imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
902
-		if ($process == false) {
903
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
904
-			imagedestroy($process);
905
-			return false;
906
-		}
907
-		imagedestroy($this->resource);
908
-		$this->resource = $process;
909
-		return true;
910
-	}
901
+        imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
902
+        if ($process == false) {
903
+            $this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
904
+            imagedestroy($process);
905
+            return false;
906
+        }
907
+        imagedestroy($this->resource);
908
+        $this->resource = $process;
909
+        return true;
910
+    }
911 911
 
912
-	/**
913
-	 * Crops the image to the middle square. If the image is already square it just returns.
914
-	 *
915
-	 * @param int $size maximum size for the result (optional)
916
-	 * @return bool for success or failure
917
-	 */
918
-	public function centerCrop($size = 0) {
919
-		if (!$this->valid()) {
920
-			$this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
921
-			return false;
922
-		}
923
-		$widthOrig = imagesx($this->resource);
924
-		$heightOrig = imagesy($this->resource);
925
-		if ($widthOrig === $heightOrig and $size == 0) {
926
-			return true;
927
-		}
928
-		$ratioOrig = $widthOrig / $heightOrig;
929
-		$width = $height = min($widthOrig, $heightOrig);
912
+    /**
913
+     * Crops the image to the middle square. If the image is already square it just returns.
914
+     *
915
+     * @param int $size maximum size for the result (optional)
916
+     * @return bool for success or failure
917
+     */
918
+    public function centerCrop($size = 0) {
919
+        if (!$this->valid()) {
920
+            $this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
921
+            return false;
922
+        }
923
+        $widthOrig = imagesx($this->resource);
924
+        $heightOrig = imagesy($this->resource);
925
+        if ($widthOrig === $heightOrig and $size == 0) {
926
+            return true;
927
+        }
928
+        $ratioOrig = $widthOrig / $heightOrig;
929
+        $width = $height = min($widthOrig, $heightOrig);
930 930
 
931
-		if ($ratioOrig > 1) {
932
-			$x = ($widthOrig / 2) - ($width / 2);
933
-			$y = 0;
934
-		} else {
935
-			$y = ($heightOrig / 2) - ($height / 2);
936
-			$x = 0;
937
-		}
938
-		if ($size > 0) {
939
-			$targetWidth = $size;
940
-			$targetHeight = $size;
941
-		} else {
942
-			$targetWidth = $width;
943
-			$targetHeight = $height;
944
-		}
945
-		$process = imagecreatetruecolor($targetWidth, $targetHeight);
946
-		if ($process == false) {
947
-			$this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
948
-			imagedestroy($process);
949
-			return false;
950
-		}
931
+        if ($ratioOrig > 1) {
932
+            $x = ($widthOrig / 2) - ($width / 2);
933
+            $y = 0;
934
+        } else {
935
+            $y = ($heightOrig / 2) - ($height / 2);
936
+            $x = 0;
937
+        }
938
+        if ($size > 0) {
939
+            $targetWidth = $size;
940
+            $targetHeight = $size;
941
+        } else {
942
+            $targetWidth = $width;
943
+            $targetHeight = $height;
944
+        }
945
+        $process = imagecreatetruecolor($targetWidth, $targetHeight);
946
+        if ($process == false) {
947
+            $this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
948
+            imagedestroy($process);
949
+            return false;
950
+        }
951 951
 
952
-		// preserve transparency
953
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
954
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
955
-			imagealphablending($process, false);
956
-			imagesavealpha($process, true);
957
-		}
952
+        // preserve transparency
953
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
954
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
955
+            imagealphablending($process, false);
956
+            imagesavealpha($process, true);
957
+        }
958 958
 
959
-		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
960
-		if ($process == false) {
961
-			$this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
962
-			imagedestroy($process);
963
-			return false;
964
-		}
965
-		imagedestroy($this->resource);
966
-		$this->resource = $process;
967
-		return true;
968
-	}
959
+        imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
960
+        if ($process == false) {
961
+            $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
962
+            imagedestroy($process);
963
+            return false;
964
+        }
965
+        imagedestroy($this->resource);
966
+        $this->resource = $process;
967
+        return true;
968
+    }
969 969
 
970
-	/**
971
-	 * Crops the image from point $x$y with dimension $wx$h.
972
-	 *
973
-	 * @param int $x Horizontal position
974
-	 * @param int $y Vertical position
975
-	 * @param int $w Width
976
-	 * @param int $h Height
977
-	 * @return bool for success or failure
978
-	 */
979
-	public function crop($x, $y, $w, $h) {
980
-		if (!$this->valid()) {
981
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
982
-			return false;
983
-		}
984
-		$process = imagecreatetruecolor($w, $h);
985
-		if ($process == false) {
986
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
987
-			imagedestroy($process);
988
-			return false;
989
-		}
970
+    /**
971
+     * Crops the image from point $x$y with dimension $wx$h.
972
+     *
973
+     * @param int $x Horizontal position
974
+     * @param int $y Vertical position
975
+     * @param int $w Width
976
+     * @param int $h Height
977
+     * @return bool for success or failure
978
+     */
979
+    public function crop($x, $y, $w, $h) {
980
+        if (!$this->valid()) {
981
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
982
+            return false;
983
+        }
984
+        $process = imagecreatetruecolor($w, $h);
985
+        if ($process == false) {
986
+            $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
987
+            imagedestroy($process);
988
+            return false;
989
+        }
990 990
 
991
-		// preserve transparency
992
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
993
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
994
-			imagealphablending($process, false);
995
-			imagesavealpha($process, true);
996
-		}
991
+        // preserve transparency
992
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
993
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
994
+            imagealphablending($process, false);
995
+            imagesavealpha($process, true);
996
+        }
997 997
 
998
-		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
999
-		if ($process == false) {
1000
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
1001
-			imagedestroy($process);
1002
-			return false;
1003
-		}
1004
-		imagedestroy($this->resource);
1005
-		$this->resource = $process;
1006
-		return true;
1007
-	}
998
+        imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
999
+        if ($process == false) {
1000
+            $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
1001
+            imagedestroy($process);
1002
+            return false;
1003
+        }
1004
+        imagedestroy($this->resource);
1005
+        $this->resource = $process;
1006
+        return true;
1007
+    }
1008 1008
 
1009
-	/**
1010
-	 * Resizes the image to fit within a boundary while preserving ratio.
1011
-	 *
1012
-	 * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
1013
-	 *
1014
-	 * @param integer $maxWidth
1015
-	 * @param integer $maxHeight
1016
-	 * @return bool
1017
-	 */
1018
-	public function fitIn($maxWidth, $maxHeight) {
1019
-		if (!$this->valid()) {
1020
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1021
-			return false;
1022
-		}
1023
-		$widthOrig = imagesx($this->resource);
1024
-		$heightOrig = imagesy($this->resource);
1025
-		$ratio = $widthOrig / $heightOrig;
1009
+    /**
1010
+     * Resizes the image to fit within a boundary while preserving ratio.
1011
+     *
1012
+     * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
1013
+     *
1014
+     * @param integer $maxWidth
1015
+     * @param integer $maxHeight
1016
+     * @return bool
1017
+     */
1018
+    public function fitIn($maxWidth, $maxHeight) {
1019
+        if (!$this->valid()) {
1020
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1021
+            return false;
1022
+        }
1023
+        $widthOrig = imagesx($this->resource);
1024
+        $heightOrig = imagesy($this->resource);
1025
+        $ratio = $widthOrig / $heightOrig;
1026 1026
 
1027
-		$newWidth = min($maxWidth, $ratio * $maxHeight);
1028
-		$newHeight = min($maxHeight, $maxWidth / $ratio);
1027
+        $newWidth = min($maxWidth, $ratio * $maxHeight);
1028
+        $newHeight = min($maxHeight, $maxWidth / $ratio);
1029 1029
 
1030
-		$this->preciseResize(round($newWidth), round($newHeight));
1031
-		return true;
1032
-	}
1030
+        $this->preciseResize(round($newWidth), round($newHeight));
1031
+        return true;
1032
+    }
1033 1033
 
1034
-	/**
1035
-	 * Shrinks larger images to fit within specified boundaries while preserving ratio.
1036
-	 *
1037
-	 * @param integer $maxWidth
1038
-	 * @param integer $maxHeight
1039
-	 * @return bool
1040
-	 */
1041
-	public function scaleDownToFit($maxWidth, $maxHeight) {
1042
-		if (!$this->valid()) {
1043
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1044
-			return false;
1045
-		}
1046
-		$widthOrig = imagesx($this->resource);
1047
-		$heightOrig = imagesy($this->resource);
1034
+    /**
1035
+     * Shrinks larger images to fit within specified boundaries while preserving ratio.
1036
+     *
1037
+     * @param integer $maxWidth
1038
+     * @param integer $maxHeight
1039
+     * @return bool
1040
+     */
1041
+    public function scaleDownToFit($maxWidth, $maxHeight) {
1042
+        if (!$this->valid()) {
1043
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1044
+            return false;
1045
+        }
1046
+        $widthOrig = imagesx($this->resource);
1047
+        $heightOrig = imagesy($this->resource);
1048 1048
 
1049
-		if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
1050
-			return $this->fitIn($maxWidth, $maxHeight);
1051
-		}
1049
+        if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
1050
+            return $this->fitIn($maxWidth, $maxHeight);
1051
+        }
1052 1052
 
1053
-		return false;
1054
-	}
1053
+        return false;
1054
+    }
1055 1055
 
1056
-	/**
1057
-	 * Destroys the current image and resets the object
1058
-	 */
1059
-	public function destroy() {
1060
-		if ($this->valid()) {
1061
-			imagedestroy($this->resource);
1062
-		}
1063
-		$this->resource = null;
1064
-	}
1056
+    /**
1057
+     * Destroys the current image and resets the object
1058
+     */
1059
+    public function destroy() {
1060
+        if ($this->valid()) {
1061
+            imagedestroy($this->resource);
1062
+        }
1063
+        $this->resource = null;
1064
+    }
1065 1065
 
1066
-	public function __destruct() {
1067
-		$this->destroy();
1068
-	}
1066
+    public function __destruct() {
1067
+        $this->destroy();
1068
+    }
1069 1069
 }
1070 1070
 
1071 1071
 if (!function_exists('imagebmp')) {
1072
-	/**
1073
-	 * Output a BMP image to either the browser or a file
1074
-	 *
1075
-	 * @link http://www.ugia.cn/wp-data/imagebmp.php
1076
-	 * @author legend <[email protected]>
1077
-	 * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
1078
-	 * @author mgutt <[email protected]>
1079
-	 * @version 1.00
1080
-	 * @param resource $im
1081
-	 * @param string $fileName [optional] <p>The path to save the file to.</p>
1082
-	 * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
1083
-	 * @param int $compression [optional]
1084
-	 * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
1085
-	 */
1086
-	function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
1087
-		if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
1088
-			$bit = 24;
1089
-		} else if ($bit == 32) {
1090
-			$bit = 24;
1091
-		}
1092
-		$bits = pow(2, $bit);
1093
-		imagetruecolortopalette($im, true, $bits);
1094
-		$width = imagesx($im);
1095
-		$height = imagesy($im);
1096
-		$colorsNum = imagecolorstotal($im);
1097
-		$rgbQuad = '';
1098
-		if ($bit <= 8) {
1099
-			for ($i = 0; $i < $colorsNum; $i++) {
1100
-				$colors = imagecolorsforindex($im, $i);
1101
-				$rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
1102
-			}
1103
-			$bmpData = '';
1104
-			if ($compression == 0 || $bit < 8) {
1105
-				$compression = 0;
1106
-				$extra = '';
1107
-				$padding = 4 - ceil($width / (8 / $bit)) % 4;
1108
-				if ($padding % 4 != 0) {
1109
-					$extra = str_repeat("\0", $padding);
1110
-				}
1111
-				for ($j = $height - 1; $j >= 0; $j--) {
1112
-					$i = 0;
1113
-					while ($i < $width) {
1114
-						$bin = 0;
1115
-						$limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
1116
-						for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
1117
-							$index = imagecolorat($im, $i, $j);
1118
-							$bin |= $index << $k;
1119
-							$i++;
1120
-						}
1121
-						$bmpData .= chr($bin);
1122
-					}
1123
-					$bmpData .= $extra;
1124
-				}
1125
-			} // RLE8
1126
-			else if ($compression == 1 && $bit == 8) {
1127
-				for ($j = $height - 1; $j >= 0; $j--) {
1128
-					$lastIndex = "\0";
1129
-					$sameNum = 0;
1130
-					for ($i = 0; $i <= $width; $i++) {
1131
-						$index = imagecolorat($im, $i, $j);
1132
-						if ($index !== $lastIndex || $sameNum > 255) {
1133
-							if ($sameNum != 0) {
1134
-								$bmpData .= chr($sameNum) . chr($lastIndex);
1135
-							}
1136
-							$lastIndex = $index;
1137
-							$sameNum = 1;
1138
-						} else {
1139
-							$sameNum++;
1140
-						}
1141
-					}
1142
-					$bmpData .= "\0\0";
1143
-				}
1144
-				$bmpData .= "\0\1";
1145
-			}
1146
-			$sizeQuad = strlen($rgbQuad);
1147
-			$sizeData = strlen($bmpData);
1148
-		} else {
1149
-			$extra = '';
1150
-			$padding = 4 - ($width * ($bit / 8)) % 4;
1151
-			if ($padding % 4 != 0) {
1152
-				$extra = str_repeat("\0", $padding);
1153
-			}
1154
-			$bmpData = '';
1155
-			for ($j = $height - 1; $j >= 0; $j--) {
1156
-				for ($i = 0; $i < $width; $i++) {
1157
-					$index = imagecolorat($im, $i, $j);
1158
-					$colors = imagecolorsforindex($im, $index);
1159
-					if ($bit == 16) {
1160
-						$bin = 0 << $bit;
1161
-						$bin |= ($colors['red'] >> 3) << 10;
1162
-						$bin |= ($colors['green'] >> 3) << 5;
1163
-						$bin |= $colors['blue'] >> 3;
1164
-						$bmpData .= pack("v", $bin);
1165
-					} else {
1166
-						$bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
1167
-					}
1168
-				}
1169
-				$bmpData .= $extra;
1170
-			}
1171
-			$sizeQuad = 0;
1172
-			$sizeData = strlen($bmpData);
1173
-			$colorsNum = 0;
1174
-		}
1175
-		$fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1176
-		$infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
1177
-		if ($fileName != '') {
1178
-			$fp = fopen($fileName, 'wb');
1179
-			fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
1180
-			fclose($fp);
1181
-			return true;
1182
-		}
1183
-		echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
1184
-		return true;
1185
-	}
1072
+    /**
1073
+     * Output a BMP image to either the browser or a file
1074
+     *
1075
+     * @link http://www.ugia.cn/wp-data/imagebmp.php
1076
+     * @author legend <[email protected]>
1077
+     * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
1078
+     * @author mgutt <[email protected]>
1079
+     * @version 1.00
1080
+     * @param resource $im
1081
+     * @param string $fileName [optional] <p>The path to save the file to.</p>
1082
+     * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
1083
+     * @param int $compression [optional]
1084
+     * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
1085
+     */
1086
+    function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
1087
+        if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
1088
+            $bit = 24;
1089
+        } else if ($bit == 32) {
1090
+            $bit = 24;
1091
+        }
1092
+        $bits = pow(2, $bit);
1093
+        imagetruecolortopalette($im, true, $bits);
1094
+        $width = imagesx($im);
1095
+        $height = imagesy($im);
1096
+        $colorsNum = imagecolorstotal($im);
1097
+        $rgbQuad = '';
1098
+        if ($bit <= 8) {
1099
+            for ($i = 0; $i < $colorsNum; $i++) {
1100
+                $colors = imagecolorsforindex($im, $i);
1101
+                $rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
1102
+            }
1103
+            $bmpData = '';
1104
+            if ($compression == 0 || $bit < 8) {
1105
+                $compression = 0;
1106
+                $extra = '';
1107
+                $padding = 4 - ceil($width / (8 / $bit)) % 4;
1108
+                if ($padding % 4 != 0) {
1109
+                    $extra = str_repeat("\0", $padding);
1110
+                }
1111
+                for ($j = $height - 1; $j >= 0; $j--) {
1112
+                    $i = 0;
1113
+                    while ($i < $width) {
1114
+                        $bin = 0;
1115
+                        $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
1116
+                        for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
1117
+                            $index = imagecolorat($im, $i, $j);
1118
+                            $bin |= $index << $k;
1119
+                            $i++;
1120
+                        }
1121
+                        $bmpData .= chr($bin);
1122
+                    }
1123
+                    $bmpData .= $extra;
1124
+                }
1125
+            } // RLE8
1126
+            else if ($compression == 1 && $bit == 8) {
1127
+                for ($j = $height - 1; $j >= 0; $j--) {
1128
+                    $lastIndex = "\0";
1129
+                    $sameNum = 0;
1130
+                    for ($i = 0; $i <= $width; $i++) {
1131
+                        $index = imagecolorat($im, $i, $j);
1132
+                        if ($index !== $lastIndex || $sameNum > 255) {
1133
+                            if ($sameNum != 0) {
1134
+                                $bmpData .= chr($sameNum) . chr($lastIndex);
1135
+                            }
1136
+                            $lastIndex = $index;
1137
+                            $sameNum = 1;
1138
+                        } else {
1139
+                            $sameNum++;
1140
+                        }
1141
+                    }
1142
+                    $bmpData .= "\0\0";
1143
+                }
1144
+                $bmpData .= "\0\1";
1145
+            }
1146
+            $sizeQuad = strlen($rgbQuad);
1147
+            $sizeData = strlen($bmpData);
1148
+        } else {
1149
+            $extra = '';
1150
+            $padding = 4 - ($width * ($bit / 8)) % 4;
1151
+            if ($padding % 4 != 0) {
1152
+                $extra = str_repeat("\0", $padding);
1153
+            }
1154
+            $bmpData = '';
1155
+            for ($j = $height - 1; $j >= 0; $j--) {
1156
+                for ($i = 0; $i < $width; $i++) {
1157
+                    $index = imagecolorat($im, $i, $j);
1158
+                    $colors = imagecolorsforindex($im, $index);
1159
+                    if ($bit == 16) {
1160
+                        $bin = 0 << $bit;
1161
+                        $bin |= ($colors['red'] >> 3) << 10;
1162
+                        $bin |= ($colors['green'] >> 3) << 5;
1163
+                        $bin |= $colors['blue'] >> 3;
1164
+                        $bmpData .= pack("v", $bin);
1165
+                    } else {
1166
+                        $bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
1167
+                    }
1168
+                }
1169
+                $bmpData .= $extra;
1170
+            }
1171
+            $sizeQuad = 0;
1172
+            $sizeData = strlen($bmpData);
1173
+            $colorsNum = 0;
1174
+        }
1175
+        $fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1176
+        $infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
1177
+        if ($fileName != '') {
1178
+            $fp = fopen($fileName, 'wb');
1179
+            fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
1180
+            fclose($fp);
1181
+            return true;
1182
+        }
1183
+        echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
1184
+        return true;
1185
+    }
1186 1186
 }
1187 1187
 
1188 1188
 if (!function_exists('exif_imagetype')) {
1189
-	/**
1190
-	 * Workaround if exif_imagetype does not exist
1191
-	 *
1192
-	 * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
1193
-	 * @param string $fileName
1194
-	 * @return string|boolean
1195
-	 */
1196
-	function exif_imagetype($fileName) {
1197
-		if (($info = getimagesize($fileName)) !== false) {
1198
-			return $info[2];
1199
-		}
1200
-		return false;
1201
-	}
1189
+    /**
1190
+     * Workaround if exif_imagetype does not exist
1191
+     *
1192
+     * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
1193
+     * @param string $fileName
1194
+     * @return string|boolean
1195
+     */
1196
+    function exif_imagetype($fileName) {
1197
+        if (($info = getimagesize($fileName)) !== false) {
1198
+            return $info[2];
1199
+        }
1200
+        return false;
1201
+    }
1202 1202
 }
Please login to merge, or discard this patch.
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 */
146 146
 	public function widthTopLeft() {
147 147
 		$o = $this->getOrientation();
148
-		$this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
148
+		$this->logger->debug('OC_Image->widthTopLeft() Orientation: '.$o, array('app' => 'core'));
149 149
 		switch ($o) {
150 150
 			case -1:
151 151
 			case 1:
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 	 */
170 170
 	public function heightTopLeft() {
171 171
 		$o = $this->getOrientation();
172
-		$this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
172
+		$this->logger->debug('OC_Image->heightTopLeft() Orientation: '.$o, array('app' => 'core'));
173 173
 		switch ($o) {
174 174
 			case -1:
175 175
 			case 1:
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 		if ($mimeType === null) {
197 197
 			$mimeType = $this->mimeType();
198 198
 		}
199
-		header('Content-Type: ' . $mimeType);
199
+		header('Content-Type: '.$mimeType);
200 200
 		return $this->_output(null, $mimeType);
201 201
 	}
202 202
 
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 		}
215 215
 		if ($filePath === null) {
216 216
 			if ($this->filePath === null) {
217
-				$this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
217
+				$this->logger->error(__METHOD__.'(): called with no path.', array('app' => 'core'));
218 218
 				return false;
219 219
 			} else {
220 220
 				$filePath = $this->filePath;
@@ -238,10 +238,10 @@  discard block
 block discarded – undo
238 238
 			}
239 239
 			$isWritable = is_writable(dirname($filePath));
240 240
 			if (!$isWritable) {
241
-				$this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
241
+				$this->logger->error(__METHOD__.'(): Directory \''.dirname($filePath).'\' is not writable.', array('app' => 'core'));
242 242
 				return false;
243 243
 			} elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
244
-				$this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
244
+				$this->logger->error(__METHOD__.'(): File \''.$filePath.'\' is not writable.', array('app' => 'core'));
245 245
 				return false;
246 246
 			}
247 247
 		}
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 					$imageType = IMAGETYPE_BMP;
270 270
 					break;
271 271
 				default:
272
-					throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
272
+					throw new Exception('\OC_Image::_output(): "'.$mimeType.'" is not supported when forcing a specific output format');
273 273
 			}
274 274
 		}
275 275
 
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
 			return;
418 418
 		}
419 419
 
420
-		$exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
420
+		$exif = @exif_read_data('data://image/jpeg;base64,'.base64_encode($data));
421 421
 		if (!$exif) {
422 422
 			return;
423 423
 		}
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 	 */
436 436
 	public function fixOrientation() {
437 437
 		$o = $this->getOrientation();
438
-		$this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
438
+		$this->logger->debug('OC_Image->fixOrientation() Orientation: '.$o, array('app' => 'core'));
439 439
 		$rotate = 0;
440 440
 		$flip = false;
441 441
 		switch ($o) {
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 				$rotate = 90;
471 471
 				break;
472 472
 		}
473
-		if($flip && function_exists('imageflip')) {
473
+		if ($flip && function_exists('imageflip')) {
474 474
 			imageflip($this->resource, IMG_FLIP_HORIZONTAL);
475 475
 		}
476 476
 		if ($rotate) {
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
 		} elseif ($this->loadFromData($imageRef) !== false) {
519 519
 			return $this->resource;
520 520
 		}
521
-		$this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
521
+		$this->logger->debug(__METHOD__.'(): could not load anything. Giving up!', array('app' => 'core'));
522 522
 		return false;
523 523
 	}
524 524
 
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 					imagealphablending($this->resource, true);
558 558
 					imagesavealpha($this->resource, true);
559 559
 				} else {
560
-					$this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
560
+					$this->logger->debug('OC_Image->loadFromFile, GIF images not supported: '.$imagePath, array('app' => 'core'));
561 561
 				}
562 562
 				break;
563 563
 			case IMAGETYPE_JPEG:
@@ -565,10 +565,10 @@  discard block
 block discarded – undo
565 565
 					if (getimagesize($imagePath) !== false) {
566 566
 						$this->resource = @imagecreatefromjpeg($imagePath);
567 567
 					} else {
568
-						$this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
568
+						$this->logger->debug('OC_Image->loadFromFile, JPG image not valid: '.$imagePath, array('app' => 'core'));
569 569
 					}
570 570
 				} else {
571
-					$this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
571
+					$this->logger->debug('OC_Image->loadFromFile, JPG images not supported: '.$imagePath, array('app' => 'core'));
572 572
 				}
573 573
 				break;
574 574
 			case IMAGETYPE_PNG:
@@ -578,21 +578,21 @@  discard block
 block discarded – undo
578 578
 					imagealphablending($this->resource, true);
579 579
 					imagesavealpha($this->resource, true);
580 580
 				} else {
581
-					$this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
581
+					$this->logger->debug('OC_Image->loadFromFile, PNG images not supported: '.$imagePath, array('app' => 'core'));
582 582
 				}
583 583
 				break;
584 584
 			case IMAGETYPE_XBM:
585 585
 				if (imagetypes() & IMG_XPM) {
586 586
 					$this->resource = @imagecreatefromxbm($imagePath);
587 587
 				} else {
588
-					$this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
588
+					$this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: '.$imagePath, array('app' => 'core'));
589 589
 				}
590 590
 				break;
591 591
 			case IMAGETYPE_WBMP:
592 592
 				if (imagetypes() & IMG_WBMP) {
593 593
 					$this->resource = @imagecreatefromwbmp($imagePath);
594 594
 				} else {
595
-					$this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
595
+					$this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: '.$imagePath, array('app' => 'core'));
596 596
 				}
597 597
 				break;
598 598
 			case IMAGETYPE_BMP:
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 	 */
703 703
 	private function imagecreatefrombmp($fileName) {
704 704
 		if (!($fh = fopen($fileName, 'rb'))) {
705
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
705
+			$this->logger->warning('imagecreatefrombmp: Can not open '.$fileName, array('app' => 'core'));
706 706
 			return false;
707 707
 		}
708 708
 		// read file header
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
 		// check for bitmap
711 711
 		if ($meta['type'] != 19778) {
712 712
 			fclose($fh);
713
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
713
+			$this->logger->warning('imagecreatefrombmp: Can not open '.$fileName.' is not a bitmap!', array('app' => 'core'));
714 714
 			return false;
715 715
 		}
716 716
 		// read image header
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 				$meta['imagesize'] = @filesize($fileName) - $meta['offset'];
735 735
 				if ($meta['imagesize'] < 1) {
736 736
 					fclose($fh);
737
-					$this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
737
+					$this->logger->warning('imagecreatefrombmp: Can not obtain file size of '.$fileName.' is not a bitmap!', array('app' => 'core'));
738 738
 					return false;
739 739
 				}
740 740
 			}
@@ -744,7 +744,7 @@  discard block
 block discarded – undo
744 744
 		// read color palette
745 745
 		$palette = array();
746 746
 		if ($meta['bits'] < 16) {
747
-			$palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
747
+			$palette = unpack('l'.$meta['colors'], fread($fh, $meta['colors'] * 4));
748 748
 			// in rare cases the color value is signed
749 749
 			if ($palette[1] < 0) {
750 750
 				foreach ($palette as $i => $color) {
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 		if ($im == false) {
758 758
 			fclose($fh);
759 759
 			$this->logger->warning(
760
-				'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
760
+				'imagecreatefrombmp: imagecreatetruecolor failed for file "'.$fileName.'" with dimensions '.$meta['width'].'x'.$meta['height'],
761 761
 				array('app' => 'core'));
762 762
 			return false;
763 763
 		}
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 		$p = 0;
767 767
 		$vide = chr(0);
768 768
 		$y = $meta['height'] - 1;
769
-		$error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
769
+		$error = 'imagecreatefrombmp: '.$fileName.' has not enough data!';
770 770
 		// loop through the image data beginning with the lower left corner
771 771
 		while ($y >= 0) {
772 772
 			$x = 0;
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 							$this->logger->warning($error, array('app' => 'core'));
779 779
 							return $im;
780 780
 						}
781
-						$color = @unpack('V', $part . $vide);
781
+						$color = @unpack('V', $part.$vide);
782 782
 						break;
783 783
 					case 16:
784 784
 						if (!($part = substr($data, $p, 2))) {
@@ -790,16 +790,16 @@  discard block
 block discarded – undo
790 790
 						$color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
791 791
 						break;
792 792
 					case 8:
793
-						$color = @unpack('n', $vide . substr($data, $p, 1));
793
+						$color = @unpack('n', $vide.substr($data, $p, 1));
794 794
 						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
795 795
 						break;
796 796
 					case 4:
797
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
797
+						$color = @unpack('n', $vide.substr($data, floor($p), 1));
798 798
 						$color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
799 799
 						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
800 800
 						break;
801 801
 					case 1:
802
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
802
+						$color = @unpack('n', $vide.substr($data, floor($p), 1));
803 803
 						switch (($p * 8) % 8) {
804 804
 							case 0:
805 805
 								$color[1] = $color[1] >> 7;
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 						break;
831 831
 					default:
832 832
 						fclose($fh);
833
-						$this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
833
+						$this->logger->warning('imagecreatefrombmp: '.$fileName.' has '.$meta['bits'].' bits and this is not supported!', array('app' => 'core'));
834 834
 						return false;
835 835
 				}
836 836
 				imagesetpixel($im, $x, $y, $color[1]);
@@ -852,7 +852,7 @@  discard block
 block discarded – undo
852 852
 	 */
853 853
 	public function resize($maxSize) {
854 854
 		if (!$this->valid()) {
855
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
855
+			$this->logger->error(__METHOD__.'(): No image loaded', array('app' => 'core'));
856 856
 			return false;
857 857
 		}
858 858
 		$widthOrig = imagesx($this->resource);
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 	 */
879 879
 	public function preciseResize($width, $height) {
880 880
 		if (!$this->valid()) {
881
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
881
+			$this->logger->error(__METHOD__.'(): No image loaded', array('app' => 'core'));
882 882
 			return false;
883 883
 		}
884 884
 		$widthOrig = imagesx($this->resource);
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
 		$process = imagecreatetruecolor($width, $height);
887 887
 
888 888
 		if ($process == false) {
889
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
889
+			$this->logger->error(__METHOD__.'(): Error creating true color image', array('app' => 'core'));
890 890
 			imagedestroy($process);
891 891
 			return false;
892 892
 		}
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 
901 901
 		imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
902 902
 		if ($process == false) {
903
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
903
+			$this->logger->error(__METHOD__.'(): Error re-sampling process image', array('app' => 'core'));
904 904
 			imagedestroy($process);
905 905
 			return false;
906 906
 		}
@@ -958,7 +958,7 @@  discard block
 block discarded – undo
958 958
 
959 959
 		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
960 960
 		if ($process == false) {
961
-			$this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
961
+			$this->logger->error('OC_Image->centerCrop, Error re-sampling process image '.$width.'x'.$height, array('app' => 'core'));
962 962
 			imagedestroy($process);
963 963
 			return false;
964 964
 		}
@@ -978,12 +978,12 @@  discard block
 block discarded – undo
978 978
 	 */
979 979
 	public function crop($x, $y, $w, $h) {
980 980
 		if (!$this->valid()) {
981
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
981
+			$this->logger->error(__METHOD__.'(): No image loaded', array('app' => 'core'));
982 982
 			return false;
983 983
 		}
984 984
 		$process = imagecreatetruecolor($w, $h);
985 985
 		if ($process == false) {
986
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
986
+			$this->logger->error(__METHOD__.'(): Error creating true color image', array('app' => 'core'));
987 987
 			imagedestroy($process);
988 988
 			return false;
989 989
 		}
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
 
998 998
 		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
999 999
 		if ($process == false) {
1000
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
1000
+			$this->logger->error(__METHOD__.'(): Error re-sampling process image '.$w.'x'.$h, array('app' => 'core'));
1001 1001
 			imagedestroy($process);
1002 1002
 			return false;
1003 1003
 		}
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
 	 */
1018 1018
 	public function fitIn($maxWidth, $maxHeight) {
1019 1019
 		if (!$this->valid()) {
1020
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1020
+			$this->logger->error(__METHOD__.'(): No image loaded', array('app' => 'core'));
1021 1021
 			return false;
1022 1022
 		}
1023 1023
 		$widthOrig = imagesx($this->resource);
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 	 */
1041 1041
 	public function scaleDownToFit($maxWidth, $maxHeight) {
1042 1042
 		if (!$this->valid()) {
1043
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1043
+			$this->logger->error(__METHOD__.'(): No image loaded', array('app' => 'core'));
1044 1044
 			return false;
1045 1045
 		}
1046 1046
 		$widthOrig = imagesx($this->resource);
@@ -1098,7 +1098,7 @@  discard block
 block discarded – undo
1098 1098
 		if ($bit <= 8) {
1099 1099
 			for ($i = 0; $i < $colorsNum; $i++) {
1100 1100
 				$colors = imagecolorsforindex($im, $i);
1101
-				$rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
1101
+				$rgbQuad .= chr($colors['blue']).chr($colors['green']).chr($colors['red'])."\0";
1102 1102
 			}
1103 1103
 			$bmpData = '';
1104 1104
 			if ($compression == 0 || $bit < 8) {
@@ -1131,7 +1131,7 @@  discard block
 block discarded – undo
1131 1131
 						$index = imagecolorat($im, $i, $j);
1132 1132
 						if ($index !== $lastIndex || $sameNum > 255) {
1133 1133
 							if ($sameNum != 0) {
1134
-								$bmpData .= chr($sameNum) . chr($lastIndex);
1134
+								$bmpData .= chr($sameNum).chr($lastIndex);
1135 1135
 							}
1136 1136
 							$lastIndex = $index;
1137 1137
 							$sameNum = 1;
@@ -1172,15 +1172,15 @@  discard block
 block discarded – undo
1172 1172
 			$sizeData = strlen($bmpData);
1173 1173
 			$colorsNum = 0;
1174 1174
 		}
1175
-		$fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1175
+		$fileHeader = 'BM'.pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1176 1176
 		$infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
1177 1177
 		if ($fileName != '') {
1178 1178
 			$fp = fopen($fileName, 'wb');
1179
-			fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
1179
+			fwrite($fp, $fileHeader.$infoHeader.$rgbQuad.$bmpData);
1180 1180
 			fclose($fp);
1181 1181
 			return true;
1182 1182
 		}
1183
-		echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
1183
+		echo $fileHeader.$infoHeader.$rgbQuad.$bmpData;
1184 1184
 		return true;
1185 1185
 	}
1186 1186
 }
Please login to merge, or discard this patch.
lib/private/PreviewManager.php 1 patch
Indentation   +381 added lines, -381 removed lines patch added patch discarded remove patch
@@ -38,385 +38,385 @@
 block discarded – undo
38 38
 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
39 39
 
40 40
 class PreviewManager implements IPreview {
41
-	/** @var IConfig */
42
-	protected $config;
43
-
44
-	/** @var IRootFolder */
45
-	protected $rootFolder;
46
-
47
-	/** @var IAppData */
48
-	protected $appData;
49
-
50
-	/** @var EventDispatcherInterface */
51
-	protected $eventDispatcher;
52
-
53
-	/** @var Generator */
54
-	private $generator;
55
-
56
-	/** @var bool */
57
-	protected $providerListDirty = false;
58
-
59
-	/** @var bool */
60
-	protected $registeredCoreProviders = false;
61
-
62
-	/** @var array */
63
-	protected $providers = [];
64
-
65
-	/** @var array mime type => support status */
66
-	protected $mimeTypeSupportMap = [];
67
-
68
-	/** @var array */
69
-	protected $defaultProviders;
70
-
71
-	/** @var string */
72
-	protected $userId;
73
-
74
-	/**
75
-	 * PreviewManager constructor.
76
-	 *
77
-	 * @param IConfig $config
78
-	 * @param IRootFolder $rootFolder
79
-	 * @param IAppData $appData
80
-	 * @param EventDispatcherInterface $eventDispatcher
81
-	 * @param string $userId
82
-	 */
83
-	public function __construct(IConfig $config,
84
-								IRootFolder $rootFolder,
85
-								IAppData $appData,
86
-								EventDispatcherInterface $eventDispatcher,
87
-								$userId) {
88
-		$this->config = $config;
89
-		$this->rootFolder = $rootFolder;
90
-		$this->appData = $appData;
91
-		$this->eventDispatcher = $eventDispatcher;
92
-		$this->userId = $userId;
93
-	}
94
-
95
-	/**
96
-	 * In order to improve lazy loading a closure can be registered which will be
97
-	 * called in case preview providers are actually requested
98
-	 *
99
-	 * $callable has to return an instance of \OCP\Preview\IProvider
100
-	 *
101
-	 * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
102
-	 * @param \Closure $callable
103
-	 * @return void
104
-	 */
105
-	public function registerProvider($mimeTypeRegex, \Closure $callable) {
106
-		if (!$this->config->getSystemValue('enable_previews', true)) {
107
-			return;
108
-		}
109
-
110
-		if (!isset($this->providers[$mimeTypeRegex])) {
111
-			$this->providers[$mimeTypeRegex] = [];
112
-		}
113
-		$this->providers[$mimeTypeRegex][] = $callable;
114
-		$this->providerListDirty = true;
115
-	}
116
-
117
-	/**
118
-	 * Get all providers
119
-	 * @return array
120
-	 */
121
-	public function getProviders() {
122
-		if (!$this->config->getSystemValue('enable_previews', true)) {
123
-			return [];
124
-		}
125
-
126
-		$this->registerCoreProviders();
127
-		if ($this->providerListDirty) {
128
-			$keys = array_map('strlen', array_keys($this->providers));
129
-			array_multisort($keys, SORT_DESC, $this->providers);
130
-			$this->providerListDirty = false;
131
-		}
132
-
133
-		return $this->providers;
134
-	}
135
-
136
-	/**
137
-	 * Does the manager have any providers
138
-	 * @return bool
139
-	 */
140
-	public function hasProviders() {
141
-		$this->registerCoreProviders();
142
-		return !empty($this->providers);
143
-	}
144
-
145
-	/**
146
-	 * return a preview of a file
147
-	 *
148
-	 * @param string $file The path to the file where you want a thumbnail from
149
-	 * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image
150
-	 * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image
151
-	 * @param boolean $scaleUp Scale smaller images up to the thumbnail size or not. Might look ugly
152
-	 * @return \OCP\IImage
153
-	 * @deprecated 11 Use getPreview
154
-	 */
155
-	public function createPreview($file, $maxX = 100, $maxY = 75, $scaleUp = false) {
156
-		try {
157
-			$userRoot = $this->rootFolder->getUserFolder($this->userId)->getParent();
158
-			$node = $userRoot->get($file);
159
-			if (!($file instanceof File)) {
160
-				throw new NotFoundException();
161
-			}
162
-
163
-			$preview = $this->getPreview($node, $maxX, $maxY);
164
-		} catch (\Exception $e) {
165
-			return new \OC_Image();
166
-		}
167
-
168
-		return new \OC_Image($preview->getContent());
169
-	}
170
-
171
-	/**
172
-	 * Returns a preview of a file
173
-	 *
174
-	 * The cache is searched first and if nothing usable was found then a preview is
175
-	 * generated by one of the providers
176
-	 *
177
-	 * @param File $file
178
-	 * @param int $width
179
-	 * @param int $height
180
-	 * @param bool $crop
181
-	 * @param string $mode
182
-	 * @param string $mimeType
183
-	 * @return ISimpleFile
184
-	 * @throws NotFoundException
185
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
186
-	 * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
187
-	 */
188
-	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
189
-		if ($this->generator === null) {
190
-			$this->generator = new Generator(
191
-				$this->config,
192
-				$this,
193
-				$this->appData,
194
-				new GeneratorHelper(
195
-					$this->rootFolder
196
-				),
197
-				$this->eventDispatcher
198
-			);
199
-		}
200
-
201
-		return $this->generator->getPreview($file, $width, $height, $crop, $mode, $mimeType);
202
-	}
203
-
204
-	/**
205
-	 * returns true if the passed mime type is supported
206
-	 *
207
-	 * @param string $mimeType
208
-	 * @return boolean
209
-	 */
210
-	public function isMimeSupported($mimeType = '*') {
211
-		if (!$this->config->getSystemValue('enable_previews', true)) {
212
-			return false;
213
-		}
214
-
215
-		if (isset($this->mimeTypeSupportMap[$mimeType])) {
216
-			return $this->mimeTypeSupportMap[$mimeType];
217
-		}
218
-
219
-		$this->registerCoreProviders();
220
-		$providerMimeTypes = array_keys($this->providers);
221
-		foreach ($providerMimeTypes as $supportedMimeType) {
222
-			if (preg_match($supportedMimeType, $mimeType)) {
223
-				$this->mimeTypeSupportMap[$mimeType] = true;
224
-				return true;
225
-			}
226
-		}
227
-		$this->mimeTypeSupportMap[$mimeType] = false;
228
-		return false;
229
-	}
230
-
231
-	/**
232
-	 * Check if a preview can be generated for a file
233
-	 *
234
-	 * @param \OCP\Files\FileInfo $file
235
-	 * @return bool
236
-	 */
237
-	public function isAvailable(\OCP\Files\FileInfo $file) {
238
-		if (!$this->config->getSystemValue('enable_previews', true)) {
239
-			return false;
240
-		}
241
-
242
-		$this->registerCoreProviders();
243
-		if (!$this->isMimeSupported($file->getMimetype())) {
244
-			return false;
245
-		}
246
-
247
-		$mount = $file->getMountPoint();
248
-		if ($mount and !$mount->getOption('previews', true)){
249
-			return false;
250
-		}
251
-
252
-		foreach ($this->providers as $supportedMimeType => $providers) {
253
-			if (preg_match($supportedMimeType, $file->getMimetype())) {
254
-				foreach ($providers as $closure) {
255
-					$provider = $closure();
256
-					if (!($provider instanceof IProvider)) {
257
-						continue;
258
-					}
259
-
260
-					/** @var $provider IProvider */
261
-					if ($provider->isAvailable($file)) {
262
-						return true;
263
-					}
264
-				}
265
-			}
266
-		}
267
-		return false;
268
-	}
269
-
270
-	/**
271
-	 * List of enabled default providers
272
-	 *
273
-	 * The following providers are enabled by default:
274
-	 *  - OC\Preview\PNG
275
-	 *  - OC\Preview\JPEG
276
-	 *  - OC\Preview\GIF
277
-	 *  - OC\Preview\BMP
278
-	 *  - OC\Preview\XBitmap
279
-	 *  - OC\Preview\MarkDown
280
-	 *  - OC\Preview\MP3
281
-	 *  - OC\Preview\TXT
282
-	 *
283
-	 * The following providers are disabled by default due to performance or privacy concerns:
284
-	 *  - OC\Preview\Font
285
-	 *  - OC\Preview\Illustrator
286
-	 *  - OC\Preview\Movie
287
-	 *  - OC\Preview\MSOfficeDoc
288
-	 *  - OC\Preview\MSOffice2003
289
-	 *  - OC\Preview\MSOffice2007
290
-	 *  - OC\Preview\OpenDocument
291
-	 *  - OC\Preview\PDF
292
-	 *  - OC\Preview\Photoshop
293
-	 *  - OC\Preview\Postscript
294
-	 *  - OC\Preview\StarOffice
295
-	 *  - OC\Preview\SVG
296
-	 *  - OC\Preview\TIFF
297
-	 *
298
-	 * @return array
299
-	 */
300
-	protected function getEnabledDefaultProvider() {
301
-		if ($this->defaultProviders !== null) {
302
-			return $this->defaultProviders;
303
-		}
304
-
305
-		$imageProviders = [
306
-			'OC\Preview\PNG',
307
-			'OC\Preview\JPEG',
308
-			'OC\Preview\GIF',
309
-			'OC\Preview\BMP',
310
-			'OC\Preview\XBitmap'
311
-		];
312
-
313
-		$this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
314
-			'OC\Preview\MarkDown',
315
-			'OC\Preview\MP3',
316
-			'OC\Preview\TXT',
317
-		], $imageProviders));
318
-
319
-		if (in_array('OC\Preview\Image', $this->defaultProviders)) {
320
-			$this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
321
-		}
322
-		$this->defaultProviders = array_unique($this->defaultProviders);
323
-		return $this->defaultProviders;
324
-	}
325
-
326
-	/**
327
-	 * Register the default providers (if enabled)
328
-	 *
329
-	 * @param string $class
330
-	 * @param string $mimeType
331
-	 */
332
-	protected function registerCoreProvider($class, $mimeType, $options = []) {
333
-		if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
334
-			$this->registerProvider($mimeType, function () use ($class, $options) {
335
-				return new $class($options);
336
-			});
337
-		}
338
-	}
339
-
340
-	/**
341
-	 * Register the default providers (if enabled)
342
-	 */
343
-	protected function registerCoreProviders() {
344
-		if ($this->registeredCoreProviders) {
345
-			return;
346
-		}
347
-		$this->registeredCoreProviders = true;
348
-
349
-		$this->registerCoreProvider('OC\Preview\TXT', '/text\/plain/');
350
-		$this->registerCoreProvider('OC\Preview\MarkDown', '/text\/(x-)?markdown/');
351
-		$this->registerCoreProvider('OC\Preview\PNG', '/image\/png/');
352
-		$this->registerCoreProvider('OC\Preview\JPEG', '/image\/jpeg/');
353
-		$this->registerCoreProvider('OC\Preview\GIF', '/image\/gif/');
354
-		$this->registerCoreProvider('OC\Preview\BMP', '/image\/bmp/');
355
-		$this->registerCoreProvider('OC\Preview\XBitmap', '/image\/x-xbitmap/');
356
-		$this->registerCoreProvider('OC\Preview\MP3', '/audio\/mpeg/');
357
-
358
-		// SVG, Office and Bitmap require imagick
359
-		if (extension_loaded('imagick')) {
360
-			$checkImagick = new \Imagick();
361
-
362
-			$imagickProviders = [
363
-				'SVG'	=> ['mimetype' => '/image\/svg\+xml/', 'class' => '\OC\Preview\SVG'],
364
-				'TIFF'	=> ['mimetype' => '/image\/tiff/', 'class' => '\OC\Preview\TIFF'],
365
-				'PDF'	=> ['mimetype' => '/application\/pdf/', 'class' => '\OC\Preview\PDF'],
366
-				'AI'	=> ['mimetype' => '/application\/illustrator/', 'class' => '\OC\Preview\Illustrator'],
367
-				'PSD'	=> ['mimetype' => '/application\/x-photoshop/', 'class' => '\OC\Preview\Photoshop'],
368
-				'EPS'	=> ['mimetype' => '/application\/postscript/', 'class' => '\OC\Preview\Postscript'],
369
-				'TTF'	=> ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => '\OC\Preview\Font'],
370
-			];
371
-
372
-			foreach ($imagickProviders as $queryFormat => $provider) {
373
-				$class = $provider['class'];
374
-				if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
375
-					continue;
376
-				}
377
-
378
-				if (count($checkImagick->queryFormats($queryFormat)) === 1) {
379
-					$this->registerCoreProvider($class, $provider['mimetype']);
380
-				}
381
-			}
382
-
383
-			if (count($checkImagick->queryFormats('PDF')) === 1) {
384
-				if (\OC_Helper::is_function_enabled('shell_exec')) {
385
-					$officeFound = is_string($this->config->getSystemValue('preview_libreoffice_path', null));
386
-
387
-					if (!$officeFound) {
388
-						//let's see if there is libreoffice or openoffice on this machine
389
-						$whichLibreOffice = shell_exec('command -v libreoffice');
390
-						$officeFound = !empty($whichLibreOffice);
391
-						if (!$officeFound) {
392
-							$whichOpenOffice = shell_exec('command -v openoffice');
393
-							$officeFound = !empty($whichOpenOffice);
394
-						}
395
-					}
396
-
397
-					if ($officeFound) {
398
-						$this->registerCoreProvider('\OC\Preview\MSOfficeDoc', '/application\/msword/');
399
-						$this->registerCoreProvider('\OC\Preview\MSOffice2003', '/application\/vnd.ms-.*/');
400
-						$this->registerCoreProvider('\OC\Preview\MSOffice2007', '/application\/vnd.openxmlformats-officedocument.*/');
401
-						$this->registerCoreProvider('\OC\Preview\OpenDocument', '/application\/vnd.oasis.opendocument.*/');
402
-						$this->registerCoreProvider('\OC\Preview\StarOffice', '/application\/vnd.sun.xml.*/');
403
-					}
404
-				}
405
-			}
406
-		}
407
-
408
-		// Video requires avconv or ffmpeg
409
-		if (in_array('OC\Preview\Movie', $this->getEnabledDefaultProvider())) {
410
-			$avconvBinary = \OC_Helper::findBinaryPath('avconv');
411
-			$ffmpegBinary = ($avconvBinary) ? null : \OC_Helper::findBinaryPath('ffmpeg');
412
-
413
-			if ($avconvBinary || $ffmpegBinary) {
414
-				// FIXME // a bit hacky but didn't want to use subclasses
415
-				\OC\Preview\Movie::$avconvBinary = $avconvBinary;
416
-				\OC\Preview\Movie::$ffmpegBinary = $ffmpegBinary;
417
-
418
-				$this->registerCoreProvider('\OC\Preview\Movie', '/video\/.*/');
419
-			}
420
-		}
421
-	}
41
+    /** @var IConfig */
42
+    protected $config;
43
+
44
+    /** @var IRootFolder */
45
+    protected $rootFolder;
46
+
47
+    /** @var IAppData */
48
+    protected $appData;
49
+
50
+    /** @var EventDispatcherInterface */
51
+    protected $eventDispatcher;
52
+
53
+    /** @var Generator */
54
+    private $generator;
55
+
56
+    /** @var bool */
57
+    protected $providerListDirty = false;
58
+
59
+    /** @var bool */
60
+    protected $registeredCoreProviders = false;
61
+
62
+    /** @var array */
63
+    protected $providers = [];
64
+
65
+    /** @var array mime type => support status */
66
+    protected $mimeTypeSupportMap = [];
67
+
68
+    /** @var array */
69
+    protected $defaultProviders;
70
+
71
+    /** @var string */
72
+    protected $userId;
73
+
74
+    /**
75
+     * PreviewManager constructor.
76
+     *
77
+     * @param IConfig $config
78
+     * @param IRootFolder $rootFolder
79
+     * @param IAppData $appData
80
+     * @param EventDispatcherInterface $eventDispatcher
81
+     * @param string $userId
82
+     */
83
+    public function __construct(IConfig $config,
84
+                                IRootFolder $rootFolder,
85
+                                IAppData $appData,
86
+                                EventDispatcherInterface $eventDispatcher,
87
+                                $userId) {
88
+        $this->config = $config;
89
+        $this->rootFolder = $rootFolder;
90
+        $this->appData = $appData;
91
+        $this->eventDispatcher = $eventDispatcher;
92
+        $this->userId = $userId;
93
+    }
94
+
95
+    /**
96
+     * In order to improve lazy loading a closure can be registered which will be
97
+     * called in case preview providers are actually requested
98
+     *
99
+     * $callable has to return an instance of \OCP\Preview\IProvider
100
+     *
101
+     * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
102
+     * @param \Closure $callable
103
+     * @return void
104
+     */
105
+    public function registerProvider($mimeTypeRegex, \Closure $callable) {
106
+        if (!$this->config->getSystemValue('enable_previews', true)) {
107
+            return;
108
+        }
109
+
110
+        if (!isset($this->providers[$mimeTypeRegex])) {
111
+            $this->providers[$mimeTypeRegex] = [];
112
+        }
113
+        $this->providers[$mimeTypeRegex][] = $callable;
114
+        $this->providerListDirty = true;
115
+    }
116
+
117
+    /**
118
+     * Get all providers
119
+     * @return array
120
+     */
121
+    public function getProviders() {
122
+        if (!$this->config->getSystemValue('enable_previews', true)) {
123
+            return [];
124
+        }
125
+
126
+        $this->registerCoreProviders();
127
+        if ($this->providerListDirty) {
128
+            $keys = array_map('strlen', array_keys($this->providers));
129
+            array_multisort($keys, SORT_DESC, $this->providers);
130
+            $this->providerListDirty = false;
131
+        }
132
+
133
+        return $this->providers;
134
+    }
135
+
136
+    /**
137
+     * Does the manager have any providers
138
+     * @return bool
139
+     */
140
+    public function hasProviders() {
141
+        $this->registerCoreProviders();
142
+        return !empty($this->providers);
143
+    }
144
+
145
+    /**
146
+     * return a preview of a file
147
+     *
148
+     * @param string $file The path to the file where you want a thumbnail from
149
+     * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image
150
+     * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image
151
+     * @param boolean $scaleUp Scale smaller images up to the thumbnail size or not. Might look ugly
152
+     * @return \OCP\IImage
153
+     * @deprecated 11 Use getPreview
154
+     */
155
+    public function createPreview($file, $maxX = 100, $maxY = 75, $scaleUp = false) {
156
+        try {
157
+            $userRoot = $this->rootFolder->getUserFolder($this->userId)->getParent();
158
+            $node = $userRoot->get($file);
159
+            if (!($file instanceof File)) {
160
+                throw new NotFoundException();
161
+            }
162
+
163
+            $preview = $this->getPreview($node, $maxX, $maxY);
164
+        } catch (\Exception $e) {
165
+            return new \OC_Image();
166
+        }
167
+
168
+        return new \OC_Image($preview->getContent());
169
+    }
170
+
171
+    /**
172
+     * Returns a preview of a file
173
+     *
174
+     * The cache is searched first and if nothing usable was found then a preview is
175
+     * generated by one of the providers
176
+     *
177
+     * @param File $file
178
+     * @param int $width
179
+     * @param int $height
180
+     * @param bool $crop
181
+     * @param string $mode
182
+     * @param string $mimeType
183
+     * @return ISimpleFile
184
+     * @throws NotFoundException
185
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
186
+     * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
187
+     */
188
+    public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
189
+        if ($this->generator === null) {
190
+            $this->generator = new Generator(
191
+                $this->config,
192
+                $this,
193
+                $this->appData,
194
+                new GeneratorHelper(
195
+                    $this->rootFolder
196
+                ),
197
+                $this->eventDispatcher
198
+            );
199
+        }
200
+
201
+        return $this->generator->getPreview($file, $width, $height, $crop, $mode, $mimeType);
202
+    }
203
+
204
+    /**
205
+     * returns true if the passed mime type is supported
206
+     *
207
+     * @param string $mimeType
208
+     * @return boolean
209
+     */
210
+    public function isMimeSupported($mimeType = '*') {
211
+        if (!$this->config->getSystemValue('enable_previews', true)) {
212
+            return false;
213
+        }
214
+
215
+        if (isset($this->mimeTypeSupportMap[$mimeType])) {
216
+            return $this->mimeTypeSupportMap[$mimeType];
217
+        }
218
+
219
+        $this->registerCoreProviders();
220
+        $providerMimeTypes = array_keys($this->providers);
221
+        foreach ($providerMimeTypes as $supportedMimeType) {
222
+            if (preg_match($supportedMimeType, $mimeType)) {
223
+                $this->mimeTypeSupportMap[$mimeType] = true;
224
+                return true;
225
+            }
226
+        }
227
+        $this->mimeTypeSupportMap[$mimeType] = false;
228
+        return false;
229
+    }
230
+
231
+    /**
232
+     * Check if a preview can be generated for a file
233
+     *
234
+     * @param \OCP\Files\FileInfo $file
235
+     * @return bool
236
+     */
237
+    public function isAvailable(\OCP\Files\FileInfo $file) {
238
+        if (!$this->config->getSystemValue('enable_previews', true)) {
239
+            return false;
240
+        }
241
+
242
+        $this->registerCoreProviders();
243
+        if (!$this->isMimeSupported($file->getMimetype())) {
244
+            return false;
245
+        }
246
+
247
+        $mount = $file->getMountPoint();
248
+        if ($mount and !$mount->getOption('previews', true)){
249
+            return false;
250
+        }
251
+
252
+        foreach ($this->providers as $supportedMimeType => $providers) {
253
+            if (preg_match($supportedMimeType, $file->getMimetype())) {
254
+                foreach ($providers as $closure) {
255
+                    $provider = $closure();
256
+                    if (!($provider instanceof IProvider)) {
257
+                        continue;
258
+                    }
259
+
260
+                    /** @var $provider IProvider */
261
+                    if ($provider->isAvailable($file)) {
262
+                        return true;
263
+                    }
264
+                }
265
+            }
266
+        }
267
+        return false;
268
+    }
269
+
270
+    /**
271
+     * List of enabled default providers
272
+     *
273
+     * The following providers are enabled by default:
274
+     *  - OC\Preview\PNG
275
+     *  - OC\Preview\JPEG
276
+     *  - OC\Preview\GIF
277
+     *  - OC\Preview\BMP
278
+     *  - OC\Preview\XBitmap
279
+     *  - OC\Preview\MarkDown
280
+     *  - OC\Preview\MP3
281
+     *  - OC\Preview\TXT
282
+     *
283
+     * The following providers are disabled by default due to performance or privacy concerns:
284
+     *  - OC\Preview\Font
285
+     *  - OC\Preview\Illustrator
286
+     *  - OC\Preview\Movie
287
+     *  - OC\Preview\MSOfficeDoc
288
+     *  - OC\Preview\MSOffice2003
289
+     *  - OC\Preview\MSOffice2007
290
+     *  - OC\Preview\OpenDocument
291
+     *  - OC\Preview\PDF
292
+     *  - OC\Preview\Photoshop
293
+     *  - OC\Preview\Postscript
294
+     *  - OC\Preview\StarOffice
295
+     *  - OC\Preview\SVG
296
+     *  - OC\Preview\TIFF
297
+     *
298
+     * @return array
299
+     */
300
+    protected function getEnabledDefaultProvider() {
301
+        if ($this->defaultProviders !== null) {
302
+            return $this->defaultProviders;
303
+        }
304
+
305
+        $imageProviders = [
306
+            'OC\Preview\PNG',
307
+            'OC\Preview\JPEG',
308
+            'OC\Preview\GIF',
309
+            'OC\Preview\BMP',
310
+            'OC\Preview\XBitmap'
311
+        ];
312
+
313
+        $this->defaultProviders = $this->config->getSystemValue('enabledPreviewProviders', array_merge([
314
+            'OC\Preview\MarkDown',
315
+            'OC\Preview\MP3',
316
+            'OC\Preview\TXT',
317
+        ], $imageProviders));
318
+
319
+        if (in_array('OC\Preview\Image', $this->defaultProviders)) {
320
+            $this->defaultProviders = array_merge($this->defaultProviders, $imageProviders);
321
+        }
322
+        $this->defaultProviders = array_unique($this->defaultProviders);
323
+        return $this->defaultProviders;
324
+    }
325
+
326
+    /**
327
+     * Register the default providers (if enabled)
328
+     *
329
+     * @param string $class
330
+     * @param string $mimeType
331
+     */
332
+    protected function registerCoreProvider($class, $mimeType, $options = []) {
333
+        if (in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
334
+            $this->registerProvider($mimeType, function () use ($class, $options) {
335
+                return new $class($options);
336
+            });
337
+        }
338
+    }
339
+
340
+    /**
341
+     * Register the default providers (if enabled)
342
+     */
343
+    protected function registerCoreProviders() {
344
+        if ($this->registeredCoreProviders) {
345
+            return;
346
+        }
347
+        $this->registeredCoreProviders = true;
348
+
349
+        $this->registerCoreProvider('OC\Preview\TXT', '/text\/plain/');
350
+        $this->registerCoreProvider('OC\Preview\MarkDown', '/text\/(x-)?markdown/');
351
+        $this->registerCoreProvider('OC\Preview\PNG', '/image\/png/');
352
+        $this->registerCoreProvider('OC\Preview\JPEG', '/image\/jpeg/');
353
+        $this->registerCoreProvider('OC\Preview\GIF', '/image\/gif/');
354
+        $this->registerCoreProvider('OC\Preview\BMP', '/image\/bmp/');
355
+        $this->registerCoreProvider('OC\Preview\XBitmap', '/image\/x-xbitmap/');
356
+        $this->registerCoreProvider('OC\Preview\MP3', '/audio\/mpeg/');
357
+
358
+        // SVG, Office and Bitmap require imagick
359
+        if (extension_loaded('imagick')) {
360
+            $checkImagick = new \Imagick();
361
+
362
+            $imagickProviders = [
363
+                'SVG'	=> ['mimetype' => '/image\/svg\+xml/', 'class' => '\OC\Preview\SVG'],
364
+                'TIFF'	=> ['mimetype' => '/image\/tiff/', 'class' => '\OC\Preview\TIFF'],
365
+                'PDF'	=> ['mimetype' => '/application\/pdf/', 'class' => '\OC\Preview\PDF'],
366
+                'AI'	=> ['mimetype' => '/application\/illustrator/', 'class' => '\OC\Preview\Illustrator'],
367
+                'PSD'	=> ['mimetype' => '/application\/x-photoshop/', 'class' => '\OC\Preview\Photoshop'],
368
+                'EPS'	=> ['mimetype' => '/application\/postscript/', 'class' => '\OC\Preview\Postscript'],
369
+                'TTF'	=> ['mimetype' => '/application\/(?:font-sfnt|x-font$)/', 'class' => '\OC\Preview\Font'],
370
+            ];
371
+
372
+            foreach ($imagickProviders as $queryFormat => $provider) {
373
+                $class = $provider['class'];
374
+                if (!in_array(trim($class, '\\'), $this->getEnabledDefaultProvider())) {
375
+                    continue;
376
+                }
377
+
378
+                if (count($checkImagick->queryFormats($queryFormat)) === 1) {
379
+                    $this->registerCoreProvider($class, $provider['mimetype']);
380
+                }
381
+            }
382
+
383
+            if (count($checkImagick->queryFormats('PDF')) === 1) {
384
+                if (\OC_Helper::is_function_enabled('shell_exec')) {
385
+                    $officeFound = is_string($this->config->getSystemValue('preview_libreoffice_path', null));
386
+
387
+                    if (!$officeFound) {
388
+                        //let's see if there is libreoffice or openoffice on this machine
389
+                        $whichLibreOffice = shell_exec('command -v libreoffice');
390
+                        $officeFound = !empty($whichLibreOffice);
391
+                        if (!$officeFound) {
392
+                            $whichOpenOffice = shell_exec('command -v openoffice');
393
+                            $officeFound = !empty($whichOpenOffice);
394
+                        }
395
+                    }
396
+
397
+                    if ($officeFound) {
398
+                        $this->registerCoreProvider('\OC\Preview\MSOfficeDoc', '/application\/msword/');
399
+                        $this->registerCoreProvider('\OC\Preview\MSOffice2003', '/application\/vnd.ms-.*/');
400
+                        $this->registerCoreProvider('\OC\Preview\MSOffice2007', '/application\/vnd.openxmlformats-officedocument.*/');
401
+                        $this->registerCoreProvider('\OC\Preview\OpenDocument', '/application\/vnd.oasis.opendocument.*/');
402
+                        $this->registerCoreProvider('\OC\Preview\StarOffice', '/application\/vnd.sun.xml.*/');
403
+                    }
404
+                }
405
+            }
406
+        }
407
+
408
+        // Video requires avconv or ffmpeg
409
+        if (in_array('OC\Preview\Movie', $this->getEnabledDefaultProvider())) {
410
+            $avconvBinary = \OC_Helper::findBinaryPath('avconv');
411
+            $ffmpegBinary = ($avconvBinary) ? null : \OC_Helper::findBinaryPath('ffmpeg');
412
+
413
+            if ($avconvBinary || $ffmpegBinary) {
414
+                // FIXME // a bit hacky but didn't want to use subclasses
415
+                \OC\Preview\Movie::$avconvBinary = $avconvBinary;
416
+                \OC\Preview\Movie::$ffmpegBinary = $ffmpegBinary;
417
+
418
+                $this->registerCoreProvider('\OC\Preview\Movie', '/video\/.*/');
419
+            }
420
+        }
421
+    }
422 422
 }
Please login to merge, or discard this patch.
lib/private/Preview/Generator.php 1 patch
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -38,338 +38,338 @@
 block discarded – undo
38 38
 
39 39
 class Generator {
40 40
 
41
-	/** @var IPreview */
42
-	private $previewManager;
43
-	/** @var IConfig */
44
-	private $config;
45
-	/** @var IAppData */
46
-	private $appData;
47
-	/** @var GeneratorHelper */
48
-	private $helper;
49
-	/** @var EventDispatcherInterface */
50
-	private $eventDispatcher;
51
-
52
-	/**
53
-	 * @param IConfig $config
54
-	 * @param IPreview $previewManager
55
-	 * @param IAppData $appData
56
-	 * @param GeneratorHelper $helper
57
-	 * @param EventDispatcherInterface $eventDispatcher
58
-	 */
59
-	public function __construct(
60
-		IConfig $config,
61
-		IPreview $previewManager,
62
-		IAppData $appData,
63
-		GeneratorHelper $helper,
64
-		EventDispatcherInterface $eventDispatcher
65
-	) {
66
-		$this->config = $config;
67
-		$this->previewManager = $previewManager;
68
-		$this->appData = $appData;
69
-		$this->helper = $helper;
70
-		$this->eventDispatcher = $eventDispatcher;
71
-	}
72
-
73
-	/**
74
-	 * Returns a preview of a file
75
-	 *
76
-	 * The cache is searched first and if nothing usable was found then a preview is
77
-	 * generated by one of the providers
78
-	 *
79
-	 * @param File $file
80
-	 * @param int $width
81
-	 * @param int $height
82
-	 * @param bool $crop
83
-	 * @param string $mode
84
-	 * @param string $mimeType
85
-	 * @return ISimpleFile
86
-	 * @throws NotFoundException
87
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
88
-	 */
89
-	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
90
-		$this->eventDispatcher->dispatch(
91
-			IPreview::EVENT,
92
-			new GenericEvent($file,[
93
-				'width' => $width,
94
-				'height' => $height,
95
-				'crop' => $crop,
96
-				'mode' => $mode
97
-			])
98
-		);
99
-
100
-		if ($mimeType === null) {
101
-			$mimeType = $file->getMimeType();
102
-		}
103
-		if (!$this->previewManager->isMimeSupported($mimeType)) {
104
-			throw new NotFoundException();
105
-		}
106
-
107
-		$previewFolder = $this->getPreviewFolder($file);
108
-
109
-		// Get the max preview and infer the max preview sizes from that
110
-		$maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
111
-		list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
112
-
113
-		// Calculate the preview size
114
-		list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
115
-
116
-		// No need to generate a preview that is just the max preview
117
-		if ($width === $maxWidth && $height === $maxHeight) {
118
-			return $maxPreview;
119
-		}
120
-
121
-		// Try to get a cached preview. Else generate (and store) one
122
-		try {
123
-			$file = $this->getCachedPreview($previewFolder, $width, $height, $crop);
124
-		} catch (NotFoundException $e) {
125
-			$file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
126
-		}
127
-
128
-		return $file;
129
-	}
130
-
131
-	/**
132
-	 * @param ISimpleFolder $previewFolder
133
-	 * @param File $file
134
-	 * @param string $mimeType
135
-	 * @return ISimpleFile
136
-	 * @throws NotFoundException
137
-	 */
138
-	private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
139
-		$nodes = $previewFolder->getDirectoryListing();
140
-
141
-		foreach ($nodes as $node) {
142
-			if (strpos($node->getName(), 'max')) {
143
-				return $node;
144
-			}
145
-		}
146
-
147
-		$previewProviders = $this->previewManager->getProviders();
148
-		foreach ($previewProviders as $supportedMimeType => $providers) {
149
-			if (!preg_match($supportedMimeType, $mimeType)) {
150
-				continue;
151
-			}
152
-
153
-			foreach ($providers as $provider) {
154
-				$provider = $this->helper->getProvider($provider);
155
-				if (!($provider instanceof IProvider)) {
156
-					continue;
157
-				}
158
-
159
-				$maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048);
160
-				$maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048);
161
-
162
-				$preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
163
-
164
-				if (!($preview instanceof IImage)) {
165
-					continue;
166
-				}
167
-
168
-				$path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.png';
169
-				try {
170
-					$file = $previewFolder->newFile($path);
171
-					$file->putContent($preview->data());
172
-				} catch (NotPermittedException $e) {
173
-					throw new NotFoundException();
174
-				}
175
-
176
-				return $file;
177
-			}
178
-		}
179
-
180
-		throw new NotFoundException();
181
-	}
182
-
183
-	/**
184
-	 * @param ISimpleFile $file
185
-	 * @return int[]
186
-	 */
187
-	private function getPreviewSize(ISimpleFile $file) {
188
-		$size = explode('-', $file->getName());
189
-		return [(int)$size[0], (int)$size[1]];
190
-	}
191
-
192
-	/**
193
-	 * @param int $width
194
-	 * @param int $height
195
-	 * @param bool $crop
196
-	 * @return string
197
-	 */
198
-	private function generatePath($width, $height, $crop) {
199
-		$path = (string)$width . '-' . (string)$height;
200
-		if ($crop) {
201
-			$path .= '-crop';
202
-		}
203
-		$path .= '.png';
204
-		return $path;
205
-	}
206
-
207
-
208
-
209
-	/**
210
-	 * @param int $width
211
-	 * @param int $height
212
-	 * @param bool $crop
213
-	 * @param string $mode
214
-	 * @param int $maxWidth
215
-	 * @param int $maxHeight
216
-	 * @return int[]
217
-	 */
218
-	private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
219
-
220
-		/*
41
+    /** @var IPreview */
42
+    private $previewManager;
43
+    /** @var IConfig */
44
+    private $config;
45
+    /** @var IAppData */
46
+    private $appData;
47
+    /** @var GeneratorHelper */
48
+    private $helper;
49
+    /** @var EventDispatcherInterface */
50
+    private $eventDispatcher;
51
+
52
+    /**
53
+     * @param IConfig $config
54
+     * @param IPreview $previewManager
55
+     * @param IAppData $appData
56
+     * @param GeneratorHelper $helper
57
+     * @param EventDispatcherInterface $eventDispatcher
58
+     */
59
+    public function __construct(
60
+        IConfig $config,
61
+        IPreview $previewManager,
62
+        IAppData $appData,
63
+        GeneratorHelper $helper,
64
+        EventDispatcherInterface $eventDispatcher
65
+    ) {
66
+        $this->config = $config;
67
+        $this->previewManager = $previewManager;
68
+        $this->appData = $appData;
69
+        $this->helper = $helper;
70
+        $this->eventDispatcher = $eventDispatcher;
71
+    }
72
+
73
+    /**
74
+     * Returns a preview of a file
75
+     *
76
+     * The cache is searched first and if nothing usable was found then a preview is
77
+     * generated by one of the providers
78
+     *
79
+     * @param File $file
80
+     * @param int $width
81
+     * @param int $height
82
+     * @param bool $crop
83
+     * @param string $mode
84
+     * @param string $mimeType
85
+     * @return ISimpleFile
86
+     * @throws NotFoundException
87
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
88
+     */
89
+    public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
90
+        $this->eventDispatcher->dispatch(
91
+            IPreview::EVENT,
92
+            new GenericEvent($file,[
93
+                'width' => $width,
94
+                'height' => $height,
95
+                'crop' => $crop,
96
+                'mode' => $mode
97
+            ])
98
+        );
99
+
100
+        if ($mimeType === null) {
101
+            $mimeType = $file->getMimeType();
102
+        }
103
+        if (!$this->previewManager->isMimeSupported($mimeType)) {
104
+            throw new NotFoundException();
105
+        }
106
+
107
+        $previewFolder = $this->getPreviewFolder($file);
108
+
109
+        // Get the max preview and infer the max preview sizes from that
110
+        $maxPreview = $this->getMaxPreview($previewFolder, $file, $mimeType);
111
+        list($maxWidth, $maxHeight) = $this->getPreviewSize($maxPreview);
112
+
113
+        // Calculate the preview size
114
+        list($width, $height) = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
115
+
116
+        // No need to generate a preview that is just the max preview
117
+        if ($width === $maxWidth && $height === $maxHeight) {
118
+            return $maxPreview;
119
+        }
120
+
121
+        // Try to get a cached preview. Else generate (and store) one
122
+        try {
123
+            $file = $this->getCachedPreview($previewFolder, $width, $height, $crop);
124
+        } catch (NotFoundException $e) {
125
+            $file = $this->generatePreview($previewFolder, $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight);
126
+        }
127
+
128
+        return $file;
129
+    }
130
+
131
+    /**
132
+     * @param ISimpleFolder $previewFolder
133
+     * @param File $file
134
+     * @param string $mimeType
135
+     * @return ISimpleFile
136
+     * @throws NotFoundException
137
+     */
138
+    private function getMaxPreview(ISimpleFolder $previewFolder, File $file, $mimeType) {
139
+        $nodes = $previewFolder->getDirectoryListing();
140
+
141
+        foreach ($nodes as $node) {
142
+            if (strpos($node->getName(), 'max')) {
143
+                return $node;
144
+            }
145
+        }
146
+
147
+        $previewProviders = $this->previewManager->getProviders();
148
+        foreach ($previewProviders as $supportedMimeType => $providers) {
149
+            if (!preg_match($supportedMimeType, $mimeType)) {
150
+                continue;
151
+            }
152
+
153
+            foreach ($providers as $provider) {
154
+                $provider = $this->helper->getProvider($provider);
155
+                if (!($provider instanceof IProvider)) {
156
+                    continue;
157
+                }
158
+
159
+                $maxWidth = (int)$this->config->getSystemValue('preview_max_x', 2048);
160
+                $maxHeight = (int)$this->config->getSystemValue('preview_max_y', 2048);
161
+
162
+                $preview = $this->helper->getThumbnail($provider, $file, $maxWidth, $maxHeight);
163
+
164
+                if (!($preview instanceof IImage)) {
165
+                    continue;
166
+                }
167
+
168
+                $path = (string)$preview->width() . '-' . (string)$preview->height() . '-max.png';
169
+                try {
170
+                    $file = $previewFolder->newFile($path);
171
+                    $file->putContent($preview->data());
172
+                } catch (NotPermittedException $e) {
173
+                    throw new NotFoundException();
174
+                }
175
+
176
+                return $file;
177
+            }
178
+        }
179
+
180
+        throw new NotFoundException();
181
+    }
182
+
183
+    /**
184
+     * @param ISimpleFile $file
185
+     * @return int[]
186
+     */
187
+    private function getPreviewSize(ISimpleFile $file) {
188
+        $size = explode('-', $file->getName());
189
+        return [(int)$size[0], (int)$size[1]];
190
+    }
191
+
192
+    /**
193
+     * @param int $width
194
+     * @param int $height
195
+     * @param bool $crop
196
+     * @return string
197
+     */
198
+    private function generatePath($width, $height, $crop) {
199
+        $path = (string)$width . '-' . (string)$height;
200
+        if ($crop) {
201
+            $path .= '-crop';
202
+        }
203
+        $path .= '.png';
204
+        return $path;
205
+    }
206
+
207
+
208
+
209
+    /**
210
+     * @param int $width
211
+     * @param int $height
212
+     * @param bool $crop
213
+     * @param string $mode
214
+     * @param int $maxWidth
215
+     * @param int $maxHeight
216
+     * @return int[]
217
+     */
218
+    private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
219
+
220
+        /*
221 221
 		 * If we are not cropping we have to make sure the requested image
222 222
 		 * respects the aspect ratio of the original.
223 223
 		 */
224
-		if (!$crop) {
225
-			$ratio = $maxHeight / $maxWidth;
224
+        if (!$crop) {
225
+            $ratio = $maxHeight / $maxWidth;
226 226
 
227
-			if ($width === -1) {
228
-				$width = $height / $ratio;
229
-			}
230
-			if ($height === -1) {
231
-				$height = $width * $ratio;
232
-			}
227
+            if ($width === -1) {
228
+                $width = $height / $ratio;
229
+            }
230
+            if ($height === -1) {
231
+                $height = $width * $ratio;
232
+            }
233 233
 
234
-			$ratioH = $height / $maxHeight;
235
-			$ratioW = $width / $maxWidth;
234
+            $ratioH = $height / $maxHeight;
235
+            $ratioW = $width / $maxWidth;
236 236
 
237
-			/*
237
+            /*
238 238
 			 * Fill means that the $height and $width are the max
239 239
 			 * Cover means min.
240 240
 			 */
241
-			if ($mode === IPreview::MODE_FILL) {
242
-				if ($ratioH > $ratioW) {
243
-					$height = $width * $ratio;
244
-				} else {
245
-					$width = $height / $ratio;
246
-				}
247
-			} else if ($mode === IPreview::MODE_COVER) {
248
-				if ($ratioH > $ratioW) {
249
-					$width = $height / $ratio;
250
-				} else {
251
-					$height = $width * $ratio;
252
-				}
253
-			}
254
-		}
255
-
256
-		if ($height !== $maxHeight && $width !== $maxWidth) {
257
-			/*
241
+            if ($mode === IPreview::MODE_FILL) {
242
+                if ($ratioH > $ratioW) {
243
+                    $height = $width * $ratio;
244
+                } else {
245
+                    $width = $height / $ratio;
246
+                }
247
+            } else if ($mode === IPreview::MODE_COVER) {
248
+                if ($ratioH > $ratioW) {
249
+                    $width = $height / $ratio;
250
+                } else {
251
+                    $height = $width * $ratio;
252
+                }
253
+            }
254
+        }
255
+
256
+        if ($height !== $maxHeight && $width !== $maxWidth) {
257
+            /*
258 258
 			 * Scale to the nearest power of two
259 259
 			 */
260
-			$pow2height = 2 ** ceil(log($height) / log(2));
261
-			$pow2width = 2 ** ceil(log($width) / log(2));
262
-
263
-			$ratioH = $height / $pow2height;
264
-			$ratioW = $width / $pow2width;
265
-
266
-			if ($ratioH < $ratioW) {
267
-				$width = $pow2width;
268
-				$height /= $ratioW;
269
-			} else {
270
-				$height = $pow2height;
271
-				$width /= $ratioH;
272
-			}
273
-		}
274
-
275
-		/*
260
+            $pow2height = 2 ** ceil(log($height) / log(2));
261
+            $pow2width = 2 ** ceil(log($width) / log(2));
262
+
263
+            $ratioH = $height / $pow2height;
264
+            $ratioW = $width / $pow2width;
265
+
266
+            if ($ratioH < $ratioW) {
267
+                $width = $pow2width;
268
+                $height /= $ratioW;
269
+            } else {
270
+                $height = $pow2height;
271
+                $width /= $ratioH;
272
+            }
273
+        }
274
+
275
+        /*
276 276
  		 * Make sure the requested height and width fall within the max
277 277
  		 * of the preview.
278 278
  		 */
279
-		if ($height > $maxHeight) {
280
-			$ratio = $height / $maxHeight;
281
-			$height = $maxHeight;
282
-			$width /= $ratio;
283
-		}
284
-		if ($width > $maxWidth) {
285
-			$ratio = $width / $maxWidth;
286
-			$width = $maxWidth;
287
-			$height /= $ratio;
288
-		}
289
-
290
-		return [(int)round($width), (int)round($height)];
291
-	}
292
-
293
-	/**
294
-	 * @param ISimpleFolder $previewFolder
295
-	 * @param ISimpleFile $maxPreview
296
-	 * @param int $width
297
-	 * @param int $height
298
-	 * @param bool $crop
299
-	 * @param int $maxWidth
300
-	 * @param int $maxHeight
301
-	 * @return ISimpleFile
302
-	 * @throws NotFoundException
303
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
304
-	 */
305
-	private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
306
-		$preview = $this->helper->getImage($maxPreview);
307
-
308
-		if ($crop) {
309
-			if ($height !== $preview->height() && $width !== $preview->width()) {
310
-				//Resize
311
-				$widthR = $preview->width() / $width;
312
-				$heightR = $preview->height() / $height;
313
-
314
-				if ($widthR > $heightR) {
315
-					$scaleH = $height;
316
-					$scaleW = $maxWidth / $heightR;
317
-				} else {
318
-					$scaleH = $maxHeight / $widthR;
319
-					$scaleW = $width;
320
-				}
321
-				$preview->preciseResize(round($scaleW), round($scaleH));
322
-			}
323
-			$cropX = floor(abs($width - $preview->width()) * 0.5);
324
-			$cropY = 0;
325
-			$preview->crop($cropX, $cropY, $width, $height);
326
-		} else {
327
-			$preview->resize(max($width, $height));
328
-		}
329
-
330
-		if (!$preview->valid()) {
331
-			throw new \InvalidArgumentException('Failed to generate preview');
332
-		}
333
-
334
-		$path = $this->generatePath($width, $height, $crop);
335
-		try {
336
-			$file = $previewFolder->newFile($path);
337
-			$file->putContent($preview->data());
338
-		} catch (NotPermittedException $e) {
339
-			throw new NotFoundException();
340
-		}
341
-
342
-		return $file;
343
-	}
344
-
345
-	/**
346
-	 * @param ISimpleFolder $previewFolder
347
-	 * @param int $width
348
-	 * @param int $height
349
-	 * @param bool $crop
350
-	 * @return ISimpleFile
351
-	 *
352
-	 * @throws NotFoundException
353
-	 */
354
-	private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) {
355
-		$path = $this->generatePath($width, $height, $crop);
356
-
357
-		return $previewFolder->getFile($path);
358
-	}
359
-
360
-	/**
361
-	 * Get the specific preview folder for this file
362
-	 *
363
-	 * @param File $file
364
-	 * @return ISimpleFolder
365
-	 */
366
-	private function getPreviewFolder(File $file) {
367
-		try {
368
-			$folder = $this->appData->getFolder($file->getId());
369
-		} catch (NotFoundException $e) {
370
-			$folder = $this->appData->newFolder($file->getId());
371
-		}
372
-
373
-		return $folder;
374
-	}
279
+        if ($height > $maxHeight) {
280
+            $ratio = $height / $maxHeight;
281
+            $height = $maxHeight;
282
+            $width /= $ratio;
283
+        }
284
+        if ($width > $maxWidth) {
285
+            $ratio = $width / $maxWidth;
286
+            $width = $maxWidth;
287
+            $height /= $ratio;
288
+        }
289
+
290
+        return [(int)round($width), (int)round($height)];
291
+    }
292
+
293
+    /**
294
+     * @param ISimpleFolder $previewFolder
295
+     * @param ISimpleFile $maxPreview
296
+     * @param int $width
297
+     * @param int $height
298
+     * @param bool $crop
299
+     * @param int $maxWidth
300
+     * @param int $maxHeight
301
+     * @return ISimpleFile
302
+     * @throws NotFoundException
303
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
304
+     */
305
+    private function generatePreview(ISimpleFolder $previewFolder, ISimpleFile $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight) {
306
+        $preview = $this->helper->getImage($maxPreview);
307
+
308
+        if ($crop) {
309
+            if ($height !== $preview->height() && $width !== $preview->width()) {
310
+                //Resize
311
+                $widthR = $preview->width() / $width;
312
+                $heightR = $preview->height() / $height;
313
+
314
+                if ($widthR > $heightR) {
315
+                    $scaleH = $height;
316
+                    $scaleW = $maxWidth / $heightR;
317
+                } else {
318
+                    $scaleH = $maxHeight / $widthR;
319
+                    $scaleW = $width;
320
+                }
321
+                $preview->preciseResize(round($scaleW), round($scaleH));
322
+            }
323
+            $cropX = floor(abs($width - $preview->width()) * 0.5);
324
+            $cropY = 0;
325
+            $preview->crop($cropX, $cropY, $width, $height);
326
+        } else {
327
+            $preview->resize(max($width, $height));
328
+        }
329
+
330
+        if (!$preview->valid()) {
331
+            throw new \InvalidArgumentException('Failed to generate preview');
332
+        }
333
+
334
+        $path = $this->generatePath($width, $height, $crop);
335
+        try {
336
+            $file = $previewFolder->newFile($path);
337
+            $file->putContent($preview->data());
338
+        } catch (NotPermittedException $e) {
339
+            throw new NotFoundException();
340
+        }
341
+
342
+        return $file;
343
+    }
344
+
345
+    /**
346
+     * @param ISimpleFolder $previewFolder
347
+     * @param int $width
348
+     * @param int $height
349
+     * @param bool $crop
350
+     * @return ISimpleFile
351
+     *
352
+     * @throws NotFoundException
353
+     */
354
+    private function getCachedPreview(ISimpleFolder $previewFolder, $width, $height, $crop) {
355
+        $path = $this->generatePath($width, $height, $crop);
356
+
357
+        return $previewFolder->getFile($path);
358
+    }
359
+
360
+    /**
361
+     * Get the specific preview folder for this file
362
+     *
363
+     * @param File $file
364
+     * @return ISimpleFolder
365
+     */
366
+    private function getPreviewFolder(File $file) {
367
+        try {
368
+            $folder = $this->appData->getFolder($file->getId());
369
+        } catch (NotFoundException $e) {
370
+            $folder = $this->appData->newFolder($file->getId());
371
+        }
372
+
373
+        return $folder;
374
+    }
375 375
 }
Please login to merge, or discard this patch.
lib/public/IPreview.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -43,86 +43,86 @@
 block discarded – undo
43 43
  */
44 44
 interface IPreview {
45 45
 
46
-	/**
47
-	 * @since 9.2.0
48
-	 */
49
-	const EVENT = self::class . ':' . 'PreviewRequested';
46
+    /**
47
+     * @since 9.2.0
48
+     */
49
+    const EVENT = self::class . ':' . 'PreviewRequested';
50 50
 
51
-	const MODE_FILL = 'fill';
52
-	const MODE_COVER = 'cover';
51
+    const MODE_FILL = 'fill';
52
+    const MODE_COVER = 'cover';
53 53
 
54
-	/**
55
-	 * In order to improve lazy loading a closure can be registered which will be
56
-	 * called in case preview providers are actually requested
57
-	 *
58
-	 * $callable has to return an instance of \OCP\Preview\IProvider
59
-	 *
60
-	 * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
61
-	 * @param \Closure $callable
62
-	 * @return void
63
-	 * @since 8.1.0
64
-	 */
65
-	public function registerProvider($mimeTypeRegex, \Closure $callable);
54
+    /**
55
+     * In order to improve lazy loading a closure can be registered which will be
56
+     * called in case preview providers are actually requested
57
+     *
58
+     * $callable has to return an instance of \OCP\Preview\IProvider
59
+     *
60
+     * @param string $mimeTypeRegex Regex with the mime types that are supported by this provider
61
+     * @param \Closure $callable
62
+     * @return void
63
+     * @since 8.1.0
64
+     */
65
+    public function registerProvider($mimeTypeRegex, \Closure $callable);
66 66
 
67
-	/**
68
-	 * Get all providers
69
-	 * @return array
70
-	 * @since 8.1.0
71
-	 */
72
-	public function getProviders();
67
+    /**
68
+     * Get all providers
69
+     * @return array
70
+     * @since 8.1.0
71
+     */
72
+    public function getProviders();
73 73
 
74
-	/**
75
-	 * Does the manager have any providers
76
-	 * @return bool
77
-	 * @since 8.1.0
78
-	 */
79
-	public function hasProviders();
74
+    /**
75
+     * Does the manager have any providers
76
+     * @return bool
77
+     * @since 8.1.0
78
+     */
79
+    public function hasProviders();
80 80
 
81
-	/**
82
-	 * Return a preview of a file
83
-	 * @param string $file The path to the file where you want a thumbnail from
84
-	 * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image
85
-	 * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image
86
-	 * @param boolean $scaleUp Scale smaller images up to the thumbnail size or not. Might look ugly
87
-	 * @return \OCP\IImage
88
-	 * @since 6.0.0
89
-	 * @deprecated 11 Use getPreview
90
-	 */
91
-	public function createPreview($file, $maxX = 100, $maxY = 75, $scaleUp = false);
81
+    /**
82
+     * Return a preview of a file
83
+     * @param string $file The path to the file where you want a thumbnail from
84
+     * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the shape of the image
85
+     * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the shape of the image
86
+     * @param boolean $scaleUp Scale smaller images up to the thumbnail size or not. Might look ugly
87
+     * @return \OCP\IImage
88
+     * @since 6.0.0
89
+     * @deprecated 11 Use getPreview
90
+     */
91
+    public function createPreview($file, $maxX = 100, $maxY = 75, $scaleUp = false);
92 92
 
93
-	/**
94
-	 * Returns a preview of a file
95
-	 *
96
-	 * The cache is searched first and if nothing usable was found then a preview is
97
-	 * generated by one of the providers
98
-	 *
99
-	 * @param File $file
100
-	 * @param int $width
101
-	 * @param int $height
102
-	 * @param bool $crop
103
-	 * @param string $mode
104
-	 * @param string $mimeType To force a given mimetype for the file (files_versions needs this)
105
-	 * @return ISimpleFile
106
-	 * @throws NotFoundException
107
-	 * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
108
-	 * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
109
-	 */
110
-	public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null);
93
+    /**
94
+     * Returns a preview of a file
95
+     *
96
+     * The cache is searched first and if nothing usable was found then a preview is
97
+     * generated by one of the providers
98
+     *
99
+     * @param File $file
100
+     * @param int $width
101
+     * @param int $height
102
+     * @param bool $crop
103
+     * @param string $mode
104
+     * @param string $mimeType To force a given mimetype for the file (files_versions needs this)
105
+     * @return ISimpleFile
106
+     * @throws NotFoundException
107
+     * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
108
+     * @since 11.0.0 - \InvalidArgumentException was added in 12.0.0
109
+     */
110
+    public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null);
111 111
 
112
-	/**
113
-	 * Returns true if the passed mime type is supported
114
-	 * @param string $mimeType
115
-	 * @return boolean
116
-	 * @since 6.0.0
117
-	 */
118
-	public function isMimeSupported($mimeType = '*');
112
+    /**
113
+     * Returns true if the passed mime type is supported
114
+     * @param string $mimeType
115
+     * @return boolean
116
+     * @since 6.0.0
117
+     */
118
+    public function isMimeSupported($mimeType = '*');
119 119
 
120
-	/**
121
-	 * Check if a preview can be generated for a file
122
-	 *
123
-	 * @param \OCP\Files\FileInfo $file
124
-	 * @return bool
125
-	 * @since 8.0.0
126
-	 */
127
-	public function isAvailable(\OCP\Files\FileInfo $file);
120
+    /**
121
+     * Check if a preview can be generated for a file
122
+     *
123
+     * @param \OCP\Files\FileInfo $file
124
+     * @return bool
125
+     * @since 8.0.0
126
+     */
127
+    public function isAvailable(\OCP\Files\FileInfo $file);
128 128
 }
Please login to merge, or discard this patch.
core/Controller/PreviewController.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -36,99 +36,99 @@
 block discarded – undo
36 36
 
37 37
 class PreviewController extends Controller {
38 38
 
39
-	/** @var string */
40
-	private $userId;
41
-
42
-	/** @var IRootFolder */
43
-	private $root;
44
-
45
-	/** @var IPreview */
46
-	private $preview;
47
-
48
-	/** @var ITimeFactory */
49
-	private $timeFactory;
50
-
51
-	/**
52
-	 * PreviewController constructor.
53
-	 *
54
-	 * @param string $appName
55
-	 * @param IRequest $request
56
-	 * @param IPreview $preview
57
-	 * @param IRootFolder $root
58
-	 * @param string $userId
59
-	 */
60
-	public function __construct($appName,
61
-								IRequest $request,
62
-								IPreview $preview,
63
-								IRootFolder $root,
64
-								$userId,
65
-								ITimeFactory $timeFactory
66
-	) {
67
-		parent::__construct($appName, $request);
68
-
69
-		$this->preview = $preview;
70
-		$this->root = $root;
71
-		$this->userId = $userId;
72
-		$this->timeFactory = $timeFactory;
73
-	}
74
-
75
-	/**
76
-	 * @NoAdminRequired
77
-	 * @NoCSRFRequired
78
-	 *
79
-	 * @param string $file
80
-	 * @param int $x
81
-	 * @param int $y
82
-	 * @param bool $a
83
-	 * @param bool $forceIcon
84
-	 * @param string $mode
85
-	 * @return DataResponse|Http\FileDisplayResponse
86
-	 */
87
-	public function getPreview(
88
-		$file = '',
89
-		$x = 32,
90
-		$y = 32,
91
-		$a = false,
92
-		$forceIcon = true,
93
-		$mode = 'fill') {
94
-
95
-		if ($file === '' || $x === 0 || $y === 0) {
96
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
97
-		}
98
-
99
-		try {
100
-			$userFolder = $this->root->getUserFolder($this->userId);
101
-			$file = $userFolder->get($file);
102
-		} catch (NotFoundException $e) {
103
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
104
-		}
105
-
106
-		if (!($file instanceof File) || (!$forceIcon && !$this->preview->isAvailable($file))) {
107
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
108
-		} else if (!$file->isReadable()) {
109
-			return new DataResponse([], Http::STATUS_FORBIDDEN);
110
-		}
111
-
112
-		try {
113
-			$f = $this->preview->getPreview($file, $x, $y, !$a, $mode);
114
-			$response = new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
115
-
116
-			// Let cache this!
117
-			$response->addHeader('Pragma', 'public');
118
-
119
-			// Cache previews for 24H
120
-			$response->cacheFor(3600 * 24);
121
-			$expires = new \DateTime();
122
-			$expires->setTimestamp($this->timeFactory->getTime());
123
-			$expires->add(new \DateInterval('P1D'));
124
-			$response->addHeader('Expires', $expires->format(\DateTime::RFC2822));
125
-
126
-			return $response;
127
-		} catch (NotFoundException $e) {
128
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
129
-		} catch (\InvalidArgumentException $e) {
130
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
131
-		}
132
-
133
-	}
39
+    /** @var string */
40
+    private $userId;
41
+
42
+    /** @var IRootFolder */
43
+    private $root;
44
+
45
+    /** @var IPreview */
46
+    private $preview;
47
+
48
+    /** @var ITimeFactory */
49
+    private $timeFactory;
50
+
51
+    /**
52
+     * PreviewController constructor.
53
+     *
54
+     * @param string $appName
55
+     * @param IRequest $request
56
+     * @param IPreview $preview
57
+     * @param IRootFolder $root
58
+     * @param string $userId
59
+     */
60
+    public function __construct($appName,
61
+                                IRequest $request,
62
+                                IPreview $preview,
63
+                                IRootFolder $root,
64
+                                $userId,
65
+                                ITimeFactory $timeFactory
66
+    ) {
67
+        parent::__construct($appName, $request);
68
+
69
+        $this->preview = $preview;
70
+        $this->root = $root;
71
+        $this->userId = $userId;
72
+        $this->timeFactory = $timeFactory;
73
+    }
74
+
75
+    /**
76
+     * @NoAdminRequired
77
+     * @NoCSRFRequired
78
+     *
79
+     * @param string $file
80
+     * @param int $x
81
+     * @param int $y
82
+     * @param bool $a
83
+     * @param bool $forceIcon
84
+     * @param string $mode
85
+     * @return DataResponse|Http\FileDisplayResponse
86
+     */
87
+    public function getPreview(
88
+        $file = '',
89
+        $x = 32,
90
+        $y = 32,
91
+        $a = false,
92
+        $forceIcon = true,
93
+        $mode = 'fill') {
94
+
95
+        if ($file === '' || $x === 0 || $y === 0) {
96
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
97
+        }
98
+
99
+        try {
100
+            $userFolder = $this->root->getUserFolder($this->userId);
101
+            $file = $userFolder->get($file);
102
+        } catch (NotFoundException $e) {
103
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
104
+        }
105
+
106
+        if (!($file instanceof File) || (!$forceIcon && !$this->preview->isAvailable($file))) {
107
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
108
+        } else if (!$file->isReadable()) {
109
+            return new DataResponse([], Http::STATUS_FORBIDDEN);
110
+        }
111
+
112
+        try {
113
+            $f = $this->preview->getPreview($file, $x, $y, !$a, $mode);
114
+            $response = new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
115
+
116
+            // Let cache this!
117
+            $response->addHeader('Pragma', 'public');
118
+
119
+            // Cache previews for 24H
120
+            $response->cacheFor(3600 * 24);
121
+            $expires = new \DateTime();
122
+            $expires->setTimestamp($this->timeFactory->getTime());
123
+            $expires->add(new \DateInterval('P1D'));
124
+            $response->addHeader('Expires', $expires->format(\DateTime::RFC2822));
125
+
126
+            return $response;
127
+        } catch (NotFoundException $e) {
128
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
129
+        } catch (\InvalidArgumentException $e) {
130
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
131
+        }
132
+
133
+    }
134 134
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/PublicPreviewController.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -36,69 +36,69 @@
 block discarded – undo
36 36
 
37 37
 class PublicPreviewController extends Controller {
38 38
 
39
-	/** @var ShareManager */
40
-	private $shareManager;
39
+    /** @var ShareManager */
40
+    private $shareManager;
41 41
 
42
-	/** @var IPreview */
43
-	private $previewManager;
42
+    /** @var IPreview */
43
+    private $previewManager;
44 44
 
45
-	public function __construct($appName,
46
-								IRequest $request,
47
-								ShareManager $shareManger,
48
-								IPreview $previewManager) {
49
-		parent::__construct($appName, $request);
45
+    public function __construct($appName,
46
+                                IRequest $request,
47
+                                ShareManager $shareManger,
48
+                                IPreview $previewManager) {
49
+        parent::__construct($appName, $request);
50 50
 
51
-		$this->shareManager = $shareManger;
52
-		$this->previewManager = $previewManager;
53
-	}
51
+        $this->shareManager = $shareManger;
52
+        $this->previewManager = $previewManager;
53
+    }
54 54
 
55
-	/**
56
-	 * @PublicPage
57
-	 * @NoCSRFRequired
58
-	 *
59
-	 * @param string $file
60
-	 * @param int $x
61
-	 * @param int $y
62
-	 * @param string $t
63
-	 * @param bool $a
64
-	 * @return DataResponse|FileDisplayResponse
65
-	 */
66
-	public function getPreview(
67
-		$file = '',
68
-		$x = 32,
69
-		$y = 32,
70
-		$t = '',
71
-		$a = false
72
-	) {
55
+    /**
56
+     * @PublicPage
57
+     * @NoCSRFRequired
58
+     *
59
+     * @param string $file
60
+     * @param int $x
61
+     * @param int $y
62
+     * @param string $t
63
+     * @param bool $a
64
+     * @return DataResponse|FileDisplayResponse
65
+     */
66
+    public function getPreview(
67
+        $file = '',
68
+        $x = 32,
69
+        $y = 32,
70
+        $t = '',
71
+        $a = false
72
+    ) {
73 73
 
74
-		if ($t === '' || $x === 0 || $y === 0) {
75
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
76
-		}
74
+        if ($t === '' || $x === 0 || $y === 0) {
75
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
76
+        }
77 77
 
78
-		try {
79
-			$share = $this->shareManager->getShareByToken($t);
80
-		} catch (ShareNotFound $e) {
81
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
82
-		}
78
+        try {
79
+            $share = $this->shareManager->getShareByToken($t);
80
+        } catch (ShareNotFound $e) {
81
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
82
+        }
83 83
 
84
-		if (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {
85
-			return new DataResponse([], Http::STATUS_FORBIDDEN);
86
-		}
84
+        if (($share->getPermissions() & Constants::PERMISSION_READ) === 0) {
85
+            return new DataResponse([], Http::STATUS_FORBIDDEN);
86
+        }
87 87
 
88
-		try {
89
-			$node = $share->getNode();
90
-			if ($node instanceof Folder) {
91
-				$file = $node->get($file);
92
-			} else {
93
-				$file = $node;
94
-			}
88
+        try {
89
+            $node = $share->getNode();
90
+            if ($node instanceof Folder) {
91
+                $file = $node->get($file);
92
+            } else {
93
+                $file = $node;
94
+            }
95 95
 
96
-			$f = $this->previewManager->getPreview($file, $x, $y, !$a);
97
-			return new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
98
-		} catch (NotFoundException $e) {
99
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
100
-		} catch (\InvalidArgumentException $e) {
101
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
102
-		}
103
-	}
96
+            $f = $this->previewManager->getPreview($file, $x, $y, !$a);
97
+            return new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
98
+        } catch (NotFoundException $e) {
99
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
100
+        } catch (\InvalidArgumentException $e) {
101
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
102
+        }
103
+    }
104 104
 }
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Controller/PreviewController.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -35,87 +35,87 @@
 block discarded – undo
35 35
 
36 36
 class PreviewController extends Controller {
37 37
 
38
-	/** @var IRootFolder */
39
-	private $rootFolder;
38
+    /** @var IRootFolder */
39
+    private $rootFolder;
40 40
 
41
-	/** @var string */
42
-	private $userId;
41
+    /** @var string */
42
+    private $userId;
43 43
 
44
-	/** @var IMimeTypeDetector */
45
-	private $mimeTypeDetector;
44
+    /** @var IMimeTypeDetector */
45
+    private $mimeTypeDetector;
46 46
 
47
-	/** @var IPreview */
48
-	private $previewManager;
47
+    /** @var IPreview */
48
+    private $previewManager;
49 49
 
50
-	/**
51
-	 * @param string $appName
52
-	 * @param IRequest $request
53
-	 * @param IRootFolder $rootFolder
54
-	 * @param $userId
55
-	 * @param IMimeTypeDetector $mimeTypeDetector
56
-	 * @param IPreview $previewManager
57
-	 */
58
-	public function __construct($appName,
59
-								IRequest $request,
60
-								IRootFolder $rootFolder,
61
-								$userId,
62
-								IMimeTypeDetector $mimeTypeDetector,
63
-								IPreview $previewManager) {
64
-		parent::__construct($appName, $request);
50
+    /**
51
+     * @param string $appName
52
+     * @param IRequest $request
53
+     * @param IRootFolder $rootFolder
54
+     * @param $userId
55
+     * @param IMimeTypeDetector $mimeTypeDetector
56
+     * @param IPreview $previewManager
57
+     */
58
+    public function __construct($appName,
59
+                                IRequest $request,
60
+                                IRootFolder $rootFolder,
61
+                                $userId,
62
+                                IMimeTypeDetector $mimeTypeDetector,
63
+                                IPreview $previewManager) {
64
+        parent::__construct($appName, $request);
65 65
 
66
-		$this->rootFolder = $rootFolder;
67
-		$this->userId = $userId;
68
-		$this->mimeTypeDetector = $mimeTypeDetector;
69
-		$this->previewManager = $previewManager;
70
-	}
66
+        $this->rootFolder = $rootFolder;
67
+        $this->userId = $userId;
68
+        $this->mimeTypeDetector = $mimeTypeDetector;
69
+        $this->previewManager = $previewManager;
70
+    }
71 71
 
72
-	/**
73
-	 * @NoAdminRequired
74
-	 * @NoCSRFRequired
75
-	 *
76
-	 * @param string $file
77
-	 * @param int $x
78
-	 * @param int $y
79
-	 * @return DataResponse|Http\FileDisplayResponse
80
-	 */
81
-	public function getPreview(
82
-		$file = '',
83
-		$x = 44,
84
-		$y = 44
85
-	) {
86
-		if ($file === '') {
87
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
88
-		}
72
+    /**
73
+     * @NoAdminRequired
74
+     * @NoCSRFRequired
75
+     *
76
+     * @param string $file
77
+     * @param int $x
78
+     * @param int $y
79
+     * @return DataResponse|Http\FileDisplayResponse
80
+     */
81
+    public function getPreview(
82
+        $file = '',
83
+        $x = 44,
84
+        $y = 44
85
+    ) {
86
+        if ($file === '') {
87
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
88
+        }
89 89
 
90
-		if ($x === 0 || $y === 0) {
91
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
92
-		}
90
+        if ($x === 0 || $y === 0) {
91
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
92
+        }
93 93
 
94
-		try {
95
-			$userFolder = $this->rootFolder->getUserFolder($this->userId);
96
-			/** @var Folder $trash */
97
-			$trash = $userFolder->getParent()->get('files_trashbin/files');
98
-			$trashFile = $trash->get($file);
94
+        try {
95
+            $userFolder = $this->rootFolder->getUserFolder($this->userId);
96
+            /** @var Folder $trash */
97
+            $trash = $userFolder->getParent()->get('files_trashbin/files');
98
+            $trashFile = $trash->get($file);
99 99
 
100
-			if ($trashFile instanceof Folder) {
101
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
102
-			}
100
+            if ($trashFile instanceof Folder) {
101
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
102
+            }
103 103
 
104
-			/** @var File $trashFile */
105
-			$fileName = $trashFile->getName();
106
-			$i = strrpos($fileName, '.');
107
-			if ($i !== false) {
108
-				$fileName = substr($fileName, 0, $i);
109
-			}
104
+            /** @var File $trashFile */
105
+            $fileName = $trashFile->getName();
106
+            $i = strrpos($fileName, '.');
107
+            if ($i !== false) {
108
+                $fileName = substr($fileName, 0, $i);
109
+            }
110 110
 
111
-			$mimeType = $this->mimeTypeDetector->detectPath($fileName);
111
+            $mimeType = $this->mimeTypeDetector->detectPath($fileName);
112 112
 
113
-			$f = $this->previewManager->getPreview($trashFile, $x, $y, true, IPreview::MODE_FILL, $mimeType);
114
-			return new Http\FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
115
-		} catch (NotFoundException $e) {
116
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
117
-		} catch (\InvalidArgumentException $e) {
118
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
119
-		}
120
-	}
113
+            $f = $this->previewManager->getPreview($trashFile, $x, $y, true, IPreview::MODE_FILL, $mimeType);
114
+            return new Http\FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
115
+        } catch (NotFoundException $e) {
116
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
117
+        } catch (\InvalidArgumentException $e) {
118
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
119
+        }
120
+    }
121 121
 }
Please login to merge, or discard this patch.
apps/files_versions/lib/Controller/PreviewController.php 1 patch
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -36,66 +36,66 @@
 block discarded – undo
36 36
 
37 37
 class PreviewController extends Controller {
38 38
 
39
-	/** @var IRootFolder */
40
-	private $rootFolder;
39
+    /** @var IRootFolder */
40
+    private $rootFolder;
41 41
 
42
-	/** @var string */
43
-	private $userId;
42
+    /** @var string */
43
+    private $userId;
44 44
 
45
-	/** @var IMimeTypeDetector */
46
-	private $mimeTypeDetector;
45
+    /** @var IMimeTypeDetector */
46
+    private $mimeTypeDetector;
47 47
 
48
-	/** @var IPreview */
49
-	private $previewManager;
48
+    /** @var IPreview */
49
+    private $previewManager;
50 50
 
51
-	public function __construct($appName,
52
-								IRequest $request,
53
-								IRootFolder $rootFolder,
54
-								$userId,
55
-								IMimeTypeDetector $mimeTypeDetector,
56
-								IPreview $previewManager) {
57
-		parent::__construct($appName, $request);
51
+    public function __construct($appName,
52
+                                IRequest $request,
53
+                                IRootFolder $rootFolder,
54
+                                $userId,
55
+                                IMimeTypeDetector $mimeTypeDetector,
56
+                                IPreview $previewManager) {
57
+        parent::__construct($appName, $request);
58 58
 
59
-		$this->rootFolder = $rootFolder;
60
-		$this->userId = $userId;
61
-		$this->mimeTypeDetector = $mimeTypeDetector;
62
-		$this->previewManager = $previewManager;
63
-	}
59
+        $this->rootFolder = $rootFolder;
60
+        $this->userId = $userId;
61
+        $this->mimeTypeDetector = $mimeTypeDetector;
62
+        $this->previewManager = $previewManager;
63
+    }
64 64
 
65
-	/**
66
-	 * @NoAdminRequired
67
-	 * @NoCSRFRequired
68
-	 *
69
-	 * @param string $file
70
-	 * @param int $x
71
-	 * @param int $y
72
-	 * @param string $version
73
-	 * @return DataResponse|FileDisplayResponse
74
-	 */
75
-	public function getPreview(
76
-		$file = '',
77
-		$x = 44,
78
-		$y = 44,
79
-		$version = ''
80
-	) {
81
-		if($file === '' || $version === '' || $x === 0 || $y === 0) {
82
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
83
-		}
65
+    /**
66
+     * @NoAdminRequired
67
+     * @NoCSRFRequired
68
+     *
69
+     * @param string $file
70
+     * @param int $x
71
+     * @param int $y
72
+     * @param string $version
73
+     * @return DataResponse|FileDisplayResponse
74
+     */
75
+    public function getPreview(
76
+        $file = '',
77
+        $x = 44,
78
+        $y = 44,
79
+        $version = ''
80
+    ) {
81
+        if($file === '' || $version === '' || $x === 0 || $y === 0) {
82
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
83
+        }
84 84
 
85
-		try {
86
-			$userFolder = $this->rootFolder->getUserFolder($this->userId);
87
-			/** @var Folder $versionFolder */
88
-			$versionFolder = $userFolder->getParent()->get('files_versions');
89
-			$mimeType = $this->mimeTypeDetector->detectPath($file);
90
-			$file = $versionFolder->get($file.'.v'.$version);
85
+        try {
86
+            $userFolder = $this->rootFolder->getUserFolder($this->userId);
87
+            /** @var Folder $versionFolder */
88
+            $versionFolder = $userFolder->getParent()->get('files_versions');
89
+            $mimeType = $this->mimeTypeDetector->detectPath($file);
90
+            $file = $versionFolder->get($file.'.v'.$version);
91 91
 
92
-			/** @var File $file */
93
-			$f = $this->previewManager->getPreview($file, $x, $y, true, IPreview::MODE_FILL, $mimeType);
94
-			return new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
95
-		} catch (NotFoundException $e) {
96
-			return new DataResponse([], Http::STATUS_NOT_FOUND);
97
-		} catch (\InvalidArgumentException $e) {
98
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
99
-		}
100
-	}
92
+            /** @var File $file */
93
+            $f = $this->previewManager->getPreview($file, $x, $y, true, IPreview::MODE_FILL, $mimeType);
94
+            return new FileDisplayResponse($f, Http::STATUS_OK, ['Content-Type' => $f->getMimeType()]);
95
+        } catch (NotFoundException $e) {
96
+            return new DataResponse([], Http::STATUS_NOT_FOUND);
97
+        } catch (\InvalidArgumentException $e) {
98
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
99
+        }
100
+    }
101 101
 }
Please login to merge, or discard this patch.