Test Failed
Push — master ( 398493...d4ef72 )
by Michael
11:04
created
htdocs/modules/system/class/thumbs/phpthumb.filters.php 2 patches
Indentation   +1506 added lines, -1506 removed lines patch added patch discarded remove patch
@@ -11,68 +11,68 @@  discard block
 block discarded – undo
11 11
 
12 12
 class phpthumb_filters {
13 13
 
14
-	/**
15
-	* @var phpthumb
16
-	*/
17
-
18
-	public $phpThumbObject = null;
19
-
20
-
21
-	public function DebugMessage($message, $file='', $line='') {
22
-		if (is_object($this->phpThumbObject)) {
23
-			return $this->phpThumbObject->DebugMessage($message, $file, $line);
24
-		}
25
-		return false;
26
-	}
27
-
28
-
29
-	public function ApplyMask(&$gdimg_mask, &$gdimg_image) {
30
-		if (phpthumb_functions::gd_version() < 2) {
31
-			$this->DebugMessage('Skipping ApplyMask() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
32
-			return false;
33
-		}
34
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.2', '>=')) {
35
-
36
-			$this->DebugMessage('Using alpha ApplyMask() technique', __FILE__, __LINE__);
37
-			if ($gdimg_mask_resized = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_image), imagesy($gdimg_image))) {
38
-
39
-				imagecopyresampled($gdimg_mask_resized, $gdimg_mask, 0, 0, 0, 0, imagesx($gdimg_image), imagesy($gdimg_image), imagesx($gdimg_mask), imagesy($gdimg_mask));
40
-				if ($gdimg_mask_blendtemp = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_image), imagesy($gdimg_image))) {
41
-
42
-					$color_background = imagecolorallocate($gdimg_mask_blendtemp, 0, 0, 0);
43
-					imagefilledrectangle($gdimg_mask_blendtemp, 0, 0, imagesx($gdimg_mask_blendtemp), imagesy($gdimg_mask_blendtemp), $color_background);
44
-					imagealphablending($gdimg_mask_blendtemp, false);
45
-					imagesavealpha($gdimg_mask_blendtemp, true);
46
-					for ($x = 0, $xMax = imagesx($gdimg_image); $x < $xMax; $x++) {
47
-						for ($y = 0, $yMax = imagesy($gdimg_image); $y < $yMax; $y++) {
48
-							//$RealPixel = phpthumb_functions::GetPixelColor($gdimg_mask_blendtemp, $x, $y);
49
-							$RealPixel = phpthumb_functions::GetPixelColor($gdimg_image, $x, $y);
50
-							$MaskPixel = phpthumb_functions::GrayscalePixel(phpthumb_functions::GetPixelColor($gdimg_mask_resized, $x, $y));
51
-							$MaskAlpha = 127 - (floor($MaskPixel['red'] / 2) * (1 - ($RealPixel['alpha'] / 127)));
52
-							$newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_mask_blendtemp, $RealPixel['red'], $RealPixel['green'], $RealPixel['blue'], $MaskAlpha);
53
-							imagesetpixel($gdimg_mask_blendtemp, $x, $y, $newcolor);
54
-						}
55
-					}
56
-					imagealphablending($gdimg_image, false);
57
-					imagesavealpha($gdimg_image, true);
58
-					imagecopy($gdimg_image, $gdimg_mask_blendtemp, 0, 0, 0, 0, imagesx($gdimg_mask_blendtemp), imagesy($gdimg_mask_blendtemp));
59
-					imagedestroy($gdimg_mask_blendtemp);
60
-
61
-				} else {
62
-					$this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
63
-				}
64
-				imagedestroy($gdimg_mask_resized);
65
-
66
-			} else {
67
-				$this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
68
-			}
69
-
70
-		} else {
71
-			// alpha merging requires PHP v4.3.2+
72
-			$this->DebugMessage('Skipping ApplyMask() technique because PHP is v"'. PHP_VERSION .'"', __FILE__, __LINE__);
73
-		}
74
-		return true;
75
-	}
14
+    /**
15
+     * @var phpthumb
16
+     */
17
+
18
+    public $phpThumbObject = null;
19
+
20
+
21
+    public function DebugMessage($message, $file='', $line='') {
22
+        if (is_object($this->phpThumbObject)) {
23
+            return $this->phpThumbObject->DebugMessage($message, $file, $line);
24
+        }
25
+        return false;
26
+    }
27
+
28
+
29
+    public function ApplyMask(&$gdimg_mask, &$gdimg_image) {
30
+        if (phpthumb_functions::gd_version() < 2) {
31
+            $this->DebugMessage('Skipping ApplyMask() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
32
+            return false;
33
+        }
34
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.2', '>=')) {
35
+
36
+            $this->DebugMessage('Using alpha ApplyMask() technique', __FILE__, __LINE__);
37
+            if ($gdimg_mask_resized = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_image), imagesy($gdimg_image))) {
38
+
39
+                imagecopyresampled($gdimg_mask_resized, $gdimg_mask, 0, 0, 0, 0, imagesx($gdimg_image), imagesy($gdimg_image), imagesx($gdimg_mask), imagesy($gdimg_mask));
40
+                if ($gdimg_mask_blendtemp = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_image), imagesy($gdimg_image))) {
41
+
42
+                    $color_background = imagecolorallocate($gdimg_mask_blendtemp, 0, 0, 0);
43
+                    imagefilledrectangle($gdimg_mask_blendtemp, 0, 0, imagesx($gdimg_mask_blendtemp), imagesy($gdimg_mask_blendtemp), $color_background);
44
+                    imagealphablending($gdimg_mask_blendtemp, false);
45
+                    imagesavealpha($gdimg_mask_blendtemp, true);
46
+                    for ($x = 0, $xMax = imagesx($gdimg_image); $x < $xMax; $x++) {
47
+                        for ($y = 0, $yMax = imagesy($gdimg_image); $y < $yMax; $y++) {
48
+                            //$RealPixel = phpthumb_functions::GetPixelColor($gdimg_mask_blendtemp, $x, $y);
49
+                            $RealPixel = phpthumb_functions::GetPixelColor($gdimg_image, $x, $y);
50
+                            $MaskPixel = phpthumb_functions::GrayscalePixel(phpthumb_functions::GetPixelColor($gdimg_mask_resized, $x, $y));
51
+                            $MaskAlpha = 127 - (floor($MaskPixel['red'] / 2) * (1 - ($RealPixel['alpha'] / 127)));
52
+                            $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_mask_blendtemp, $RealPixel['red'], $RealPixel['green'], $RealPixel['blue'], $MaskAlpha);
53
+                            imagesetpixel($gdimg_mask_blendtemp, $x, $y, $newcolor);
54
+                        }
55
+                    }
56
+                    imagealphablending($gdimg_image, false);
57
+                    imagesavealpha($gdimg_image, true);
58
+                    imagecopy($gdimg_image, $gdimg_mask_blendtemp, 0, 0, 0, 0, imagesx($gdimg_mask_blendtemp), imagesy($gdimg_mask_blendtemp));
59
+                    imagedestroy($gdimg_mask_blendtemp);
60
+
61
+                } else {
62
+                    $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
63
+                }
64
+                imagedestroy($gdimg_mask_resized);
65
+
66
+            } else {
67
+                $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
68
+            }
69
+
70
+        } else {
71
+            // alpha merging requires PHP v4.3.2+
72
+            $this->DebugMessage('Skipping ApplyMask() technique because PHP is v"'. PHP_VERSION .'"', __FILE__, __LINE__);
73
+        }
74
+        return true;
75
+    }
76 76
 
77 77
 
78 78
     public function Bevel(&$gdimg, $width, $hexcolor1, $hexcolor2) {
@@ -95,1449 +95,1449 @@  discard block
 block discarded – undo
95 95
     }
96 96
 
97 97
 
98
-	public function Blur(&$gdimg, $radius=0.5) {
99
-		// Taken from Torstein Hønsi's phpUnsharpMask (see phpthumb.unsharp.php)
100
-
101
-		$radius = round(max(0, min($radius, 50)) * 2);
102
-		if (!$radius) {
103
-			return false;
104
-		}
105
-
106
-		$w = imagesx($gdimg);
107
-		$h = imagesy($gdimg);
108
-		if ($imgBlur = imagecreatetruecolor($w, $h)) {
109
-			// Gaussian blur matrix:
110
-			//	1	2	1
111
-			//	2	4	2
112
-			//	1	2	1
113
-
114
-			// Move copies of the image around one pixel at the time and merge them with weight
115
-			// according to the matrix. The same matrix is simply repeated for higher radii.
116
-			for ($i = 0; $i < $radius; $i++)	{
117
-				imagecopy     ($imgBlur, $gdimg, 0, 0, 1, 1, $w - 1, $h - 1);            // up left
118
-				imagecopymerge($imgBlur, $gdimg, 1, 1, 0, 0, $w,     $h,     50.00000);  // down right
119
-				imagecopymerge($imgBlur, $gdimg, 0, 1, 1, 0, $w - 1, $h,     33.33333);  // down left
120
-				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 1, $w,     $h - 1, 25.00000);  // up right
121
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 1, 0, $w - 1, $h,     33.33333);  // left
122
-				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 0, $w,     $h,     25.00000);  // right
123
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 1, $w,     $h - 1, 20.00000);  // up
124
-				imagecopymerge($imgBlur, $gdimg, 0, 1, 0, 0, $w,     $h,     16.666667); // down
125
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 0, $w,     $h,     50.000000); // center
126
-				imagecopy     ($gdimg, $imgBlur, 0, 0, 0, 0, $w,     $h);
127
-			}
128
-			return true;
129
-		}
130
-		return false;
131
-	}
132
-
133
-
134
-	public function BlurGaussian(&$gdimg) {
135
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
136
-			if (imagefilter($gdimg, IMG_FILTER_GAUSSIAN_BLUR)) {
137
-				return true;
138
-			}
139
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GAUSSIAN_BLUR)', __FILE__, __LINE__);
140
-			// fall through and try it the hard way
141
-		}
142
-		$this->DebugMessage('FAILED: phpthumb_filters::BlurGaussian($gdimg) [using phpthumb_filters::Blur() instead]', __FILE__, __LINE__);
143
-		return self::Blur($gdimg, 0.5);
144
-	}
145
-
146
-
147
-	public function BlurSelective(&$gdimg) {
148
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
149
-			if (imagefilter($gdimg, IMG_FILTER_SELECTIVE_BLUR)) {
150
-				return true;
151
-			}
152
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_SELECTIVE_BLUR)', __FILE__, __LINE__);
153
-			// fall through and try it the hard way
154
-		}
155
-		// currently not implemented "the hard way"
156
-		$this->DebugMessage('FAILED: phpthumb_filters::BlurSelective($gdimg) [function not implemented]', __FILE__, __LINE__);
157
-		return false;
158
-	}
159
-
160
-
161
-	public function Brightness(&$gdimg, $amount=0) {
162
-		if ($amount == 0) {
163
-			return true;
164
-		}
165
-		$amount = max(-255, min(255, $amount));
166
-
167
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
168
-			if (imagefilter($gdimg, IMG_FILTER_BRIGHTNESS, $amount)) {
169
-				return true;
170
-			}
171
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_BRIGHTNESS, '.$amount.')', __FILE__, __LINE__);
172
-			// fall through and try it the hard way
173
-		}
174
-
175
-		$scaling = (255 - abs($amount)) / 255;
176
-		$baseamount = (($amount > 0) ? $amount : 0);
177
-		for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
178
-			for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
179
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
180
-				$NewPixel = array();
181
-				foreach ($OriginalPixel as $key => $value) {
182
-					$NewPixel[$key] = round($baseamount + ($OriginalPixel[$key] * $scaling));
183
-				}
184
-				$newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
185
-				imagesetpixel($gdimg, $x, $y, $newColor);
186
-			}
187
-		}
188
-		return true;
189
-	}
190
-
191
-
192
-	public function Contrast(&$gdimg, $amount=0) {
193
-		if ($amount == 0) {
194
-			return true;
195
-		}
196
-		$amount = max(-255, min(255, $amount));
197
-
198
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
199
-			// imagefilter(IMG_FILTER_CONTRAST) has range +100 to -100 (positive numbers make it darker!)
200
-			$amount = ($amount / 255) * -100;
201
-			if (imagefilter($gdimg, IMG_FILTER_CONTRAST, $amount)) {
202
-				return true;
203
-			}
204
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_CONTRAST, '.$amount.')', __FILE__, __LINE__);
205
-			// fall through and try it the hard way
206
-		}
207
-
208
-		if ($amount > 0) {
209
-			$scaling = 1 + ($amount / 255);
210
-		} else {
211
-			$scaling = (255 - abs($amount)) / 255;
212
-		}
213
-		for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
214
-			for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
215
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
216
-				$NewPixel = array();
217
-				foreach ($OriginalPixel as $key => $value) {
218
-					$NewPixel[$key] = min(255, max(0, round($OriginalPixel[$key] * $scaling)));
219
-				}
220
-				$newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
221
-				imagesetpixel($gdimg, $x, $y, $newColor);
222
-			}
223
-		}
224
-		return true;
225
-	}
226
-
227
-
228
-	public function Colorize(&$gdimg, $amount, $targetColor) {
229
-		$amount      = (is_numeric($amount)                          ? $amount      : 25);
230
-		$amountPct   = $amount / 100;
231
-		$targetColor = (phpthumb_functions::IsHexColor($targetColor) ? $targetColor : 'gray');
232
-
233
-		if ($amount == 0) {
234
-			return true;
235
-		}
236
-
237
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
238
-			if ($targetColor == 'gray') {
239
-				$targetColor = '808080';
240
-			}
241
-			$r = round($amountPct * hexdec(substr($targetColor, 0, 2)));
242
-			$g = round($amountPct * hexdec(substr($targetColor, 2, 2)));
243
-			$b = round($amountPct * hexdec(substr($targetColor, 4, 2)));
244
-			if (imagefilter($gdimg, IMG_FILTER_COLORIZE, $r, $g, $b)) {
245
-				return true;
246
-			}
247
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_COLORIZE)', __FILE__, __LINE__);
248
-			// fall through and try it the hard way
249
-		}
250
-
251
-		// overridden below for grayscale
252
-		$TargetPixel = array();
253
-		if ($targetColor != 'gray') {
254
-			$TargetPixel['red']   = hexdec(substr($targetColor, 0, 2));
255
-			$TargetPixel['green'] = hexdec(substr($targetColor, 2, 2));
256
-			$TargetPixel['blue']  = hexdec(substr($targetColor, 4, 2));
257
-		}
258
-
259
-		for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
260
-			for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
261
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
262
-				if ($targetColor == 'gray') {
263
-					$TargetPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
264
-				}
265
-				$NewPixel = array();
266
-				foreach ($TargetPixel as $key => $value) {
267
-					$NewPixel[$key] = round(max(0, min(255, ($OriginalPixel[$key] * ((100 - $amount) / 100)) + ($TargetPixel[$key] * $amountPct))));
268
-				}
269
-				//$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue'], $OriginalPixel['alpha']);
270
-				$newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
271
-				imagesetpixel($gdimg, $x, $y, $newColor);
272
-			}
273
-		}
274
-		return true;
275
-	}
276
-
277
-
278
-	public function Crop(&$gdimg, $left=0, $right=0, $top=0, $bottom=0) {
279
-		if (!$left && !$right && !$top && !$bottom) {
280
-			return true;
281
-		}
282
-		$oldW = imagesx($gdimg);
283
-		$oldH = imagesy($gdimg);
284
-		if (($left   > 0) && ($left   < 1)) { $left   = round($left   * $oldW); }
285
-		if (($right  > 0) && ($right  < 1)) { $right  = round($right  * $oldW); }
286
-		if (($top    > 0) && ($top    < 1)) { $top    = round($top    * $oldH); }
287
-		if (($bottom > 0) && ($bottom < 1)) { $bottom = round($bottom * $oldH); }
288
-		$right  = min($oldW - $left - 1, $right);
289
-		$bottom = min($oldH - $top  - 1, $bottom);
290
-		$newW = $oldW - $left - $right;
291
-		$newH = $oldH - $top  - $bottom;
292
-
293
-		if ($imgCropped = imagecreatetruecolor($newW, $newH)) {
294
-			imagecopy($imgCropped, $gdimg, 0, 0, $left, $top, $newW, $newH);
295
-			if ($gdimg = imagecreatetruecolor($newW, $newH)) {
296
-				imagecopy($gdimg, $imgCropped, 0, 0, 0, 0, $newW, $newH);
297
-				imagedestroy($imgCropped);
298
-				return true;
299
-			}
300
-			imagedestroy($imgCropped);
301
-		}
302
-		return false;
303
-	}
304
-
305
-
306
-	public function Desaturate(&$gdimg, $amount, $color='') {
307
-		if ($amount == 0) {
308
-			return true;
309
-		}
310
-		return self::Colorize($gdimg, $amount, (phpthumb_functions::IsHexColor($color) ? $color : 'gray'));
311
-	}
312
-
313
-
314
-	public function DropShadow(&$gdimg, $distance, $width, $hexcolor, $angle, $alpha) {
315
-		if (phpthumb_functions::gd_version() < 2) {
316
-			return false;
317
-		}
318
-		$distance =                 ($distance ? $distance : 10);
319
-		$width    =                 ($width    ? $width    : 10);
320
-		$hexcolor =                 ($hexcolor ? $hexcolor : '000000');
321
-		$angle    =                 ($angle    ? $angle    : 225) % 360;
322
-		$alpha    = max(0, min(100, ($alpha    ? $alpha    : 100)));
323
-
324
-		if ($alpha <= 0) {
325
-			// invisible shadow, nothing to do
326
-			return true;
327
-		}
328
-		if ($distance <= 0) {
329
-			// shadow completely obscured by source image, nothing to do
330
-			return true;
331
-		}
332
-
333
-		//$width_shadow  = cos(deg2rad($angle)) * ($distance + $width);
334
-		//$height_shadow = sin(deg2rad($angle)) * ($distance + $width);
335
-		//$scaling = min(imagesx($gdimg) / (imagesx($gdimg) + abs($width_shadow)), imagesy($gdimg) / (imagesy($gdimg) + abs($height_shadow)));
336
-
337
-		$Offset = array();
338
-		for ($i = 0; $i < $width; $i++) {
339
-			$WidthAlpha[$i] = (abs(($width / 2) - $i) / $width);
340
-			$Offset['x'] = cos(deg2rad($angle)) * ($distance + $i);
341
-			$Offset['y'] = sin(deg2rad($angle)) * ($distance + $i);
342
-		}
343
-
344
-		$tempImageWidth  = imagesx($gdimg)  + abs($Offset['x']);
345
-		$tempImageHeight = imagesy($gdimg) + abs($Offset['y']);
346
-
347
-		if ($gdimg_dropshadow_temp = phpthumb_functions::ImageCreateFunction($tempImageWidth, $tempImageHeight)) {
348
-
349
-			imagealphablending($gdimg_dropshadow_temp, false);
350
-			imagesavealpha($gdimg_dropshadow_temp, true);
351
-			$transparent1 = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_dropshadow_temp, 0, 0, 0, 127);
352
-			imagefill($gdimg_dropshadow_temp, 0, 0, $transparent1);
353
-
354
-			$PixelMap = array();
355
-			for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
356
-				for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
357
-					$PixelMap[$x][$y] = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
358
-				}
359
-			}
360
-			for ($x = 0; $x < $tempImageWidth; $x++) {
361
-				for ($y = 0; $y < $tempImageHeight; $y++) {
362
-					//for ($i = 0; $i < $width; $i++) {
363
-					for ($i = 0; $i < 1; $i++) {
364
-						if (!isset($PixelMap[$x][$y]['alpha']) || ($PixelMap[$x][$y]['alpha'] > 0)) {
365
-							if (isset($PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha']) && ($PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha'] < 127)) {
366
-								$thisColor = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor, false, $PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha']);
367
-								imagesetpixel($gdimg_dropshadow_temp, $x, $y, $thisColor);
368
-							}
369
-						}
370
-					}
371
-				}
372
-			}
373
-
374
-			imagealphablending($gdimg_dropshadow_temp, true);
375
-			for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
376
-				for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
377
-					if ($PixelMap[$x][$y]['alpha'] < 127) {
378
-						$thisColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_dropshadow_temp, $PixelMap[$x][$y]['red'], $PixelMap[$x][$y]['green'], $PixelMap[$x][$y]['blue'], $PixelMap[$x][$y]['alpha']);
379
-						imagesetpixel($gdimg_dropshadow_temp, $x, $y, $thisColor);
380
-					}
381
-				}
382
-			}
383
-
384
-			imagesavealpha($gdimg, true);
385
-			imagealphablending($gdimg, false);
386
-			//$this->is_alpha = true;
387
-			$transparent2 = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0, 0, 0, 127);
388
-			imagefilledrectangle($gdimg, 0, 0, imagesx($gdimg), imagesy($gdimg), $transparent2);
389
-			imagecopyresampled($gdimg, $gdimg_dropshadow_temp, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg), imagesx($gdimg_dropshadow_temp), imagesy($gdimg_dropshadow_temp));
390
-
391
-			imagedestroy($gdimg_dropshadow_temp);
392
-		}
393
-		return true;
394
-	}
395
-
396
-
397
-	public function EdgeDetect(&$gdimg) {
398
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
399
-			if (imagefilter($gdimg, IMG_FILTER_EDGEDETECT)) {
400
-				return true;
401
-			}
402
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_EDGEDETECT)', __FILE__, __LINE__);
403
-			// fall through and try it the hard way
404
-		}
405
-		// currently not implemented "the hard way"
406
-		$this->DebugMessage('FAILED: phpthumb_filters::EdgeDetect($gdimg) [function not implemented]', __FILE__, __LINE__);
407
-		return false;
408
-	}
409
-
410
-
411
-	public function Ellipse($gdimg) {
412
-		if (phpthumb_functions::gd_version() < 2) {
413
-			return false;
414
-		}
415
-		// generate mask at twice desired resolution and downsample afterwards for easy antialiasing
416
-		if ($gdimg_ellipsemask_double = phpthumb_functions::ImageCreateFunction(imagesx($gdimg) * 2, imagesy($gdimg) * 2)) {
417
-			if ($gdimg_ellipsemask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
418
-
419
-				$color_transparent = imagecolorallocate($gdimg_ellipsemask_double, 255, 255, 255);
420
-				imagefilledellipse($gdimg_ellipsemask_double, imagesx($gdimg), imagesy($gdimg), (imagesx($gdimg) - 1) * 2, (imagesy($gdimg) - 1) * 2, $color_transparent);
421
-				imagecopyresampled($gdimg_ellipsemask, $gdimg_ellipsemask_double, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg), imagesx($gdimg) * 2, imagesy($gdimg) * 2);
422
-
423
-				self::ApplyMask($gdimg_ellipsemask, $gdimg);
424
-				imagedestroy($gdimg_ellipsemask);
425
-				return true;
426
-
427
-			} else {
428
-				$this->DebugMessage('$gdimg_ellipsemask = phpthumb_functions::ImageCreateFunction() failed', __FILE__, __LINE__);
429
-			}
430
-			imagedestroy($gdimg_ellipsemask_double);
431
-		} else {
432
-			$this->DebugMessage('$gdimg_ellipsemask_double = phpthumb_functions::ImageCreateFunction() failed', __FILE__, __LINE__);
433
-		}
434
-		return false;
435
-	}
436
-
437
-
438
-	public function Emboss(&$gdimg) {
439
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
440
-			if (imagefilter($gdimg, IMG_FILTER_EMBOSS)) {
441
-				return true;
442
-			}
443
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_EMBOSS)', __FILE__, __LINE__);
444
-			// fall through and try it the hard way
445
-		}
446
-		// currently not implemented "the hard way"
447
-		$this->DebugMessage('FAILED: phpthumb_filters::Emboss($gdimg) [function not implemented]', __FILE__, __LINE__);
448
-		return false;
449
-	}
450
-
451
-
452
-	public function Flip(&$gdimg, $x=false, $y=false) {
453
-		if (!$x && !$y) {
454
-			return false;
455
-		}
456
-		if ($tempImage = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
457
-			if ($x) {
458
-				imagecopy($tempImage, $gdimg, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg));
459
-				for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
460
-					imagecopy($gdimg, $tempImage, imagesx($gdimg) - 1 - $x, 0, $x, 0, 1, imagesy($gdimg));
461
-				}
462
-			}
463
-			if ($y) {
464
-				imagecopy($tempImage, $gdimg, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg));
465
-				for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
466
-					imagecopy($gdimg, $tempImage, 0, imagesy($gdimg) - 1 - $y, 0, $y, imagesx($gdimg), 1);
467
-				}
468
-			}
469
-			imagedestroy($tempImage);
470
-		}
471
-		return true;
472
-	}
473
-
474
-
475
-	public function Frame(&$gdimg, $frame_width, $edge_width, $hexcolor_frame, $hexcolor1, $hexcolor2) {
476
-		$frame_width    = ($frame_width    ? $frame_width    : 5);
477
-		$edge_width     = ($edge_width     ? $edge_width     : 1);
478
-		$hexcolor_frame = ($hexcolor_frame ? $hexcolor_frame : 'CCCCCC');
479
-		$hexcolor1      = ($hexcolor1      ? $hexcolor1      : 'FFFFFF');
480
-		$hexcolor2      = ($hexcolor2      ? $hexcolor2      : '000000');
481
-
482
-		$color_frame = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor_frame);
483
-		$color1      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor1);
484
-		$color2      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor2);
485
-		for ($i = 0; $i < $edge_width; $i++) {
486
-			// outer bevel
487
-			imageline($gdimg,                   $i,                   $i,                   $i, imagesy($gdimg) - $i, $color1); // left
488
-			imageline($gdimg,                   $i,                   $i, imagesx($gdimg) - $i,                   $i, $color1); // top
489
-			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, imagesx($gdimg) - $i,                   $i, $color2); // right
490
-			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i,                   $i, imagesy($gdimg) - $i, $color2); // bottom
491
-		}
492
-		for ($i = 0; $i < $frame_width; $i++) {
493
-			// actual frame
494
-			imagerectangle($gdimg, $edge_width + $i, $edge_width + $i, imagesx($gdimg) - $edge_width - $i, imagesy($gdimg) - $edge_width - $i, $color_frame);
495
-		}
496
-		for ($i = 0; $i < $edge_width; $i++) {
497
-			// inner bevel
498
-			imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color2); // left
499
-			imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color2); // top
500
-			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color1); // right
501
-			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color1); // bottom
502
-		}
503
-		return true;
504
-	}
505
-
506
-
507
-	public function Gamma(&$gdimg, $amount) {
508
-		if (number_format($amount, 4) == '1.0000') {
509
-			return true;
510
-		}
511
-		return imagegammacorrect($gdimg, 1.0, $amount);
512
-	}
513
-
514
-
515
-	public function Grayscale(&$gdimg) {
516
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
517
-			if (imagefilter($gdimg, IMG_FILTER_GRAYSCALE)) {
518
-				return true;
519
-			}
520
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GRAYSCALE)', __FILE__, __LINE__);
521
-			// fall through and try it the hard way
522
-		}
523
-		return self::Colorize($gdimg, 100, 'gray');
524
-	}
525
-
526
-
527
-	public function HistogramAnalysis(&$gdimg, $calculateGray=false) {
528
-		$ImageSX = imagesx($gdimg);
529
-		$ImageSY = imagesy($gdimg);
530
-		$Analysis = array();
531
-		for ($x = 0; $x < $ImageSX; $x++) {
532
-			for ($y = 0; $y < $ImageSY; $y++) {
533
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
534
-				@$Analysis['red'][$OriginalPixel['red']]++;
535
-				@$Analysis['green'][$OriginalPixel['green']]++;
536
-				@$Analysis['blue'][$OriginalPixel['blue']]++;
537
-				@$Analysis['alpha'][$OriginalPixel['alpha']]++;
538
-				if ($calculateGray) {
539
-					$GrayPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
540
-					@$Analysis['gray'][$GrayPixel['red']]++;
541
-				}
542
-			}
543
-		}
544
-		$keys = array('red', 'green', 'blue', 'alpha');
545
-		if ($calculateGray) {
546
-			$keys[] = 'gray';
547
-		}
548
-		foreach ($keys as $dummy => $key) {
549
-			ksort($Analysis[$key]);
550
-		}
551
-		return $Analysis;
552
-	}
553
-
554
-
555
-	public function HistogramStretch(&$gdimg, $band='*', $method=0, $threshold=0.1) {
556
-		// equivalent of "Auto Contrast" in Adobe Photoshop
557
-		// method 0 stretches according to RGB colors. Gives a more conservative stretch.
558
-		// method 1 band stretches according to grayscale which is color-biased (59% green, 30% red, 11% blue). May give a punchier / more aggressive stretch, possibly appearing over-saturated
559
-		$Analysis = self::HistogramAnalysis($gdimg, true);
560
-		$keys = array('r'=>'red', 'g'=>'green', 'b'=>'blue', 'a'=>'alpha', '*'=>(($method == 0) ? 'all' : 'gray'));
561
-		$band = $band[ 0 ];
562
-		if (!isset($keys[$band])) {
563
-			return false;
564
-		}
565
-		$key = $keys[$band];
566
-
567
-		// If the absolute brightest and darkest pixels are used then one random
568
-		// pixel in the image could throw off the whole system. Instead, count up/down
569
-		// from the limit and allow <threshold> (default = 0.1%) of brightest/darkest
570
-		// pixels to be clipped to min/max
571
-		$threshold = (float) $threshold / 100;
572
-		$clip_threshold = imagesx($gdimg) * imagesx($gdimg) * $threshold;
573
-
574
-		$countsum  = 0;
575
-		$range_min = 0;
576
-		for ($i = 0; $i <= 255; $i++) {
577
-			if ($method == 0) {
578
-				$countsum = max(@$Analysis['red'][$i], @$Analysis['green'][$i], @$Analysis['blue'][$i]);
579
-			} else {
580
-				$countsum += @$Analysis[$key][$i];
581
-			}
582
-			if ($countsum >= $clip_threshold) {
583
-				$range_min = $i - 1;
584
-				break;
585
-			}
586
-		}
587
-		$range_min = max($range_min, 0);
588
-
589
-		$countsum  =   0;
590
-		$range_max = 255;
591
-		for ($i = 255; $i >= 0; $i--) {
592
-			if ($method == 0) {
593
-				$countsum = max(@$Analysis['red'][$i], @$Analysis['green'][$i], @$Analysis['blue'][$i]);
594
-			} else {
595
-				$countsum += @$Analysis[$key][$i];
596
-			}
597
-			if ($countsum >= $clip_threshold) {
598
-				$range_max = $i + 1;
599
-				break;
600
-			}
601
-		}
602
-		$range_max = min($range_max, 255);
603
-
604
-		$range_scale = (($range_max == $range_min) ? 1 : (255 / ($range_max - $range_min)));
605
-		if (($range_min == 0) && ($range_max == 255)) {
606
-			// no adjustment necessary - don't waste CPU time!
607
-			return true;
608
-		}
609
-
610
-		$ImageSX = imagesx($gdimg);
611
-		$ImageSY = imagesy($gdimg);
612
-		for ($x = 0; $x < $ImageSX; $x++) {
613
-			for ($y = 0; $y < $ImageSY; $y++) {
614
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
615
-				if ($band == '*') {
616
-					$new['red']   = min(255, max(0, ($OriginalPixel['red']   - $range_min) * $range_scale));
617
-					$new['green'] = min(255, max(0, ($OriginalPixel['green'] - $range_min) * $range_scale));
618
-					$new['blue']  = min(255, max(0, ($OriginalPixel['blue']  - $range_min) * $range_scale));
619
-					$new['alpha'] = min(255, max(0, ($OriginalPixel['alpha'] - $range_min) * $range_scale));
620
-				} else {
621
-					$new = $OriginalPixel;
622
-					$new[$key] = min(255, max(0, ($OriginalPixel[$key] - $range_min) * $range_scale));
623
-				}
624
-				$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $new['red'], $new['green'], $new['blue'], $new['alpha']);
625
-				imagesetpixel($gdimg, $x, $y, $newColor);
626
-			}
627
-		}
628
-
629
-		return true;
630
-	}
631
-
632
-
633
-	public function HistogramOverlay(&$gdimg, $bands='*', $colors='', $width=0.25, $height=0.25, $alignment='BR', $opacity=50, $margin_x=5, $margin_y=null) {
634
-		$margin_y = (null === $margin_y ? $margin_x : $margin_y);
635
-
636
-		$Analysis = self::HistogramAnalysis($gdimg, true);
637
-		$histW = round(($width > 1) ? min($width, imagesx($gdimg)) : imagesx($gdimg) * $width);
638
-		$histH = round(($width > 1) ? min($width, imagesx($gdimg)) : imagesx($gdimg) * $width);
639
-		if ($gdHist = imagecreatetruecolor($histW, $histH)) {
640
-			$color_back = phpthumb_functions::ImageColorAllocateAlphaSafe($gdHist, 0, 0, 0, 127);
641
-			imagefilledrectangle($gdHist, 0, 0, $histW, $histH, $color_back);
642
-			imagealphablending($gdHist, false);
643
-			imagesavealpha($gdHist, true);
644
-
645
-			$HistogramTempWidth  = 256;
646
-			$HistogramTempHeight = 100;
647
-			if ($gdHistTemp = imagecreatetruecolor($HistogramTempWidth, $HistogramTempHeight)) {
648
-				$color_back_temp = phpthumb_functions::ImageColorAllocateAlphaSafe($gdHistTemp, 255, 0, 255, 127);
649
-				imagealphablending($gdHistTemp, false);
650
-				imagesavealpha($gdHistTemp, true);
651
-				imagefilledrectangle($gdHistTemp, 0, 0, imagesx($gdHistTemp), imagesy($gdHistTemp), $color_back_temp);
652
-
653
-				$DefaultColors = array('r'=>'FF0000', 'g'=>'00FF00', 'b'=>'0000FF', 'a'=>'999999', '*'=>'FFFFFF');
654
-				$Colors = explode(';', $colors);
655
-				$BandsToGraph = array_unique(preg_split('##', $bands));
656
-				$keys = array('r'=>'red', 'g'=>'green', 'b'=>'blue', 'a'=>'alpha', '*'=>'gray');
657
-				foreach ($BandsToGraph as $key => $band) {
658
-					if (!isset($keys[$band])) {
659
-						continue;
660
-					}
661
-					$PeakValue = max($Analysis[$keys[$band]]);
662
-					$thisColor = phpthumb_functions::ImageHexColorAllocate($gdHistTemp, phpthumb_functions::IsHexColor(@$Colors[$key]) ? $Colors[$key] : $DefaultColors[$band]);
663
-					for ($x = 0; $x < $HistogramTempWidth; $x++) {
664
-						imageline($gdHistTemp, $x, $HistogramTempHeight - 1, $x, $HistogramTempHeight - 1 - round(@$Analysis[$keys[$band]][$x] / $PeakValue * $HistogramTempHeight), $thisColor);
665
-					}
666
-					imageline($gdHistTemp, 0, $HistogramTempHeight - 1, $HistogramTempWidth - 1, $HistogramTempHeight - 1, $thisColor);
667
-					imageline($gdHistTemp, 0, $HistogramTempHeight - 2, $HistogramTempWidth - 1, $HistogramTempHeight - 2, $thisColor);
668
-				}
669
-				imagecopyresampled($gdHist, $gdHistTemp, 0, 0, 0, 0, imagesx($gdHist), imagesy($gdHist), imagesx($gdHistTemp), imagesy($gdHistTemp));
670
-				imagedestroy($gdHistTemp);
671
-			} else {
672
-				return false;
673
-			}
674
-
675
-			self::WatermarkOverlay($gdimg, $gdHist, $alignment, $opacity, $margin_x, $margin_y);
676
-			imagedestroy($gdHist);
677
-			return true;
678
-		}
679
-		return false;
680
-	}
681
-
682
-
683
-	public function ImageBorder(&$gdimg, $border_width, $radius_x, $radius_y, $hexcolor_border) {
684
-		$border_width = ($border_width ? $border_width : 1);
685
-		$radius_x     = ($radius_x     ? $radius_x     : 0);
686
-		$radius_y     = ($radius_y     ? $radius_y     : 0);
687
-
688
-		$output_width  = imagesx($gdimg);
689
-		$output_height = imagesy($gdimg);
690
-
691
-		list($new_width, $new_height) = phpthumb_functions::ProportionalResize($output_width, $output_height, $output_width - max($border_width * 2, $radius_x), $output_height - max($border_width * 2, $radius_y));
692
-		$offset_x = ($radius_x ? $output_width  - $new_width  - $radius_x : 0);
693
-
694
-		if ($gd_border_canvas = phpthumb_functions::ImageCreateFunction($output_width, $output_height)) {
695
-
696
-			imagesavealpha($gd_border_canvas, true);
697
-			imagealphablending($gd_border_canvas, false);
698
-			$color_background = phpthumb_functions::ImageColorAllocateAlphaSafe($gd_border_canvas, 255, 255, 255, 127);
699
-			imagefilledrectangle($gd_border_canvas, 0, 0, $output_width, $output_height, $color_background);
700
-
701
-			$color_border = phpthumb_functions::ImageHexColorAllocate($gd_border_canvas, (phpthumb_functions::IsHexColor($hexcolor_border) ? $hexcolor_border : '000000'));
702
-
703
-			for ($i = 0; $i < $border_width; $i++) {
704
-				imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x,                      $i, $output_width - $radius_x - ceil($offset_x / 2),                         $i, $color_border); // top
705
-				imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x, $output_height - 1 - $i, $output_width - $radius_x - ceil($offset_x / 2),    $output_height - 1 - $i, $color_border); // bottom
706
-				imageline($gd_border_canvas,                    floor($offset_x / 2) + $i,               $radius_y,                      floor($offset_x / 2) +  $i, $output_height - $radius_y, $color_border); // left
707
-				imageline($gd_border_canvas, $output_width - 1 - $i - ceil($offset_x / 2),               $radius_y,    $output_width - 1 - $i - ceil($offset_x / 2), $output_height - $radius_y, $color_border); // right
708
-			}
709
-
710
-			if ($radius_x && $radius_y) {
711
-
712
-				// PHP bug: imagearc() with thicknesses > 1 give bad/undesirable/unpredicatable results
713
-				// Solution: Draw multiple 1px arcs side-by-side.
714
-
715
-				// Problem: parallel arcs give strange/ugly antialiasing problems
716
-				// Solution: draw non-parallel arcs, from one side of the line thickness at the start angle
717
-				//   to the opposite edge of the line thickness at the terminating angle
718
-				for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
719
-					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x,              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
720
-					imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2),              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
721
-					imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2), $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
722
-					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x, $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
723
-				}
724
-				if ($border_width > 1) {
725
-					for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
726
-						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                                      $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
727
-						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                                      $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
728
-						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
729
-						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
730
-					}
731
-				}
732
-
733
-			}
734
-			$this->phpThumbObject->ImageResizeFunction($gd_border_canvas, $gdimg, floor(($output_width - $new_width) / 2), round(($output_height - $new_height) / 2), 0, 0, $new_width, $new_height, $output_width, $output_height);
735
-
736
-			imagedestroy($gdimg);
737
-			$gdimg = phpthumb_functions::ImageCreateFunction($output_width, $output_height);
738
-			imagesavealpha($gdimg, true);
739
-			imagealphablending($gdimg, false);
740
-			$gdimg_color_background = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 255, 255, 255, 127);
741
-			imagefilledrectangle($gdimg, 0, 0, $output_width, $output_height, $gdimg_color_background);
742
-
743
-			imagecopy($gdimg, $gd_border_canvas, 0, 0, 0, 0, $output_width, $output_height);
744
-			imagedestroy($gd_border_canvas);
745
-			return true;
746
-
747
-
748
-		} else {
749
-			$this->DebugMessage('FAILED: $gd_border_canvas = phpthumb_functions::ImageCreateFunction('.$output_width.', '.$output_height.')', __FILE__, __LINE__);
750
-		}
751
-		return false;
752
-	}
753
-
754
-
755
-	public static function ImprovedImageRotate(&$gdimg_source, $rotate_angle=0, $config_background_hexcolor='FFFFFF', $bg=null, &$phpThumbObject) {
756
-		while ($rotate_angle < 0) {
757
-			$rotate_angle += 360;
758
-		}
759
-		$rotate_angle %= 360;
760
-		if ($rotate_angle != 0) {
761
-
762
-			$background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_source, $config_background_hexcolor);
763
-
764
-			if ((phpthumb_functions::gd_version() >= 2) && !$bg && ($rotate_angle % 90)) {
765
-
766
-				//$this->DebugMessage('Using alpha rotate', __FILE__, __LINE__);
767
-				if ($gdimg_rotate_mask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_source), imagesy($gdimg_source))) {
768
-
769
-					$color_mask = array();
770
-					for ($i = 0; $i <= 255; $i++) {
771
-						$color_mask[$i] = imagecolorallocate($gdimg_rotate_mask, $i, $i, $i);
772
-					}
773
-					imagefilledrectangle($gdimg_rotate_mask, 0, 0, imagesx($gdimg_rotate_mask), imagesy($gdimg_rotate_mask), $color_mask[255]);
774
-					$imageX = imagesx($gdimg_source);
775
-					$imageY = imagesy($gdimg_source);
776
-					for ($x = 0; $x < $imageX; $x++) {
777
-						for ($y = 0; $y < $imageY; $y++) {
778
-							$pixelcolor = phpthumb_functions::GetPixelColor($gdimg_source, $x, $y);
779
-							imagesetpixel($gdimg_rotate_mask, $x, $y, $color_mask[255 - round($pixelcolor['alpha'] * 255 / 127)]);
780
-						}
781
-					}
782
-					$gdimg_rotate_mask = imagerotate($gdimg_rotate_mask, $rotate_angle, $color_mask[0]);
783
-					$gdimg_source      = imagerotate($gdimg_source,      $rotate_angle, $background_color);
784
-
785
-					imagealphablending($gdimg_source, false);
786
-					imagesavealpha($gdimg_source, true);
787
-					//$this->is_alpha = true;
788
-					$phpThumbFilters = new self();
789
-					//$phpThumbFilters->phpThumbObject = $this;
790
-					$phpThumbFilters->phpThumbObject = $phpThumbObject;
791
-					$phpThumbFilters->ApplyMask($gdimg_rotate_mask, $gdimg_source);
792
-
793
-					imagedestroy($gdimg_rotate_mask);
794
-
795
-				} else {
796
-					//$this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
797
-				}
798
-
799
-			} else {
800
-
801
-				if (phpthumb_functions::gd_version() < 2) {
802
-					//$this->DebugMessage('Using non-alpha rotate because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
803
-				} elseif ($bg) {
804
-					//$this->DebugMessage('Using non-alpha rotate because $this->bg is "'.$bg.'"', __FILE__, __LINE__);
805
-				} elseif ($rotate_angle % 90) {
806
-					//$this->DebugMessage('Using non-alpha rotate because ($rotate_angle % 90) = "'.($rotate_angle % 90).'"', __FILE__, __LINE__);
807
-				} else {
808
-					//$this->DebugMessage('Using non-alpha rotate because $this->thumbnailFormat is "'.$this->thumbnailFormat.'"', __FILE__, __LINE__);
809
-				}
810
-
811
-				if (imagecolortransparent($gdimg_source) >= 0) {
812
-					// imagerotate() forgets all about an image's transparency and sets the transparent color to black
813
-					// To compensate, flood-fill the transparent color of the source image with the specified background color first
814
-					// then rotate and the colors should match
815
-
816
-					if (!function_exists('imageistruecolor') || !imageistruecolor($gdimg_source)) {
817
-						// convert paletted image to true-color before rotating to prevent nasty aliasing artifacts
818
-
819
-						//$this->source_width  = imagesx($gdimg_source);
820
-						//$this->source_height = imagesy($gdimg_source);
821
-						$gdimg_newsrc = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_source), imagesy($gdimg_source));
822
-						$background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $config_background_hexcolor);
823
-						imagefilledrectangle($gdimg_newsrc, 0, 0, imagesx($gdimg_source), imagesy($gdimg_source), phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $config_background_hexcolor));
824
-						imagecopy($gdimg_newsrc, $gdimg_source, 0, 0, 0, 0, imagesx($gdimg_source), imagesy($gdimg_source));
825
-						imagedestroy($gdimg_source);
826
-						unset($gdimg_source);
827
-						$gdimg_source = $gdimg_newsrc;
828
-						unset($gdimg_newsrc);
829
-
830
-					} else {
831
-
832
-						imagecolorset(
833
-							$gdimg_source,
834
-							imagecolortransparent($gdimg_source),
835
-							hexdec(substr($config_background_hexcolor, 0, 2)),
836
-							hexdec(substr($config_background_hexcolor, 2, 2)),
837
-							hexdec(substr($config_background_hexcolor, 4, 2)));
838
-
839
-						imagecolortransparent($gdimg_source, -1);
840
-
841
-					}
842
-				}
843
-
844
-				$gdimg_source = imagerotate($gdimg_source, $rotate_angle, $background_color);
845
-
846
-			}
847
-		}
848
-		return true;
849
-	}
850
-
851
-
852
-	public function MeanRemoval(&$gdimg) {
853
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
854
-			if (imagefilter($gdimg, IMG_FILTER_MEAN_REMOVAL)) {
855
-				return true;
856
-			}
857
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_MEAN_REMOVAL)', __FILE__, __LINE__);
858
-			// fall through and try it the hard way
859
-		}
860
-		// currently not implemented "the hard way"
861
-		$this->DebugMessage('FAILED: phpthumb_filters::MeanRemoval($gdimg) [function not implemented]', __FILE__, __LINE__);
862
-		return false;
863
-	}
864
-
865
-
866
-	public function Negative(&$gdimg) {
867
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
868
-			if (imagefilter($gdimg, IMG_FILTER_NEGATE)) {
869
-				return true;
870
-			}
871
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_NEGATE)', __FILE__, __LINE__);
872
-			// fall through and try it the hard way
873
-		}
874
-		$ImageSX = imagesx($gdimg);
875
-		$ImageSY = imagesy($gdimg);
876
-		for ($x = 0; $x < $ImageSX; $x++) {
877
-			for ($y = 0; $y < $ImageSY; $y++) {
878
-				$currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
879
-				$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, (~$currentPixel['red'] & 0xFF), (~$currentPixel['green'] & 0xFF), (~$currentPixel['blue'] & 0xFF), $currentPixel['alpha']);
880
-				imagesetpixel($gdimg, $x, $y, $newColor);
881
-			}
882
-		}
883
-		return true;
884
-	}
885
-
886
-
887
-	public function RoundedImageCorners(&$gdimg, $radius_x, $radius_y) {
888
-		// generate mask at twice desired resolution and downsample afterwards for easy antialiasing
889
-		// mask is generated as a white double-size ellipse on a triple-size black background and copy-paste-resampled
890
-		// onto a correct-size mask image as 4 corners due to errors when the entire mask is resampled at once (gray edges)
891
-		if ($gdimg_cornermask_triple = phpthumb_functions::ImageCreateFunction($radius_x * 6, $radius_y * 6)) {
892
-			if ($gdimg_cornermask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
893
-
894
-				$color_transparent = imagecolorallocate($gdimg_cornermask_triple, 255, 255, 255);
895
-				imagefilledellipse($gdimg_cornermask_triple, $radius_x * 3, $radius_y * 3, $radius_x * 4, $radius_y * 4, $color_transparent);
896
-
897
-				imagefilledrectangle($gdimg_cornermask, 0, 0, imagesx($gdimg), imagesy($gdimg), $color_transparent);
898
-
899
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0,                           0,     $radius_x,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
900
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0, imagesy($gdimg) - $radius_y,     $radius_x, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
901
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x, imagesy($gdimg) - $radius_y, $radius_x * 3, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
902
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x,                           0, $radius_x * 3,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
903
-
904
-				self::ApplyMask($gdimg_cornermask, $gdimg);
905
-				imagedestroy($gdimg_cornermask);
906
-				$this->DebugMessage('RoundedImageCorners('.$radius_x.', '.$radius_y.') succeeded', __FILE__, __LINE__);
907
-				return true;
908
-
909
-			} else {
910
-				$this->DebugMessage('FAILED: $gdimg_cornermask = phpthumb_functions::ImageCreateFunction('.imagesx($gdimg).', '.imagesy($gdimg).')', __FILE__, __LINE__);
911
-			}
912
-			imagedestroy($gdimg_cornermask_triple);
913
-
914
-		} else {
915
-			$this->DebugMessage('FAILED: $gdimg_cornermask_triple = phpthumb_functions::ImageCreateFunction('.($radius_x * 6).', '.($radius_y * 6).')', __FILE__, __LINE__);
916
-		}
917
-		return false;
918
-	}
919
-
920
-
921
-	public function Saturation(&$gdimg, $amount, $color='') {
922
-		if ($amount == 0) {
923
-			return true;
924
-		} elseif ($amount > 0) {
925
-			$amount = 0 - $amount;
926
-		} else {
927
-			$amount = abs($amount);
928
-		}
929
-		return self::Desaturate($gdimg, $amount, $color);
930
-	}
931
-
932
-
933
-	public function Sepia(&$gdimg, $amount, $targetColor) {
934
-		$amount      = (is_numeric($amount) ? max(0, min(100, $amount)) : 50);
935
-		$amountPct   = $amount / 100;
936
-		$targetColor = (phpthumb_functions::IsHexColor($targetColor) ? $targetColor : 'A28065');
937
-
938
-		if ($amount == 0) {
939
-			return true;
940
-		}
941
-
942
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
943
-			if (imagefilter($gdimg, IMG_FILTER_GRAYSCALE)) {
944
-
945
-				$r = round($amountPct * hexdec(substr($targetColor, 0, 2)));
946
-				$g = round($amountPct * hexdec(substr($targetColor, 2, 2)));
947
-				$b = round($amountPct * hexdec(substr($targetColor, 4, 2)));
948
-				if (imagefilter($gdimg, IMG_FILTER_COLORIZE, $r, $g, $b)) {
949
-					return true;
950
-				}
951
-				$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_COLORIZE)', __FILE__, __LINE__);
952
-				// fall through and try it the hard way
953
-
954
-			} else {
955
-
956
-				$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GRAYSCALE)', __FILE__, __LINE__);
957
-				// fall through and try it the hard way
958
-
959
-			}
960
-		}
961
-
962
-		$TargetPixel['red']   = hexdec(substr($targetColor, 0, 2));
963
-		$TargetPixel['green'] = hexdec(substr($targetColor, 2, 2));
964
-		$TargetPixel['blue']  = hexdec(substr($targetColor, 4, 2));
965
-
966
-		$ImageSX = imagesx($gdimg);
967
-		$ImageSY = imagesy($gdimg);
968
-		for ($x = 0; $x < $ImageSX; $x++) {
969
-			for ($y = 0; $y < $ImageSY; $y++) {
970
-				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
971
-				$GrayPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
972
-
973
-				// http://www.gimpguru.org/Tutorials/SepiaToning/
974
-				// "In the traditional sepia toning process, the tinting occurs most in
975
-				// the mid-tones: the lighter and darker areas appear to be closer to B&W."
976
-				$SepiaAmount = ((128 - abs($GrayPixel['red'] - 128)) / 128) * $amountPct;
977
-
978
-				$NewPixel = array();
979
-				foreach ($TargetPixel as $key => $value) {
980
-					$NewPixel[$key] = round(max(0, min(255, $GrayPixel[$key] * (1 - $SepiaAmount) + ($TargetPixel[$key] * $SepiaAmount))));
981
-				}
982
-				$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue'], $OriginalPixel['alpha']);
983
-				imagesetpixel($gdimg, $x, $y, $newColor);
984
-			}
985
-		}
986
-		return true;
987
-	}
988
-
989
-
990
-	public function Smooth(&$gdimg, $amount=6) {
991
-		$amount = min(25, max(0, $amount));
992
-		if ($amount == 0) {
993
-			return true;
994
-		}
995
-		if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
996
-			if (imagefilter($gdimg, IMG_FILTER_SMOOTH, $amount)) {
997
-				return true;
998
-			}
999
-			$this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_SMOOTH, '.$amount.')', __FILE__, __LINE__);
1000
-			// fall through and try it the hard way
1001
-		}
1002
-		// currently not implemented "the hard way"
1003
-		$this->DebugMessage('FAILED: phpthumb_filters::Smooth($gdimg, '.$amount.') [function not implemented]', __FILE__, __LINE__);
1004
-		return false;
1005
-	}
1006
-
1007
-
1008
-	public function SourceTransparentColorMask(&$gdimg, $hexcolor, $min_limit=5, $max_limit=10) {
1009
-		$width  = imagesx($gdimg);
1010
-		$height = imagesy($gdimg);
1011
-		if ($gdimg_mask = imagecreatetruecolor($width, $height)) {
1012
-			$R = hexdec(substr($hexcolor, 0, 2));
1013
-			$G = hexdec(substr($hexcolor, 2, 2));
1014
-			$B = hexdec(substr($hexcolor, 4, 2));
1015
-			$targetPixel = array('red'=>$R, 'green'=>$G, 'blue'=>$B);
1016
-			$cutoffRange = $max_limit - $min_limit;
1017
-			for ($x = 0; $x < $width; $x++) {
1018
-				for ($y = 0; $y < $height; $y++) {
1019
-					$currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1020
-					$colorDiff = phpthumb_functions::PixelColorDifferencePercent($currentPixel, $targetPixel);
1021
-					$grayLevel = min($cutoffRange, max(0, -$min_limit + $colorDiff)) * (255 / max(1, $cutoffRange));
1022
-					$newColor = imagecolorallocate($gdimg_mask, $grayLevel, $grayLevel, $grayLevel);
1023
-					imagesetpixel($gdimg_mask, $x, $y, $newColor);
1024
-				}
1025
-			}
1026
-			return $gdimg_mask;
1027
-		}
1028
-		return false;
1029
-	}
1030
-
1031
-
1032
-	public function Threshold(&$gdimg, $cutoff) {
1033
-		$width  = imagesx($gdimg);
1034
-		$height = imagesy($gdimg);
1035
-		$cutoff = min(255, max(0, ($cutoff ? $cutoff : 128)));
1036
-		for ($x = 0; $x < $width; $x++) {
1037
-			for ($y = 0; $y < $height; $y++) {
1038
-				$currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1039
-				$grayPixel = phpthumb_functions::GrayscalePixel($currentPixel);
1040
-				if ($grayPixel['red'] < $cutoff) {
1041
-					$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0x00, 0x00, 0x00, $currentPixel['alpha']);
1042
-				} else {
1043
-					$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0xFF, 0xFF, 0xFF, $currentPixel['alpha']);
1044
-				}
1045
-				imagesetpixel($gdimg, $x, $y, $newColor);
1046
-			}
1047
-		}
1048
-		return true;
1049
-	}
1050
-
1051
-
1052
-	public function ImageTrueColorToPalette2(&$image, $dither, $ncolors) {
1053
-		// http://www.php.net/manual/en/function.imagetruecolortopalette.php
1054
-		// zmorris at zsculpt dot com (17-Aug-2004 06:58)
1055
-		$width  = imagesx($image);
1056
-		$height = imagesy($image);
1057
-		$image_copy = imagecreatetruecolor($width, $height);
1058
-		//imagecopymerge($image_copy, $image, 0, 0, 0, 0, $width, $height, 100);
1059
-		imagecopy($image_copy, $image, 0, 0, 0, 0, $width, $height);
1060
-		imagetruecolortopalette($image, $dither, $ncolors);
1061
-		imagecolormatch($image_copy, $image);
1062
-		imagedestroy($image_copy);
1063
-		return true;
1064
-	}
1065
-
1066
-	public function ReduceColorDepth(&$gdimg, $colors=256, $dither=true) {
1067
-		$colors = max(min($colors, 256), 2);
1068
-		// imagetruecolortopalette usually makes ugly colors, the replacement is a bit better
1069
-		//imagetruecolortopalette($gdimg, $dither, $colors);
1070
-		self::ImageTrueColorToPalette2($gdimg, $dither, $colors);
1071
-		return true;
1072
-	}
1073
-
1074
-
1075
-	public function WhiteBalance(&$gdimg, $targetColor='') {
1076
-		if (phpthumb_functions::IsHexColor($targetColor)) {
1077
-			$targetPixel = array(
1078
-				'red'   => hexdec(substr($targetColor, 0, 2)),
1079
-				'green' => hexdec(substr($targetColor, 2, 2)),
1080
-				'blue'  => hexdec(substr($targetColor, 4, 2))
1081
-			);
1082
-		} else {
1083
-			$Analysis = self::HistogramAnalysis($gdimg, false);
1084
-			$targetPixel = array(
1085
-				'red'   => max(array_keys($Analysis['red'])),
1086
-				'green' => max(array_keys($Analysis['green'])),
1087
-				'blue'  => max(array_keys($Analysis['blue']))
1088
-			);
1089
-		}
1090
-		$grayValue = phpthumb_functions::GrayscaleValue($targetPixel['red'], $targetPixel['green'], $targetPixel['blue']);
1091
-		$scaleR = $grayValue / $targetPixel['red'];
1092
-		$scaleG = $grayValue / $targetPixel['green'];
1093
-		$scaleB = $grayValue / $targetPixel['blue'];
1094
-
1095
-		for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
1096
-			for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
1097
-				$currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1098
-				$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe(
1099
-					$gdimg,
1100
-					max(0, min(255, round($currentPixel['red']   * $scaleR))),
1101
-					max(0, min(255, round($currentPixel['green'] * $scaleG))),
1102
-					max(0, min(255, round($currentPixel['blue']  * $scaleB))),
1103
-					$currentPixel['alpha']
1104
-				);
1105
-				imagesetpixel($gdimg, $x, $y, $newColor);
1106
-			}
1107
-		}
1108
-		return true;
1109
-	}
1110
-
1111
-
1112
-	public function WatermarkText(&$gdimg, $text, $size, $alignment, $hex_color='000000', $ttffont='', $opacity=100, $margin=5, $angle=0, $bg_color=false, $bg_opacity=0, $fillextend='', $lineheight=1.0) {
1113
-		// text watermark requested
1114
-		if (!$text) {
1115
-			return false;
1116
-		}
1117
-		imagealphablending($gdimg, true);
1118
-
1119
-		if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)(@[LCR])?$#i', $alignment, $matches)) {
1120
-			$originOffsetX = (int) $matches[ 1];
1121
-			$originOffsetY = (int) $matches[ 2];
1122
-			$alignment = (@$matches[4] ? $matches[4] : 'L');
1123
-			$margin = 0;
1124
-		} else {
1125
-			$originOffsetX = 0;
1126
-			$originOffsetY = 0;
1127
-		}
1128
-		$lineheight = min(100.0, max(0.01, (float) $lineheight));
1129
-
1130
-		$metaTextArray = array(
1131
-			'^Fb' =>       $this->phpThumbObject->getimagesizeinfo['filesize'],
1132
-			'^Fk' => round($this->phpThumbObject->getimagesizeinfo['filesize'] / 1024),
1133
-			'^Fm' => round($this->phpThumbObject->getimagesizeinfo['filesize'] / 1048576),
1134
-			'^X'  => $this->phpThumbObject->getimagesizeinfo[0],
1135
-			'^Y'  => $this->phpThumbObject->getimagesizeinfo[1],
1136
-			'^x'  => imagesx($gdimg),
1137
-			'^y'  => imagesy($gdimg),
1138
-			'^^'  => '^',
1139
-		);
1140
-		$text = strtr($text, $metaTextArray);
1141
-
1142
-		$text = str_replace(array(
1143
-			"\r\n",
1144
-			"\r"
1145
-		), "\n", $text);
1146
-		$textlines = explode("\n", $text);
1147
-		$this->DebugMessage('Processing '.count($textlines).' lines of text', __FILE__, __LINE__);
1148
-
1149
-		if (@is_readable($ttffont) && is_file($ttffont)) {
1150
-
1151
-			$opacity = 100 - (int) max(min($opacity, 100), 0);
1152
-			$letter_color_text = phpthumb_functions::ImageHexColorAllocate($gdimg, $hex_color, false, $opacity * 1.27);
1153
-
1154
-			$this->DebugMessage('Using TTF font "'.$ttffont.'"', __FILE__, __LINE__);
1155
-
1156
-			$TTFbox = imagettfbbox($size, $angle, $ttffont, $text);
1157
-
1158
-			$min_x = min($TTFbox[0], $TTFbox[2], $TTFbox[4], $TTFbox[6]);
1159
-			$max_x = max($TTFbox[0], $TTFbox[2], $TTFbox[4], $TTFbox[6]);
1160
-			//$text_width = round($max_x - $min_x + ($size * 0.5));
1161
-			$text_width = round($max_x - $min_x);
1162
-
1163
-			$min_y = min($TTFbox[1], $TTFbox[3], $TTFbox[5], $TTFbox[7]);
1164
-			$max_y = max($TTFbox[1], $TTFbox[3], $TTFbox[5], $TTFbox[7]);
1165
-			//$text_height = round($max_y - $min_y + ($size * 0.5));
1166
-			$text_height = round($max_y - $min_y);
1167
-
1168
-			$TTFboxChar = imagettfbbox($size, $angle, $ttffont, 'jH');
1169
-			$char_min_y = min($TTFboxChar[1], $TTFboxChar[3], $TTFboxChar[5], $TTFboxChar[7]);
1170
-			$char_max_y = max($TTFboxChar[1], $TTFboxChar[3], $TTFboxChar[5], $TTFboxChar[7]);
1171
-			$char_height = round($char_max_y - $char_min_y);
1172
-
1173
-			if ($alignment == '*') {
1174
-
1175
-				$text_origin_y = $char_height + $margin;
1176
-				while (($text_origin_y - $text_height) < imagesy($gdimg)) {
1177
-					$text_origin_x = $margin;
1178
-					while ($text_origin_x < imagesx($gdimg)) {
1179
-						imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y, $letter_color_text, $ttffont, $text);
1180
-						$text_origin_x += ($text_width + $margin);
1181
-					}
1182
-					$text_origin_y += ($text_height + $margin) * $lineheight;
1183
-				}
1184
-
1185
-			} else {
1186
-
1187
-				// this block for background color only
1188
-
1189
-				$text_origin_x = 0;
1190
-				$text_origin_y = 0;
1191
-				switch ($alignment) {
1192
-					case '*':
1193
-						// handled separately
1194
-						break;
1195
-
1196
-					case 'T':
1197
-						$text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1198
-						$text_origin_y = $char_height + $margin + $originOffsetY;
1199
-						break;
1200
-
1201
-					case 'B':
1202
-						$text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1203
-						$text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1204
-						break;
1205
-
1206
-					case 'L':
1207
-						$text_origin_x = $margin + $originOffsetX;
1208
-						$text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1209
-						break;
1210
-
1211
-					case 'R':
1212
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1213
-						$text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1214
-						break;
1215
-
1216
-					case 'C':
1217
-						$text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1218
-						$text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1219
-						break;
1220
-
1221
-					case 'TL':
1222
-						$text_origin_x = $margin + $originOffsetX;
1223
-						$text_origin_y = $char_height + $margin + $originOffsetY;
1224
-						break;
1225
-
1226
-					case 'TR':
1227
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1228
-						$text_origin_y = $char_height + $margin + $originOffsetY;
1229
-						break;
1230
-
1231
-					case 'BL':
1232
-						$text_origin_x = $margin + $originOffsetX;
1233
-						$text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1234
-						break;
1235
-
1236
-					case 'BR':
1237
-					default:
1238
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1239
-						$text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1240
-						break;
1241
-				}
1242
-
1243
-				if (phpthumb_functions::IsHexColor($bg_color)) {
1244
-					$text_background_alpha = round(127 * ((100 - min(max(0, $bg_opacity), 100)) / 100));
1245
-					$text_color_background = phpthumb_functions::ImageHexColorAllocate($gdimg, $bg_color, false, $text_background_alpha);
1246
-				} else {
1247
-					$text_color_background = phpthumb_functions::ImageHexColorAllocate($gdimg, 'FFFFFF', false, 127);
1248
-				}
1249
-				$x1 = $text_origin_x + $min_x;
1250
-				$y1 = $text_origin_y + $TTFbox[1];
1251
-				$x2 = $text_origin_x + $min_x + $text_width;
1252
-				$y2 = $text_origin_y + $TTFbox[1] - $text_height;
1253
-				$x_TL = false !== stripos($fillextend, "x") ?               0 : min($x1, $x2);
1254
-				$y_TL = false !== stripos($fillextend, "y") ?               0 : min($y1, $y2);
1255
-				$x_BR = false !== stripos($fillextend, "x") ? imagesx($gdimg) : max($x1, $x2);
1256
-				$y_BR = false !== stripos($fillextend, "y") ? imagesy($gdimg) : max($y1, $y2);
1257
-				$this->DebugMessage('WatermarkText() calling imagefilledrectangle($gdimg, '.$x_TL.', '.$y_TL.', '.$x_BR.', '.$y_BR.', $text_color_background)', __FILE__, __LINE__);
1258
-				imagefilledrectangle($gdimg, $x_TL, $y_TL, $x_BR, $y_BR, $text_color_background);
1259
-
1260
-				// end block for background color only
1261
-
1262
-
1263
-				$y_offset = 0;
1264
-				foreach ($textlines as $dummy => $line) {
1265
-
1266
-					$TTFboxLine = imagettfbbox($size, $angle, $ttffont, $line);
1267
-					$min_x_line = min($TTFboxLine[0], $TTFboxLine[2], $TTFboxLine[4], $TTFboxLine[6]);
1268
-					$max_x_line = max($TTFboxLine[0], $TTFboxLine[2], $TTFboxLine[4], $TTFboxLine[6]);
1269
-					$text_width_line = round($max_x_line - $min_x_line);
1270
-
1271
-					switch ($alignment) {
1272
-						// $text_origin_y set above, just re-set $text_origin_x here as needed
1273
-
1274
-						case 'L':
1275
-						case 'TL':
1276
-						case 'BL':
1277
-							// no change necessary
1278
-							break;
1279
-
1280
-						case 'C':
1281
-						case 'T':
1282
-						case 'B':
1283
-							$text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width_line / 2) : round((imagesx($gdimg) - $text_width_line) / 2));
1284
-							break;
1285
-
1286
-						case 'R':
1287
-						case 'TR':
1288
-						case 'BR':
1289
-							$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width_line : imagesx($gdimg) - $text_width_line  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1290
-							break;
1291
-					}
1292
-
1293
-					//imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y, $letter_color_text, $ttffont, $text);
1294
-					$this->DebugMessage('WatermarkText() calling imagettftext($gdimg, '.$size.', '.$angle.', '.$text_origin_x.', '.($text_origin_y + $y_offset).', $letter_color_text, '.$ttffont.', '.$line.')', __FILE__, __LINE__);
1295
-					imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y + $y_offset, $letter_color_text, $ttffont, $line);
1296
-
1297
-					$y_offset += $char_height * $lineheight;
1298
-				}
1299
-
1300
-			}
1301
-			return true;
1302
-
1303
-		} else {
1304
-
1305
-			$size = min(5, max(1, $size));
1306
-			$this->DebugMessage('Using built-in font (size='.$size.') for text watermark'.($ttffont ? ' because $ttffont !is_readable('.$ttffont.')' : ''), __FILE__, __LINE__);
1307
-
1308
-			$text_width  = 0;
1309
-			$text_height = 0;
1310
-			foreach ($textlines as $dummy => $line) {
1311
-				$text_width   = max($text_width, imagefontwidth($size) * strlen($line));
1312
-				$text_height += imagefontheight($size);
1313
-			}
1314
-			if ($img_watermark = phpthumb_functions::ImageCreateFunction($text_width, $text_height)) {
1315
-				imagealphablending($img_watermark, false);
1316
-				if (phpthumb_functions::IsHexColor($bg_color)) {
1317
-					$text_background_alpha = round(127 * ((100 - min(max(0, $bg_opacity), 100)) / 100));
1318
-					$text_color_background = phpthumb_functions::ImageHexColorAllocate($img_watermark, $bg_color, false, $text_background_alpha);
1319
-				} else {
1320
-					$text_color_background = phpthumb_functions::ImageHexColorAllocate($img_watermark, 'FFFFFF', false, 127);
1321
-				}
1322
-				$this->DebugMessage('WatermarkText() calling imagefilledrectangle($img_watermark, 0, 0, '.imagesx($img_watermark).', '.imagesy($img_watermark).', $text_color_background)', __FILE__, __LINE__);
1323
-				imagefilledrectangle($img_watermark, 0, 0, imagesx($img_watermark), imagesy($img_watermark), $text_color_background);
1324
-
1325
-				$img_watermark_mask    = false;
1326
-				$mask_color_background = false;
1327
-				$mask_color_watermark  = false;
1328
-				if ($angle && function_exists('imagerotate')) {
1329
-					// using $img_watermark_mask is pointless if imagerotate function isn't available
1330
-					if ($img_watermark_mask = phpthumb_functions::ImageCreateFunction($text_width, $text_height)) {
1331
-						$mask_color_background = imagecolorallocate($img_watermark_mask, 0, 0, 0);
1332
-						imagealphablending($img_watermark_mask, false);
1333
-						imagefilledrectangle($img_watermark_mask, 0, 0, imagesx($img_watermark_mask), imagesy($img_watermark_mask), $mask_color_background);
1334
-						$mask_color_watermark = imagecolorallocate($img_watermark_mask, 255, 255, 255);
1335
-					}
1336
-				}
1337
-
1338
-				$text_color_watermark = phpthumb_functions::ImageHexColorAllocate($img_watermark, $hex_color);
1339
-				$x_offset = 0;
1340
-				foreach ($textlines as $key => $line) {
1341
-					switch ($alignment) {
1342
-						case 'C':
1343
-							$x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1344
-							$originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1345
-							$originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1346
-							break;
1347
-
1348
-						case 'T':
1349
-							$x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1350
-							$originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1351
-							$originOffsetY = $margin;
1352
-							break;
1353
-
1354
-						case 'B':
1355
-							$x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1356
-							$originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1357
-							$originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1358
-							break;
1359
-
1360
-						case 'L':
1361
-							$x_offset = 0;
1362
-							$originOffsetX = $margin;
1363
-							$originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1364
-							break;
1365
-
1366
-						case 'TL':
1367
-							$x_offset = 0;
1368
-							$originOffsetX = $margin;
1369
-							$originOffsetY = $margin;
1370
-							break;
1371
-
1372
-						case 'BL':
1373
-							$x_offset = 0;
1374
-							$originOffsetX = $margin;
1375
-							$originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1376
-							break;
1377
-
1378
-						case 'R':
1379
-							$x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1380
-							$originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1381
-							$originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1382
-							break;
1383
-
1384
-						case 'TR':
1385
-							$x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1386
-							$originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1387
-							$originOffsetY = $margin;
1388
-							break;
1389
-
1390
-						case 'BR':
1391
-						default:
1392
-							if (!empty($originOffsetX) || !empty($originOffsetY)) {
1393
-								// absolute pixel positioning
1394
-							} else {
1395
-								$x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1396
-								$originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1397
-								$originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1398
-							}
1399
-							break;
1400
-					}
1401
-					$this->DebugMessage('WatermarkText() calling imagestring($img_watermark, '.$size.', '.$x_offset.', '.($key * imagefontheight($size)).', '.$line.', $text_color_watermark)', __FILE__, __LINE__);
1402
-					imagestring($img_watermark, $size, $x_offset, $key * imagefontheight($size), $line, $text_color_watermark);
1403
-					if ($angle && $img_watermark_mask) {
1404
-						$this->DebugMessage('WatermarkText() calling imagestring($img_watermark_mask, '.$size.', '.$x_offset.', '.($key * imagefontheight($size) * $lineheight).', '.$text.', $mask_color_watermark)', __FILE__, __LINE__);
1405
-						imagestring($img_watermark_mask, $size, $x_offset, $key * imagefontheight($size) * $lineheight, $text, $mask_color_watermark);
1406
-					}
1407
-				}
1408
-				if ($angle && $img_watermark_mask) {
1409
-					$img_watermark      = imagerotate($img_watermark,      $angle, $text_color_background);
1410
-					$img_watermark_mask = imagerotate($img_watermark_mask, $angle, $mask_color_background);
1411
-					self::ApplyMask($img_watermark_mask, $img_watermark);
1412
-				}
1413
-				//phpthumb_filters::WatermarkOverlay($gdimg, $img_watermark, $alignment, $opacity, $margin);
1414
-				$this->DebugMessage('WatermarkText() calling phpthumb_filters::WatermarkOverlay($gdimg, $img_watermark, '.($originOffsetX.'x'.$originOffsetY).', '.$opacity.', 0)', __FILE__, __LINE__);
1415
-				self::WatermarkOverlay($gdimg, $img_watermark, $originOffsetX.'x'.$originOffsetY, $opacity, 0);
1416
-				imagedestroy($img_watermark);
1417
-				return true;
1418
-			}
1419
-
1420
-		}
1421
-		return false;
1422
-	}
1423
-
1424
-
1425
-	public function WatermarkOverlay(&$gdimg_dest, &$img_watermark, $alignment='*', $opacity=50, $margin_x=5, $margin_y=null) {
1426
-
1427
-		if (is_resource($gdimg_dest) && is_resource($img_watermark)) {
1428
-			$img_source_width          = imagesx($gdimg_dest);
1429
-			$img_source_height         = imagesy($gdimg_dest);
1430
-			$watermark_source_width    = imagesx($img_watermark);
1431
-			$watermark_source_height   = imagesy($img_watermark);
1432
-			$watermark_opacity_percent = max(0, min(100, $opacity));
1433
-			$margin_y = (null === $margin_y ? $margin_x : $margin_y);
1434
-			$watermark_margin_x = ((($margin_x > 0) && ($margin_x < 1)) ? round((1 - $margin_x) * $img_source_width)  : $margin_x);
1435
-			$watermark_margin_y = ((($margin_y > 0) && ($margin_y < 1)) ? round((1 - $margin_y) * $img_source_height) : $margin_y);
1436
-			$watermark_destination_x = 0;
1437
-			$watermark_destination_y = 0;
1438
-			if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) {
1439
-				$watermark_destination_x = (int) $matches[ 1];
1440
-				$watermark_destination_y = (int) $matches[ 2];
1441
-			} else {
1442
-				switch ($alignment) {
1443
-					case '*':
1444
-						if ($gdimg_tiledwatermark = phpthumb_functions::ImageCreateFunction($img_source_width, $img_source_height)) {
1445
-
1446
-							imagealphablending($gdimg_tiledwatermark, false);
1447
-							imagesavealpha($gdimg_tiledwatermark, true);
1448
-							$text_color_transparent = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_tiledwatermark, 255, 0, 255, 127);
1449
-							imagefill($gdimg_tiledwatermark, 0, 0, $text_color_transparent);
1450
-
1451
-							// set the tiled image transparent color to whatever the untiled image transparency index is
1452
-	//						imagecolortransparent($gdimg_tiledwatermark, imagecolortransparent($img_watermark));
1453
-
1454
-							// a "cleaner" way of doing it, but can't handle the margin feature :(
1455
-	//						imagesettile($gdimg_tiledwatermark, $img_watermark);
1456
-	//						imagefill($gdimg_tiledwatermark, 0, 0, IMG_COLOR_TILED);
1457
-	//						break;
1458
-
1459
-	//						imagefill($gdimg_tiledwatermark, 0, 0, imagecolortransparent($gdimg_tiledwatermark));
1460
-							// tile the image as many times as can fit
1461
-							for ($x = $watermark_margin_x; $x < ($img_source_width + $watermark_source_width); $x += ($watermark_source_width + $watermark_margin_x)) {
1462
-								for ($y = $watermark_margin_y; $y < ($img_source_height + $watermark_source_height); $y += ($watermark_source_height + $watermark_margin_y)) {
1463
-									imagecopy(
1464
-										$gdimg_tiledwatermark,
1465
-										$img_watermark,
1466
-										$x,
1467
-										$y,
1468
-										0,
1469
-										0,
1470
-										min($watermark_source_width,  $img_source_width  - $x - $watermark_margin_x),
1471
-										min($watermark_source_height, $img_source_height - $y - $watermark_margin_y)
1472
-									);
1473
-								}
1474
-							}
1475
-
1476
-							$watermark_source_width  = imagesx($gdimg_tiledwatermark);
1477
-							$watermark_source_height = imagesy($gdimg_tiledwatermark);
1478
-							$watermark_destination_x = 0;
1479
-							$watermark_destination_y = 0;
1480
-
1481
-							imagedestroy($img_watermark);
1482
-							$img_watermark = $gdimg_tiledwatermark;
1483
-						}
1484
-						break;
1485
-
1486
-					case 'T':
1487
-						$watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1488
-						$watermark_destination_y = $watermark_margin_y;
1489
-						break;
1490
-
1491
-					case 'B':
1492
-						$watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1493
-						$watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1494
-						break;
1495
-
1496
-					case 'L':
1497
-						$watermark_destination_x = $watermark_margin_x;
1498
-						$watermark_destination_y = round((($img_source_height / 2) - ($watermark_source_height / 2)) + $watermark_margin_y);
1499
-						break;
1500
-
1501
-					case 'R':
1502
-						$watermark_destination_x = $img_source_width - $watermark_source_width - $watermark_margin_x;
1503
-						$watermark_destination_y = round((($img_source_height / 2) - ($watermark_source_height / 2)) + $watermark_margin_y);
1504
-						break;
1505
-
1506
-					case 'C':
1507
-						$watermark_destination_x = round(($img_source_width  / 2) - ($watermark_source_width  / 2));
1508
-						$watermark_destination_y = round(($img_source_height / 2) - ($watermark_source_height / 2));
1509
-						break;
1510
-
1511
-					case 'TL':
1512
-						$watermark_destination_x = $watermark_margin_x;
1513
-						$watermark_destination_y = $watermark_margin_y;
1514
-						break;
1515
-
1516
-					case 'TR':
1517
-						$watermark_destination_x = $img_source_width - $watermark_source_width - $watermark_margin_x;
1518
-						$watermark_destination_y = $watermark_margin_y;
1519
-						break;
1520
-
1521
-					case 'BL':
1522
-						$watermark_destination_x = $watermark_margin_x;
1523
-						$watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1524
-						break;
1525
-
1526
-					case 'BR':
1527
-					default:
1528
-						$watermark_destination_x = $img_source_width  - $watermark_source_width  - $watermark_margin_x;
1529
-						$watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1530
-						break;
1531
-				}
1532
-			}
1533
-			imagealphablending($gdimg_dest, false);
1534
-			imagesavealpha($gdimg_dest, true);
1535
-			imagesavealpha($img_watermark, true);
1536
-			phpthumb_functions::ImageCopyRespectAlpha($gdimg_dest, $img_watermark, $watermark_destination_x, $watermark_destination_y, 0, 0, $watermark_source_width, $watermark_source_height, $watermark_opacity_percent);
1537
-
1538
-			return true;
1539
-		}
1540
-		return false;
1541
-	}
98
+    public function Blur(&$gdimg, $radius=0.5) {
99
+        // Taken from Torstein Hønsi's phpUnsharpMask (see phpthumb.unsharp.php)
100
+
101
+        $radius = round(max(0, min($radius, 50)) * 2);
102
+        if (!$radius) {
103
+            return false;
104
+        }
105
+
106
+        $w = imagesx($gdimg);
107
+        $h = imagesy($gdimg);
108
+        if ($imgBlur = imagecreatetruecolor($w, $h)) {
109
+            // Gaussian blur matrix:
110
+            //	1	2	1
111
+            //	2	4	2
112
+            //	1	2	1
113
+
114
+            // Move copies of the image around one pixel at the time and merge them with weight
115
+            // according to the matrix. The same matrix is simply repeated for higher radii.
116
+            for ($i = 0; $i < $radius; $i++)	{
117
+                imagecopy     ($imgBlur, $gdimg, 0, 0, 1, 1, $w - 1, $h - 1);            // up left
118
+                imagecopymerge($imgBlur, $gdimg, 1, 1, 0, 0, $w,     $h,     50.00000);  // down right
119
+                imagecopymerge($imgBlur, $gdimg, 0, 1, 1, 0, $w - 1, $h,     33.33333);  // down left
120
+                imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 1, $w,     $h - 1, 25.00000);  // up right
121
+                imagecopymerge($imgBlur, $gdimg, 0, 0, 1, 0, $w - 1, $h,     33.33333);  // left
122
+                imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 0, $w,     $h,     25.00000);  // right
123
+                imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 1, $w,     $h - 1, 20.00000);  // up
124
+                imagecopymerge($imgBlur, $gdimg, 0, 1, 0, 0, $w,     $h,     16.666667); // down
125
+                imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 0, $w,     $h,     50.000000); // center
126
+                imagecopy     ($gdimg, $imgBlur, 0, 0, 0, 0, $w,     $h);
127
+            }
128
+            return true;
129
+        }
130
+        return false;
131
+    }
132
+
133
+
134
+    public function BlurGaussian(&$gdimg) {
135
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
136
+            if (imagefilter($gdimg, IMG_FILTER_GAUSSIAN_BLUR)) {
137
+                return true;
138
+            }
139
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GAUSSIAN_BLUR)', __FILE__, __LINE__);
140
+            // fall through and try it the hard way
141
+        }
142
+        $this->DebugMessage('FAILED: phpthumb_filters::BlurGaussian($gdimg) [using phpthumb_filters::Blur() instead]', __FILE__, __LINE__);
143
+        return self::Blur($gdimg, 0.5);
144
+    }
145
+
146
+
147
+    public function BlurSelective(&$gdimg) {
148
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
149
+            if (imagefilter($gdimg, IMG_FILTER_SELECTIVE_BLUR)) {
150
+                return true;
151
+            }
152
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_SELECTIVE_BLUR)', __FILE__, __LINE__);
153
+            // fall through and try it the hard way
154
+        }
155
+        // currently not implemented "the hard way"
156
+        $this->DebugMessage('FAILED: phpthumb_filters::BlurSelective($gdimg) [function not implemented]', __FILE__, __LINE__);
157
+        return false;
158
+    }
159
+
160
+
161
+    public function Brightness(&$gdimg, $amount=0) {
162
+        if ($amount == 0) {
163
+            return true;
164
+        }
165
+        $amount = max(-255, min(255, $amount));
166
+
167
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
168
+            if (imagefilter($gdimg, IMG_FILTER_BRIGHTNESS, $amount)) {
169
+                return true;
170
+            }
171
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_BRIGHTNESS, '.$amount.')', __FILE__, __LINE__);
172
+            // fall through and try it the hard way
173
+        }
174
+
175
+        $scaling = (255 - abs($amount)) / 255;
176
+        $baseamount = (($amount > 0) ? $amount : 0);
177
+        for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
178
+            for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
179
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
180
+                $NewPixel = array();
181
+                foreach ($OriginalPixel as $key => $value) {
182
+                    $NewPixel[$key] = round($baseamount + ($OriginalPixel[$key] * $scaling));
183
+                }
184
+                $newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
185
+                imagesetpixel($gdimg, $x, $y, $newColor);
186
+            }
187
+        }
188
+        return true;
189
+    }
190
+
191
+
192
+    public function Contrast(&$gdimg, $amount=0) {
193
+        if ($amount == 0) {
194
+            return true;
195
+        }
196
+        $amount = max(-255, min(255, $amount));
197
+
198
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
199
+            // imagefilter(IMG_FILTER_CONTRAST) has range +100 to -100 (positive numbers make it darker!)
200
+            $amount = ($amount / 255) * -100;
201
+            if (imagefilter($gdimg, IMG_FILTER_CONTRAST, $amount)) {
202
+                return true;
203
+            }
204
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_CONTRAST, '.$amount.')', __FILE__, __LINE__);
205
+            // fall through and try it the hard way
206
+        }
207
+
208
+        if ($amount > 0) {
209
+            $scaling = 1 + ($amount / 255);
210
+        } else {
211
+            $scaling = (255 - abs($amount)) / 255;
212
+        }
213
+        for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
214
+            for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
215
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
216
+                $NewPixel = array();
217
+                foreach ($OriginalPixel as $key => $value) {
218
+                    $NewPixel[$key] = min(255, max(0, round($OriginalPixel[$key] * $scaling)));
219
+                }
220
+                $newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
221
+                imagesetpixel($gdimg, $x, $y, $newColor);
222
+            }
223
+        }
224
+        return true;
225
+    }
226
+
227
+
228
+    public function Colorize(&$gdimg, $amount, $targetColor) {
229
+        $amount      = (is_numeric($amount)                          ? $amount      : 25);
230
+        $amountPct   = $amount / 100;
231
+        $targetColor = (phpthumb_functions::IsHexColor($targetColor) ? $targetColor : 'gray');
232
+
233
+        if ($amount == 0) {
234
+            return true;
235
+        }
236
+
237
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
238
+            if ($targetColor == 'gray') {
239
+                $targetColor = '808080';
240
+            }
241
+            $r = round($amountPct * hexdec(substr($targetColor, 0, 2)));
242
+            $g = round($amountPct * hexdec(substr($targetColor, 2, 2)));
243
+            $b = round($amountPct * hexdec(substr($targetColor, 4, 2)));
244
+            if (imagefilter($gdimg, IMG_FILTER_COLORIZE, $r, $g, $b)) {
245
+                return true;
246
+            }
247
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_COLORIZE)', __FILE__, __LINE__);
248
+            // fall through and try it the hard way
249
+        }
250
+
251
+        // overridden below for grayscale
252
+        $TargetPixel = array();
253
+        if ($targetColor != 'gray') {
254
+            $TargetPixel['red']   = hexdec(substr($targetColor, 0, 2));
255
+            $TargetPixel['green'] = hexdec(substr($targetColor, 2, 2));
256
+            $TargetPixel['blue']  = hexdec(substr($targetColor, 4, 2));
257
+        }
258
+
259
+        for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
260
+            for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
261
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
262
+                if ($targetColor == 'gray') {
263
+                    $TargetPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
264
+                }
265
+                $NewPixel = array();
266
+                foreach ($TargetPixel as $key => $value) {
267
+                    $NewPixel[$key] = round(max(0, min(255, ($OriginalPixel[$key] * ((100 - $amount) / 100)) + ($TargetPixel[$key] * $amountPct))));
268
+                }
269
+                //$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue'], $OriginalPixel['alpha']);
270
+                $newColor = imagecolorallocate($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue']);
271
+                imagesetpixel($gdimg, $x, $y, $newColor);
272
+            }
273
+        }
274
+        return true;
275
+    }
276
+
277
+
278
+    public function Crop(&$gdimg, $left=0, $right=0, $top=0, $bottom=0) {
279
+        if (!$left && !$right && !$top && !$bottom) {
280
+            return true;
281
+        }
282
+        $oldW = imagesx($gdimg);
283
+        $oldH = imagesy($gdimg);
284
+        if (($left   > 0) && ($left   < 1)) { $left   = round($left   * $oldW); }
285
+        if (($right  > 0) && ($right  < 1)) { $right  = round($right  * $oldW); }
286
+        if (($top    > 0) && ($top    < 1)) { $top    = round($top    * $oldH); }
287
+        if (($bottom > 0) && ($bottom < 1)) { $bottom = round($bottom * $oldH); }
288
+        $right  = min($oldW - $left - 1, $right);
289
+        $bottom = min($oldH - $top  - 1, $bottom);
290
+        $newW = $oldW - $left - $right;
291
+        $newH = $oldH - $top  - $bottom;
292
+
293
+        if ($imgCropped = imagecreatetruecolor($newW, $newH)) {
294
+            imagecopy($imgCropped, $gdimg, 0, 0, $left, $top, $newW, $newH);
295
+            if ($gdimg = imagecreatetruecolor($newW, $newH)) {
296
+                imagecopy($gdimg, $imgCropped, 0, 0, 0, 0, $newW, $newH);
297
+                imagedestroy($imgCropped);
298
+                return true;
299
+            }
300
+            imagedestroy($imgCropped);
301
+        }
302
+        return false;
303
+    }
304
+
305
+
306
+    public function Desaturate(&$gdimg, $amount, $color='') {
307
+        if ($amount == 0) {
308
+            return true;
309
+        }
310
+        return self::Colorize($gdimg, $amount, (phpthumb_functions::IsHexColor($color) ? $color : 'gray'));
311
+    }
312
+
313
+
314
+    public function DropShadow(&$gdimg, $distance, $width, $hexcolor, $angle, $alpha) {
315
+        if (phpthumb_functions::gd_version() < 2) {
316
+            return false;
317
+        }
318
+        $distance =                 ($distance ? $distance : 10);
319
+        $width    =                 ($width    ? $width    : 10);
320
+        $hexcolor =                 ($hexcolor ? $hexcolor : '000000');
321
+        $angle    =                 ($angle    ? $angle    : 225) % 360;
322
+        $alpha    = max(0, min(100, ($alpha    ? $alpha    : 100)));
323
+
324
+        if ($alpha <= 0) {
325
+            // invisible shadow, nothing to do
326
+            return true;
327
+        }
328
+        if ($distance <= 0) {
329
+            // shadow completely obscured by source image, nothing to do
330
+            return true;
331
+        }
332
+
333
+        //$width_shadow  = cos(deg2rad($angle)) * ($distance + $width);
334
+        //$height_shadow = sin(deg2rad($angle)) * ($distance + $width);
335
+        //$scaling = min(imagesx($gdimg) / (imagesx($gdimg) + abs($width_shadow)), imagesy($gdimg) / (imagesy($gdimg) + abs($height_shadow)));
336
+
337
+        $Offset = array();
338
+        for ($i = 0; $i < $width; $i++) {
339
+            $WidthAlpha[$i] = (abs(($width / 2) - $i) / $width);
340
+            $Offset['x'] = cos(deg2rad($angle)) * ($distance + $i);
341
+            $Offset['y'] = sin(deg2rad($angle)) * ($distance + $i);
342
+        }
343
+
344
+        $tempImageWidth  = imagesx($gdimg)  + abs($Offset['x']);
345
+        $tempImageHeight = imagesy($gdimg) + abs($Offset['y']);
346
+
347
+        if ($gdimg_dropshadow_temp = phpthumb_functions::ImageCreateFunction($tempImageWidth, $tempImageHeight)) {
348
+
349
+            imagealphablending($gdimg_dropshadow_temp, false);
350
+            imagesavealpha($gdimg_dropshadow_temp, true);
351
+            $transparent1 = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_dropshadow_temp, 0, 0, 0, 127);
352
+            imagefill($gdimg_dropshadow_temp, 0, 0, $transparent1);
353
+
354
+            $PixelMap = array();
355
+            for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
356
+                for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
357
+                    $PixelMap[$x][$y] = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
358
+                }
359
+            }
360
+            for ($x = 0; $x < $tempImageWidth; $x++) {
361
+                for ($y = 0; $y < $tempImageHeight; $y++) {
362
+                    //for ($i = 0; $i < $width; $i++) {
363
+                    for ($i = 0; $i < 1; $i++) {
364
+                        if (!isset($PixelMap[$x][$y]['alpha']) || ($PixelMap[$x][$y]['alpha'] > 0)) {
365
+                            if (isset($PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha']) && ($PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha'] < 127)) {
366
+                                $thisColor = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor, false, $PixelMap[$x + $Offset['x']][$y + $Offset['y']]['alpha']);
367
+                                imagesetpixel($gdimg_dropshadow_temp, $x, $y, $thisColor);
368
+                            }
369
+                        }
370
+                    }
371
+                }
372
+            }
373
+
374
+            imagealphablending($gdimg_dropshadow_temp, true);
375
+            for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
376
+                for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
377
+                    if ($PixelMap[$x][$y]['alpha'] < 127) {
378
+                        $thisColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_dropshadow_temp, $PixelMap[$x][$y]['red'], $PixelMap[$x][$y]['green'], $PixelMap[$x][$y]['blue'], $PixelMap[$x][$y]['alpha']);
379
+                        imagesetpixel($gdimg_dropshadow_temp, $x, $y, $thisColor);
380
+                    }
381
+                }
382
+            }
383
+
384
+            imagesavealpha($gdimg, true);
385
+            imagealphablending($gdimg, false);
386
+            //$this->is_alpha = true;
387
+            $transparent2 = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0, 0, 0, 127);
388
+            imagefilledrectangle($gdimg, 0, 0, imagesx($gdimg), imagesy($gdimg), $transparent2);
389
+            imagecopyresampled($gdimg, $gdimg_dropshadow_temp, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg), imagesx($gdimg_dropshadow_temp), imagesy($gdimg_dropshadow_temp));
390
+
391
+            imagedestroy($gdimg_dropshadow_temp);
392
+        }
393
+        return true;
394
+    }
395
+
396
+
397
+    public function EdgeDetect(&$gdimg) {
398
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
399
+            if (imagefilter($gdimg, IMG_FILTER_EDGEDETECT)) {
400
+                return true;
401
+            }
402
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_EDGEDETECT)', __FILE__, __LINE__);
403
+            // fall through and try it the hard way
404
+        }
405
+        // currently not implemented "the hard way"
406
+        $this->DebugMessage('FAILED: phpthumb_filters::EdgeDetect($gdimg) [function not implemented]', __FILE__, __LINE__);
407
+        return false;
408
+    }
409
+
410
+
411
+    public function Ellipse($gdimg) {
412
+        if (phpthumb_functions::gd_version() < 2) {
413
+            return false;
414
+        }
415
+        // generate mask at twice desired resolution and downsample afterwards for easy antialiasing
416
+        if ($gdimg_ellipsemask_double = phpthumb_functions::ImageCreateFunction(imagesx($gdimg) * 2, imagesy($gdimg) * 2)) {
417
+            if ($gdimg_ellipsemask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
418
+
419
+                $color_transparent = imagecolorallocate($gdimg_ellipsemask_double, 255, 255, 255);
420
+                imagefilledellipse($gdimg_ellipsemask_double, imagesx($gdimg), imagesy($gdimg), (imagesx($gdimg) - 1) * 2, (imagesy($gdimg) - 1) * 2, $color_transparent);
421
+                imagecopyresampled($gdimg_ellipsemask, $gdimg_ellipsemask_double, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg), imagesx($gdimg) * 2, imagesy($gdimg) * 2);
422
+
423
+                self::ApplyMask($gdimg_ellipsemask, $gdimg);
424
+                imagedestroy($gdimg_ellipsemask);
425
+                return true;
426
+
427
+            } else {
428
+                $this->DebugMessage('$gdimg_ellipsemask = phpthumb_functions::ImageCreateFunction() failed', __FILE__, __LINE__);
429
+            }
430
+            imagedestroy($gdimg_ellipsemask_double);
431
+        } else {
432
+            $this->DebugMessage('$gdimg_ellipsemask_double = phpthumb_functions::ImageCreateFunction() failed', __FILE__, __LINE__);
433
+        }
434
+        return false;
435
+    }
436
+
437
+
438
+    public function Emboss(&$gdimg) {
439
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
440
+            if (imagefilter($gdimg, IMG_FILTER_EMBOSS)) {
441
+                return true;
442
+            }
443
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_EMBOSS)', __FILE__, __LINE__);
444
+            // fall through and try it the hard way
445
+        }
446
+        // currently not implemented "the hard way"
447
+        $this->DebugMessage('FAILED: phpthumb_filters::Emboss($gdimg) [function not implemented]', __FILE__, __LINE__);
448
+        return false;
449
+    }
450
+
451
+
452
+    public function Flip(&$gdimg, $x=false, $y=false) {
453
+        if (!$x && !$y) {
454
+            return false;
455
+        }
456
+        if ($tempImage = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
457
+            if ($x) {
458
+                imagecopy($tempImage, $gdimg, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg));
459
+                for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
460
+                    imagecopy($gdimg, $tempImage, imagesx($gdimg) - 1 - $x, 0, $x, 0, 1, imagesy($gdimg));
461
+                }
462
+            }
463
+            if ($y) {
464
+                imagecopy($tempImage, $gdimg, 0, 0, 0, 0, imagesx($gdimg), imagesy($gdimg));
465
+                for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
466
+                    imagecopy($gdimg, $tempImage, 0, imagesy($gdimg) - 1 - $y, 0, $y, imagesx($gdimg), 1);
467
+                }
468
+            }
469
+            imagedestroy($tempImage);
470
+        }
471
+        return true;
472
+    }
473
+
474
+
475
+    public function Frame(&$gdimg, $frame_width, $edge_width, $hexcolor_frame, $hexcolor1, $hexcolor2) {
476
+        $frame_width    = ($frame_width    ? $frame_width    : 5);
477
+        $edge_width     = ($edge_width     ? $edge_width     : 1);
478
+        $hexcolor_frame = ($hexcolor_frame ? $hexcolor_frame : 'CCCCCC');
479
+        $hexcolor1      = ($hexcolor1      ? $hexcolor1      : 'FFFFFF');
480
+        $hexcolor2      = ($hexcolor2      ? $hexcolor2      : '000000');
481
+
482
+        $color_frame = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor_frame);
483
+        $color1      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor1);
484
+        $color2      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor2);
485
+        for ($i = 0; $i < $edge_width; $i++) {
486
+            // outer bevel
487
+            imageline($gdimg,                   $i,                   $i,                   $i, imagesy($gdimg) - $i, $color1); // left
488
+            imageline($gdimg,                   $i,                   $i, imagesx($gdimg) - $i,                   $i, $color1); // top
489
+            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, imagesx($gdimg) - $i,                   $i, $color2); // right
490
+            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i,                   $i, imagesy($gdimg) - $i, $color2); // bottom
491
+        }
492
+        for ($i = 0; $i < $frame_width; $i++) {
493
+            // actual frame
494
+            imagerectangle($gdimg, $edge_width + $i, $edge_width + $i, imagesx($gdimg) - $edge_width - $i, imagesy($gdimg) - $edge_width - $i, $color_frame);
495
+        }
496
+        for ($i = 0; $i < $edge_width; $i++) {
497
+            // inner bevel
498
+            imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color2); // left
499
+            imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color2); // top
500
+            imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color1); // right
501
+            imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color1); // bottom
502
+        }
503
+        return true;
504
+    }
505
+
506
+
507
+    public function Gamma(&$gdimg, $amount) {
508
+        if (number_format($amount, 4) == '1.0000') {
509
+            return true;
510
+        }
511
+        return imagegammacorrect($gdimg, 1.0, $amount);
512
+    }
513
+
514
+
515
+    public function Grayscale(&$gdimg) {
516
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
517
+            if (imagefilter($gdimg, IMG_FILTER_GRAYSCALE)) {
518
+                return true;
519
+            }
520
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GRAYSCALE)', __FILE__, __LINE__);
521
+            // fall through and try it the hard way
522
+        }
523
+        return self::Colorize($gdimg, 100, 'gray');
524
+    }
525
+
526
+
527
+    public function HistogramAnalysis(&$gdimg, $calculateGray=false) {
528
+        $ImageSX = imagesx($gdimg);
529
+        $ImageSY = imagesy($gdimg);
530
+        $Analysis = array();
531
+        for ($x = 0; $x < $ImageSX; $x++) {
532
+            for ($y = 0; $y < $ImageSY; $y++) {
533
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
534
+                @$Analysis['red'][$OriginalPixel['red']]++;
535
+                @$Analysis['green'][$OriginalPixel['green']]++;
536
+                @$Analysis['blue'][$OriginalPixel['blue']]++;
537
+                @$Analysis['alpha'][$OriginalPixel['alpha']]++;
538
+                if ($calculateGray) {
539
+                    $GrayPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
540
+                    @$Analysis['gray'][$GrayPixel['red']]++;
541
+                }
542
+            }
543
+        }
544
+        $keys = array('red', 'green', 'blue', 'alpha');
545
+        if ($calculateGray) {
546
+            $keys[] = 'gray';
547
+        }
548
+        foreach ($keys as $dummy => $key) {
549
+            ksort($Analysis[$key]);
550
+        }
551
+        return $Analysis;
552
+    }
553
+
554
+
555
+    public function HistogramStretch(&$gdimg, $band='*', $method=0, $threshold=0.1) {
556
+        // equivalent of "Auto Contrast" in Adobe Photoshop
557
+        // method 0 stretches according to RGB colors. Gives a more conservative stretch.
558
+        // method 1 band stretches according to grayscale which is color-biased (59% green, 30% red, 11% blue). May give a punchier / more aggressive stretch, possibly appearing over-saturated
559
+        $Analysis = self::HistogramAnalysis($gdimg, true);
560
+        $keys = array('r'=>'red', 'g'=>'green', 'b'=>'blue', 'a'=>'alpha', '*'=>(($method == 0) ? 'all' : 'gray'));
561
+        $band = $band[ 0 ];
562
+        if (!isset($keys[$band])) {
563
+            return false;
564
+        }
565
+        $key = $keys[$band];
566
+
567
+        // If the absolute brightest and darkest pixels are used then one random
568
+        // pixel in the image could throw off the whole system. Instead, count up/down
569
+        // from the limit and allow <threshold> (default = 0.1%) of brightest/darkest
570
+        // pixels to be clipped to min/max
571
+        $threshold = (float) $threshold / 100;
572
+        $clip_threshold = imagesx($gdimg) * imagesx($gdimg) * $threshold;
573
+
574
+        $countsum  = 0;
575
+        $range_min = 0;
576
+        for ($i = 0; $i <= 255; $i++) {
577
+            if ($method == 0) {
578
+                $countsum = max(@$Analysis['red'][$i], @$Analysis['green'][$i], @$Analysis['blue'][$i]);
579
+            } else {
580
+                $countsum += @$Analysis[$key][$i];
581
+            }
582
+            if ($countsum >= $clip_threshold) {
583
+                $range_min = $i - 1;
584
+                break;
585
+            }
586
+        }
587
+        $range_min = max($range_min, 0);
588
+
589
+        $countsum  =   0;
590
+        $range_max = 255;
591
+        for ($i = 255; $i >= 0; $i--) {
592
+            if ($method == 0) {
593
+                $countsum = max(@$Analysis['red'][$i], @$Analysis['green'][$i], @$Analysis['blue'][$i]);
594
+            } else {
595
+                $countsum += @$Analysis[$key][$i];
596
+            }
597
+            if ($countsum >= $clip_threshold) {
598
+                $range_max = $i + 1;
599
+                break;
600
+            }
601
+        }
602
+        $range_max = min($range_max, 255);
603
+
604
+        $range_scale = (($range_max == $range_min) ? 1 : (255 / ($range_max - $range_min)));
605
+        if (($range_min == 0) && ($range_max == 255)) {
606
+            // no adjustment necessary - don't waste CPU time!
607
+            return true;
608
+        }
609
+
610
+        $ImageSX = imagesx($gdimg);
611
+        $ImageSY = imagesy($gdimg);
612
+        for ($x = 0; $x < $ImageSX; $x++) {
613
+            for ($y = 0; $y < $ImageSY; $y++) {
614
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
615
+                if ($band == '*') {
616
+                    $new['red']   = min(255, max(0, ($OriginalPixel['red']   - $range_min) * $range_scale));
617
+                    $new['green'] = min(255, max(0, ($OriginalPixel['green'] - $range_min) * $range_scale));
618
+                    $new['blue']  = min(255, max(0, ($OriginalPixel['blue']  - $range_min) * $range_scale));
619
+                    $new['alpha'] = min(255, max(0, ($OriginalPixel['alpha'] - $range_min) * $range_scale));
620
+                } else {
621
+                    $new = $OriginalPixel;
622
+                    $new[$key] = min(255, max(0, ($OriginalPixel[$key] - $range_min) * $range_scale));
623
+                }
624
+                $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $new['red'], $new['green'], $new['blue'], $new['alpha']);
625
+                imagesetpixel($gdimg, $x, $y, $newColor);
626
+            }
627
+        }
628
+
629
+        return true;
630
+    }
631
+
632
+
633
+    public function HistogramOverlay(&$gdimg, $bands='*', $colors='', $width=0.25, $height=0.25, $alignment='BR', $opacity=50, $margin_x=5, $margin_y=null) {
634
+        $margin_y = (null === $margin_y ? $margin_x : $margin_y);
635
+
636
+        $Analysis = self::HistogramAnalysis($gdimg, true);
637
+        $histW = round(($width > 1) ? min($width, imagesx($gdimg)) : imagesx($gdimg) * $width);
638
+        $histH = round(($width > 1) ? min($width, imagesx($gdimg)) : imagesx($gdimg) * $width);
639
+        if ($gdHist = imagecreatetruecolor($histW, $histH)) {
640
+            $color_back = phpthumb_functions::ImageColorAllocateAlphaSafe($gdHist, 0, 0, 0, 127);
641
+            imagefilledrectangle($gdHist, 0, 0, $histW, $histH, $color_back);
642
+            imagealphablending($gdHist, false);
643
+            imagesavealpha($gdHist, true);
644
+
645
+            $HistogramTempWidth  = 256;
646
+            $HistogramTempHeight = 100;
647
+            if ($gdHistTemp = imagecreatetruecolor($HistogramTempWidth, $HistogramTempHeight)) {
648
+                $color_back_temp = phpthumb_functions::ImageColorAllocateAlphaSafe($gdHistTemp, 255, 0, 255, 127);
649
+                imagealphablending($gdHistTemp, false);
650
+                imagesavealpha($gdHistTemp, true);
651
+                imagefilledrectangle($gdHistTemp, 0, 0, imagesx($gdHistTemp), imagesy($gdHistTemp), $color_back_temp);
652
+
653
+                $DefaultColors = array('r'=>'FF0000', 'g'=>'00FF00', 'b'=>'0000FF', 'a'=>'999999', '*'=>'FFFFFF');
654
+                $Colors = explode(';', $colors);
655
+                $BandsToGraph = array_unique(preg_split('##', $bands));
656
+                $keys = array('r'=>'red', 'g'=>'green', 'b'=>'blue', 'a'=>'alpha', '*'=>'gray');
657
+                foreach ($BandsToGraph as $key => $band) {
658
+                    if (!isset($keys[$band])) {
659
+                        continue;
660
+                    }
661
+                    $PeakValue = max($Analysis[$keys[$band]]);
662
+                    $thisColor = phpthumb_functions::ImageHexColorAllocate($gdHistTemp, phpthumb_functions::IsHexColor(@$Colors[$key]) ? $Colors[$key] : $DefaultColors[$band]);
663
+                    for ($x = 0; $x < $HistogramTempWidth; $x++) {
664
+                        imageline($gdHistTemp, $x, $HistogramTempHeight - 1, $x, $HistogramTempHeight - 1 - round(@$Analysis[$keys[$band]][$x] / $PeakValue * $HistogramTempHeight), $thisColor);
665
+                    }
666
+                    imageline($gdHistTemp, 0, $HistogramTempHeight - 1, $HistogramTempWidth - 1, $HistogramTempHeight - 1, $thisColor);
667
+                    imageline($gdHistTemp, 0, $HistogramTempHeight - 2, $HistogramTempWidth - 1, $HistogramTempHeight - 2, $thisColor);
668
+                }
669
+                imagecopyresampled($gdHist, $gdHistTemp, 0, 0, 0, 0, imagesx($gdHist), imagesy($gdHist), imagesx($gdHistTemp), imagesy($gdHistTemp));
670
+                imagedestroy($gdHistTemp);
671
+            } else {
672
+                return false;
673
+            }
674
+
675
+            self::WatermarkOverlay($gdimg, $gdHist, $alignment, $opacity, $margin_x, $margin_y);
676
+            imagedestroy($gdHist);
677
+            return true;
678
+        }
679
+        return false;
680
+    }
681
+
682
+
683
+    public function ImageBorder(&$gdimg, $border_width, $radius_x, $radius_y, $hexcolor_border) {
684
+        $border_width = ($border_width ? $border_width : 1);
685
+        $radius_x     = ($radius_x     ? $radius_x     : 0);
686
+        $radius_y     = ($radius_y     ? $radius_y     : 0);
687
+
688
+        $output_width  = imagesx($gdimg);
689
+        $output_height = imagesy($gdimg);
690
+
691
+        list($new_width, $new_height) = phpthumb_functions::ProportionalResize($output_width, $output_height, $output_width - max($border_width * 2, $radius_x), $output_height - max($border_width * 2, $radius_y));
692
+        $offset_x = ($radius_x ? $output_width  - $new_width  - $radius_x : 0);
693
+
694
+        if ($gd_border_canvas = phpthumb_functions::ImageCreateFunction($output_width, $output_height)) {
695
+
696
+            imagesavealpha($gd_border_canvas, true);
697
+            imagealphablending($gd_border_canvas, false);
698
+            $color_background = phpthumb_functions::ImageColorAllocateAlphaSafe($gd_border_canvas, 255, 255, 255, 127);
699
+            imagefilledrectangle($gd_border_canvas, 0, 0, $output_width, $output_height, $color_background);
700
+
701
+            $color_border = phpthumb_functions::ImageHexColorAllocate($gd_border_canvas, (phpthumb_functions::IsHexColor($hexcolor_border) ? $hexcolor_border : '000000'));
702
+
703
+            for ($i = 0; $i < $border_width; $i++) {
704
+                imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x,                      $i, $output_width - $radius_x - ceil($offset_x / 2),                         $i, $color_border); // top
705
+                imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x, $output_height - 1 - $i, $output_width - $radius_x - ceil($offset_x / 2),    $output_height - 1 - $i, $color_border); // bottom
706
+                imageline($gd_border_canvas,                    floor($offset_x / 2) + $i,               $radius_y,                      floor($offset_x / 2) +  $i, $output_height - $radius_y, $color_border); // left
707
+                imageline($gd_border_canvas, $output_width - 1 - $i - ceil($offset_x / 2),               $radius_y,    $output_width - 1 - $i - ceil($offset_x / 2), $output_height - $radius_y, $color_border); // right
708
+            }
709
+
710
+            if ($radius_x && $radius_y) {
711
+
712
+                // PHP bug: imagearc() with thicknesses > 1 give bad/undesirable/unpredicatable results
713
+                // Solution: Draw multiple 1px arcs side-by-side.
714
+
715
+                // Problem: parallel arcs give strange/ugly antialiasing problems
716
+                // Solution: draw non-parallel arcs, from one side of the line thickness at the start angle
717
+                //   to the opposite edge of the line thickness at the terminating angle
718
+                for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
719
+                    imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x,              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
720
+                    imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2),              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
721
+                    imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2), $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
722
+                    imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x, $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
723
+                }
724
+                if ($border_width > 1) {
725
+                    for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
726
+                        imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                                      $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
727
+                        imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                                      $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
728
+                        imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
729
+                        imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
730
+                    }
731
+                }
732
+
733
+            }
734
+            $this->phpThumbObject->ImageResizeFunction($gd_border_canvas, $gdimg, floor(($output_width - $new_width) / 2), round(($output_height - $new_height) / 2), 0, 0, $new_width, $new_height, $output_width, $output_height);
735
+
736
+            imagedestroy($gdimg);
737
+            $gdimg = phpthumb_functions::ImageCreateFunction($output_width, $output_height);
738
+            imagesavealpha($gdimg, true);
739
+            imagealphablending($gdimg, false);
740
+            $gdimg_color_background = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 255, 255, 255, 127);
741
+            imagefilledrectangle($gdimg, 0, 0, $output_width, $output_height, $gdimg_color_background);
742
+
743
+            imagecopy($gdimg, $gd_border_canvas, 0, 0, 0, 0, $output_width, $output_height);
744
+            imagedestroy($gd_border_canvas);
745
+            return true;
746
+
747
+
748
+        } else {
749
+            $this->DebugMessage('FAILED: $gd_border_canvas = phpthumb_functions::ImageCreateFunction('.$output_width.', '.$output_height.')', __FILE__, __LINE__);
750
+        }
751
+        return false;
752
+    }
753
+
754
+
755
+    public static function ImprovedImageRotate(&$gdimg_source, $rotate_angle=0, $config_background_hexcolor='FFFFFF', $bg=null, &$phpThumbObject) {
756
+        while ($rotate_angle < 0) {
757
+            $rotate_angle += 360;
758
+        }
759
+        $rotate_angle %= 360;
760
+        if ($rotate_angle != 0) {
761
+
762
+            $background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_source, $config_background_hexcolor);
763
+
764
+            if ((phpthumb_functions::gd_version() >= 2) && !$bg && ($rotate_angle % 90)) {
765
+
766
+                //$this->DebugMessage('Using alpha rotate', __FILE__, __LINE__);
767
+                if ($gdimg_rotate_mask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_source), imagesy($gdimg_source))) {
768
+
769
+                    $color_mask = array();
770
+                    for ($i = 0; $i <= 255; $i++) {
771
+                        $color_mask[$i] = imagecolorallocate($gdimg_rotate_mask, $i, $i, $i);
772
+                    }
773
+                    imagefilledrectangle($gdimg_rotate_mask, 0, 0, imagesx($gdimg_rotate_mask), imagesy($gdimg_rotate_mask), $color_mask[255]);
774
+                    $imageX = imagesx($gdimg_source);
775
+                    $imageY = imagesy($gdimg_source);
776
+                    for ($x = 0; $x < $imageX; $x++) {
777
+                        for ($y = 0; $y < $imageY; $y++) {
778
+                            $pixelcolor = phpthumb_functions::GetPixelColor($gdimg_source, $x, $y);
779
+                            imagesetpixel($gdimg_rotate_mask, $x, $y, $color_mask[255 - round($pixelcolor['alpha'] * 255 / 127)]);
780
+                        }
781
+                    }
782
+                    $gdimg_rotate_mask = imagerotate($gdimg_rotate_mask, $rotate_angle, $color_mask[0]);
783
+                    $gdimg_source      = imagerotate($gdimg_source,      $rotate_angle, $background_color);
784
+
785
+                    imagealphablending($gdimg_source, false);
786
+                    imagesavealpha($gdimg_source, true);
787
+                    //$this->is_alpha = true;
788
+                    $phpThumbFilters = new self();
789
+                    //$phpThumbFilters->phpThumbObject = $this;
790
+                    $phpThumbFilters->phpThumbObject = $phpThumbObject;
791
+                    $phpThumbFilters->ApplyMask($gdimg_rotate_mask, $gdimg_source);
792
+
793
+                    imagedestroy($gdimg_rotate_mask);
794
+
795
+                } else {
796
+                    //$this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
797
+                }
798
+
799
+            } else {
800
+
801
+                if (phpthumb_functions::gd_version() < 2) {
802
+                    //$this->DebugMessage('Using non-alpha rotate because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
803
+                } elseif ($bg) {
804
+                    //$this->DebugMessage('Using non-alpha rotate because $this->bg is "'.$bg.'"', __FILE__, __LINE__);
805
+                } elseif ($rotate_angle % 90) {
806
+                    //$this->DebugMessage('Using non-alpha rotate because ($rotate_angle % 90) = "'.($rotate_angle % 90).'"', __FILE__, __LINE__);
807
+                } else {
808
+                    //$this->DebugMessage('Using non-alpha rotate because $this->thumbnailFormat is "'.$this->thumbnailFormat.'"', __FILE__, __LINE__);
809
+                }
810
+
811
+                if (imagecolortransparent($gdimg_source) >= 0) {
812
+                    // imagerotate() forgets all about an image's transparency and sets the transparent color to black
813
+                    // To compensate, flood-fill the transparent color of the source image with the specified background color first
814
+                    // then rotate and the colors should match
815
+
816
+                    if (!function_exists('imageistruecolor') || !imageistruecolor($gdimg_source)) {
817
+                        // convert paletted image to true-color before rotating to prevent nasty aliasing artifacts
818
+
819
+                        //$this->source_width  = imagesx($gdimg_source);
820
+                        //$this->source_height = imagesy($gdimg_source);
821
+                        $gdimg_newsrc = phpthumb_functions::ImageCreateFunction(imagesx($gdimg_source), imagesy($gdimg_source));
822
+                        $background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $config_background_hexcolor);
823
+                        imagefilledrectangle($gdimg_newsrc, 0, 0, imagesx($gdimg_source), imagesy($gdimg_source), phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $config_background_hexcolor));
824
+                        imagecopy($gdimg_newsrc, $gdimg_source, 0, 0, 0, 0, imagesx($gdimg_source), imagesy($gdimg_source));
825
+                        imagedestroy($gdimg_source);
826
+                        unset($gdimg_source);
827
+                        $gdimg_source = $gdimg_newsrc;
828
+                        unset($gdimg_newsrc);
829
+
830
+                    } else {
831
+
832
+                        imagecolorset(
833
+                            $gdimg_source,
834
+                            imagecolortransparent($gdimg_source),
835
+                            hexdec(substr($config_background_hexcolor, 0, 2)),
836
+                            hexdec(substr($config_background_hexcolor, 2, 2)),
837
+                            hexdec(substr($config_background_hexcolor, 4, 2)));
838
+
839
+                        imagecolortransparent($gdimg_source, -1);
840
+
841
+                    }
842
+                }
843
+
844
+                $gdimg_source = imagerotate($gdimg_source, $rotate_angle, $background_color);
845
+
846
+            }
847
+        }
848
+        return true;
849
+    }
850
+
851
+
852
+    public function MeanRemoval(&$gdimg) {
853
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
854
+            if (imagefilter($gdimg, IMG_FILTER_MEAN_REMOVAL)) {
855
+                return true;
856
+            }
857
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_MEAN_REMOVAL)', __FILE__, __LINE__);
858
+            // fall through and try it the hard way
859
+        }
860
+        // currently not implemented "the hard way"
861
+        $this->DebugMessage('FAILED: phpthumb_filters::MeanRemoval($gdimg) [function not implemented]', __FILE__, __LINE__);
862
+        return false;
863
+    }
864
+
865
+
866
+    public function Negative(&$gdimg) {
867
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
868
+            if (imagefilter($gdimg, IMG_FILTER_NEGATE)) {
869
+                return true;
870
+            }
871
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_NEGATE)', __FILE__, __LINE__);
872
+            // fall through and try it the hard way
873
+        }
874
+        $ImageSX = imagesx($gdimg);
875
+        $ImageSY = imagesy($gdimg);
876
+        for ($x = 0; $x < $ImageSX; $x++) {
877
+            for ($y = 0; $y < $ImageSY; $y++) {
878
+                $currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
879
+                $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, (~$currentPixel['red'] & 0xFF), (~$currentPixel['green'] & 0xFF), (~$currentPixel['blue'] & 0xFF), $currentPixel['alpha']);
880
+                imagesetpixel($gdimg, $x, $y, $newColor);
881
+            }
882
+        }
883
+        return true;
884
+    }
885
+
886
+
887
+    public function RoundedImageCorners(&$gdimg, $radius_x, $radius_y) {
888
+        // generate mask at twice desired resolution and downsample afterwards for easy antialiasing
889
+        // mask is generated as a white double-size ellipse on a triple-size black background and copy-paste-resampled
890
+        // onto a correct-size mask image as 4 corners due to errors when the entire mask is resampled at once (gray edges)
891
+        if ($gdimg_cornermask_triple = phpthumb_functions::ImageCreateFunction($radius_x * 6, $radius_y * 6)) {
892
+            if ($gdimg_cornermask = phpthumb_functions::ImageCreateFunction(imagesx($gdimg), imagesy($gdimg))) {
893
+
894
+                $color_transparent = imagecolorallocate($gdimg_cornermask_triple, 255, 255, 255);
895
+                imagefilledellipse($gdimg_cornermask_triple, $radius_x * 3, $radius_y * 3, $radius_x * 4, $radius_y * 4, $color_transparent);
896
+
897
+                imagefilledrectangle($gdimg_cornermask, 0, 0, imagesx($gdimg), imagesy($gdimg), $color_transparent);
898
+
899
+                imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0,                           0,     $radius_x,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
900
+                imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0, imagesy($gdimg) - $radius_y,     $radius_x, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
901
+                imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x, imagesy($gdimg) - $radius_y, $radius_x * 3, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
902
+                imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x,                           0, $radius_x * 3,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
903
+
904
+                self::ApplyMask($gdimg_cornermask, $gdimg);
905
+                imagedestroy($gdimg_cornermask);
906
+                $this->DebugMessage('RoundedImageCorners('.$radius_x.', '.$radius_y.') succeeded', __FILE__, __LINE__);
907
+                return true;
908
+
909
+            } else {
910
+                $this->DebugMessage('FAILED: $gdimg_cornermask = phpthumb_functions::ImageCreateFunction('.imagesx($gdimg).', '.imagesy($gdimg).')', __FILE__, __LINE__);
911
+            }
912
+            imagedestroy($gdimg_cornermask_triple);
913
+
914
+        } else {
915
+            $this->DebugMessage('FAILED: $gdimg_cornermask_triple = phpthumb_functions::ImageCreateFunction('.($radius_x * 6).', '.($radius_y * 6).')', __FILE__, __LINE__);
916
+        }
917
+        return false;
918
+    }
919
+
920
+
921
+    public function Saturation(&$gdimg, $amount, $color='') {
922
+        if ($amount == 0) {
923
+            return true;
924
+        } elseif ($amount > 0) {
925
+            $amount = 0 - $amount;
926
+        } else {
927
+            $amount = abs($amount);
928
+        }
929
+        return self::Desaturate($gdimg, $amount, $color);
930
+    }
931
+
932
+
933
+    public function Sepia(&$gdimg, $amount, $targetColor) {
934
+        $amount      = (is_numeric($amount) ? max(0, min(100, $amount)) : 50);
935
+        $amountPct   = $amount / 100;
936
+        $targetColor = (phpthumb_functions::IsHexColor($targetColor) ? $targetColor : 'A28065');
937
+
938
+        if ($amount == 0) {
939
+            return true;
940
+        }
941
+
942
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
943
+            if (imagefilter($gdimg, IMG_FILTER_GRAYSCALE)) {
944
+
945
+                $r = round($amountPct * hexdec(substr($targetColor, 0, 2)));
946
+                $g = round($amountPct * hexdec(substr($targetColor, 2, 2)));
947
+                $b = round($amountPct * hexdec(substr($targetColor, 4, 2)));
948
+                if (imagefilter($gdimg, IMG_FILTER_COLORIZE, $r, $g, $b)) {
949
+                    return true;
950
+                }
951
+                $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_COLORIZE)', __FILE__, __LINE__);
952
+                // fall through and try it the hard way
953
+
954
+            } else {
955
+
956
+                $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_GRAYSCALE)', __FILE__, __LINE__);
957
+                // fall through and try it the hard way
958
+
959
+            }
960
+        }
961
+
962
+        $TargetPixel['red']   = hexdec(substr($targetColor, 0, 2));
963
+        $TargetPixel['green'] = hexdec(substr($targetColor, 2, 2));
964
+        $TargetPixel['blue']  = hexdec(substr($targetColor, 4, 2));
965
+
966
+        $ImageSX = imagesx($gdimg);
967
+        $ImageSY = imagesy($gdimg);
968
+        for ($x = 0; $x < $ImageSX; $x++) {
969
+            for ($y = 0; $y < $ImageSY; $y++) {
970
+                $OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
971
+                $GrayPixel = phpthumb_functions::GrayscalePixel($OriginalPixel);
972
+
973
+                // http://www.gimpguru.org/Tutorials/SepiaToning/
974
+                // "In the traditional sepia toning process, the tinting occurs most in
975
+                // the mid-tones: the lighter and darker areas appear to be closer to B&W."
976
+                $SepiaAmount = ((128 - abs($GrayPixel['red'] - 128)) / 128) * $amountPct;
977
+
978
+                $NewPixel = array();
979
+                foreach ($TargetPixel as $key => $value) {
980
+                    $NewPixel[$key] = round(max(0, min(255, $GrayPixel[$key] * (1 - $SepiaAmount) + ($TargetPixel[$key] * $SepiaAmount))));
981
+                }
982
+                $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, $NewPixel['red'], $NewPixel['green'], $NewPixel['blue'], $OriginalPixel['alpha']);
983
+                imagesetpixel($gdimg, $x, $y, $newColor);
984
+            }
985
+        }
986
+        return true;
987
+    }
988
+
989
+
990
+    public function Smooth(&$gdimg, $amount=6) {
991
+        $amount = min(25, max(0, $amount));
992
+        if ($amount == 0) {
993
+            return true;
994
+        }
995
+        if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
996
+            if (imagefilter($gdimg, IMG_FILTER_SMOOTH, $amount)) {
997
+                return true;
998
+            }
999
+            $this->DebugMessage('FAILED: imagefilter($gdimg, IMG_FILTER_SMOOTH, '.$amount.')', __FILE__, __LINE__);
1000
+            // fall through and try it the hard way
1001
+        }
1002
+        // currently not implemented "the hard way"
1003
+        $this->DebugMessage('FAILED: phpthumb_filters::Smooth($gdimg, '.$amount.') [function not implemented]', __FILE__, __LINE__);
1004
+        return false;
1005
+    }
1006
+
1007
+
1008
+    public function SourceTransparentColorMask(&$gdimg, $hexcolor, $min_limit=5, $max_limit=10) {
1009
+        $width  = imagesx($gdimg);
1010
+        $height = imagesy($gdimg);
1011
+        if ($gdimg_mask = imagecreatetruecolor($width, $height)) {
1012
+            $R = hexdec(substr($hexcolor, 0, 2));
1013
+            $G = hexdec(substr($hexcolor, 2, 2));
1014
+            $B = hexdec(substr($hexcolor, 4, 2));
1015
+            $targetPixel = array('red'=>$R, 'green'=>$G, 'blue'=>$B);
1016
+            $cutoffRange = $max_limit - $min_limit;
1017
+            for ($x = 0; $x < $width; $x++) {
1018
+                for ($y = 0; $y < $height; $y++) {
1019
+                    $currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1020
+                    $colorDiff = phpthumb_functions::PixelColorDifferencePercent($currentPixel, $targetPixel);
1021
+                    $grayLevel = min($cutoffRange, max(0, -$min_limit + $colorDiff)) * (255 / max(1, $cutoffRange));
1022
+                    $newColor = imagecolorallocate($gdimg_mask, $grayLevel, $grayLevel, $grayLevel);
1023
+                    imagesetpixel($gdimg_mask, $x, $y, $newColor);
1024
+                }
1025
+            }
1026
+            return $gdimg_mask;
1027
+        }
1028
+        return false;
1029
+    }
1030
+
1031
+
1032
+    public function Threshold(&$gdimg, $cutoff) {
1033
+        $width  = imagesx($gdimg);
1034
+        $height = imagesy($gdimg);
1035
+        $cutoff = min(255, max(0, ($cutoff ? $cutoff : 128)));
1036
+        for ($x = 0; $x < $width; $x++) {
1037
+            for ($y = 0; $y < $height; $y++) {
1038
+                $currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1039
+                $grayPixel = phpthumb_functions::GrayscalePixel($currentPixel);
1040
+                if ($grayPixel['red'] < $cutoff) {
1041
+                    $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0x00, 0x00, 0x00, $currentPixel['alpha']);
1042
+                } else {
1043
+                    $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg, 0xFF, 0xFF, 0xFF, $currentPixel['alpha']);
1044
+                }
1045
+                imagesetpixel($gdimg, $x, $y, $newColor);
1046
+            }
1047
+        }
1048
+        return true;
1049
+    }
1050
+
1051
+
1052
+    public function ImageTrueColorToPalette2(&$image, $dither, $ncolors) {
1053
+        // http://www.php.net/manual/en/function.imagetruecolortopalette.php
1054
+        // zmorris at zsculpt dot com (17-Aug-2004 06:58)
1055
+        $width  = imagesx($image);
1056
+        $height = imagesy($image);
1057
+        $image_copy = imagecreatetruecolor($width, $height);
1058
+        //imagecopymerge($image_copy, $image, 0, 0, 0, 0, $width, $height, 100);
1059
+        imagecopy($image_copy, $image, 0, 0, 0, 0, $width, $height);
1060
+        imagetruecolortopalette($image, $dither, $ncolors);
1061
+        imagecolormatch($image_copy, $image);
1062
+        imagedestroy($image_copy);
1063
+        return true;
1064
+    }
1065
+
1066
+    public function ReduceColorDepth(&$gdimg, $colors=256, $dither=true) {
1067
+        $colors = max(min($colors, 256), 2);
1068
+        // imagetruecolortopalette usually makes ugly colors, the replacement is a bit better
1069
+        //imagetruecolortopalette($gdimg, $dither, $colors);
1070
+        self::ImageTrueColorToPalette2($gdimg, $dither, $colors);
1071
+        return true;
1072
+    }
1073
+
1074
+
1075
+    public function WhiteBalance(&$gdimg, $targetColor='') {
1076
+        if (phpthumb_functions::IsHexColor($targetColor)) {
1077
+            $targetPixel = array(
1078
+                'red'   => hexdec(substr($targetColor, 0, 2)),
1079
+                'green' => hexdec(substr($targetColor, 2, 2)),
1080
+                'blue'  => hexdec(substr($targetColor, 4, 2))
1081
+            );
1082
+        } else {
1083
+            $Analysis = self::HistogramAnalysis($gdimg, false);
1084
+            $targetPixel = array(
1085
+                'red'   => max(array_keys($Analysis['red'])),
1086
+                'green' => max(array_keys($Analysis['green'])),
1087
+                'blue'  => max(array_keys($Analysis['blue']))
1088
+            );
1089
+        }
1090
+        $grayValue = phpthumb_functions::GrayscaleValue($targetPixel['red'], $targetPixel['green'], $targetPixel['blue']);
1091
+        $scaleR = $grayValue / $targetPixel['red'];
1092
+        $scaleG = $grayValue / $targetPixel['green'];
1093
+        $scaleB = $grayValue / $targetPixel['blue'];
1094
+
1095
+        for ($x = 0, $xMax = imagesx($gdimg); $x < $xMax; $x++) {
1096
+            for ($y = 0, $yMax = imagesy($gdimg); $y < $yMax; $y++) {
1097
+                $currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1098
+                $newColor = phpthumb_functions::ImageColorAllocateAlphaSafe(
1099
+                    $gdimg,
1100
+                    max(0, min(255, round($currentPixel['red']   * $scaleR))),
1101
+                    max(0, min(255, round($currentPixel['green'] * $scaleG))),
1102
+                    max(0, min(255, round($currentPixel['blue']  * $scaleB))),
1103
+                    $currentPixel['alpha']
1104
+                );
1105
+                imagesetpixel($gdimg, $x, $y, $newColor);
1106
+            }
1107
+        }
1108
+        return true;
1109
+    }
1110
+
1111
+
1112
+    public function WatermarkText(&$gdimg, $text, $size, $alignment, $hex_color='000000', $ttffont='', $opacity=100, $margin=5, $angle=0, $bg_color=false, $bg_opacity=0, $fillextend='', $lineheight=1.0) {
1113
+        // text watermark requested
1114
+        if (!$text) {
1115
+            return false;
1116
+        }
1117
+        imagealphablending($gdimg, true);
1118
+
1119
+        if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)(@[LCR])?$#i', $alignment, $matches)) {
1120
+            $originOffsetX = (int) $matches[ 1];
1121
+            $originOffsetY = (int) $matches[ 2];
1122
+            $alignment = (@$matches[4] ? $matches[4] : 'L');
1123
+            $margin = 0;
1124
+        } else {
1125
+            $originOffsetX = 0;
1126
+            $originOffsetY = 0;
1127
+        }
1128
+        $lineheight = min(100.0, max(0.01, (float) $lineheight));
1129
+
1130
+        $metaTextArray = array(
1131
+            '^Fb' =>       $this->phpThumbObject->getimagesizeinfo['filesize'],
1132
+            '^Fk' => round($this->phpThumbObject->getimagesizeinfo['filesize'] / 1024),
1133
+            '^Fm' => round($this->phpThumbObject->getimagesizeinfo['filesize'] / 1048576),
1134
+            '^X'  => $this->phpThumbObject->getimagesizeinfo[0],
1135
+            '^Y'  => $this->phpThumbObject->getimagesizeinfo[1],
1136
+            '^x'  => imagesx($gdimg),
1137
+            '^y'  => imagesy($gdimg),
1138
+            '^^'  => '^',
1139
+        );
1140
+        $text = strtr($text, $metaTextArray);
1141
+
1142
+        $text = str_replace(array(
1143
+            "\r\n",
1144
+            "\r"
1145
+        ), "\n", $text);
1146
+        $textlines = explode("\n", $text);
1147
+        $this->DebugMessage('Processing '.count($textlines).' lines of text', __FILE__, __LINE__);
1148
+
1149
+        if (@is_readable($ttffont) && is_file($ttffont)) {
1150
+
1151
+            $opacity = 100 - (int) max(min($opacity, 100), 0);
1152
+            $letter_color_text = phpthumb_functions::ImageHexColorAllocate($gdimg, $hex_color, false, $opacity * 1.27);
1153
+
1154
+            $this->DebugMessage('Using TTF font "'.$ttffont.'"', __FILE__, __LINE__);
1155
+
1156
+            $TTFbox = imagettfbbox($size, $angle, $ttffont, $text);
1157
+
1158
+            $min_x = min($TTFbox[0], $TTFbox[2], $TTFbox[4], $TTFbox[6]);
1159
+            $max_x = max($TTFbox[0], $TTFbox[2], $TTFbox[4], $TTFbox[6]);
1160
+            //$text_width = round($max_x - $min_x + ($size * 0.5));
1161
+            $text_width = round($max_x - $min_x);
1162
+
1163
+            $min_y = min($TTFbox[1], $TTFbox[3], $TTFbox[5], $TTFbox[7]);
1164
+            $max_y = max($TTFbox[1], $TTFbox[3], $TTFbox[5], $TTFbox[7]);
1165
+            //$text_height = round($max_y - $min_y + ($size * 0.5));
1166
+            $text_height = round($max_y - $min_y);
1167
+
1168
+            $TTFboxChar = imagettfbbox($size, $angle, $ttffont, 'jH');
1169
+            $char_min_y = min($TTFboxChar[1], $TTFboxChar[3], $TTFboxChar[5], $TTFboxChar[7]);
1170
+            $char_max_y = max($TTFboxChar[1], $TTFboxChar[3], $TTFboxChar[5], $TTFboxChar[7]);
1171
+            $char_height = round($char_max_y - $char_min_y);
1172
+
1173
+            if ($alignment == '*') {
1174
+
1175
+                $text_origin_y = $char_height + $margin;
1176
+                while (($text_origin_y - $text_height) < imagesy($gdimg)) {
1177
+                    $text_origin_x = $margin;
1178
+                    while ($text_origin_x < imagesx($gdimg)) {
1179
+                        imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y, $letter_color_text, $ttffont, $text);
1180
+                        $text_origin_x += ($text_width + $margin);
1181
+                    }
1182
+                    $text_origin_y += ($text_height + $margin) * $lineheight;
1183
+                }
1184
+
1185
+            } else {
1186
+
1187
+                // this block for background color only
1188
+
1189
+                $text_origin_x = 0;
1190
+                $text_origin_y = 0;
1191
+                switch ($alignment) {
1192
+                    case '*':
1193
+                        // handled separately
1194
+                        break;
1195
+
1196
+                    case 'T':
1197
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1198
+                        $text_origin_y = $char_height + $margin + $originOffsetY;
1199
+                        break;
1200
+
1201
+                    case 'B':
1202
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1203
+                        $text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1204
+                        break;
1205
+
1206
+                    case 'L':
1207
+                        $text_origin_x = $margin + $originOffsetX;
1208
+                        $text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1209
+                        break;
1210
+
1211
+                    case 'R':
1212
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1213
+                        $text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1214
+                        break;
1215
+
1216
+                    case 'C':
1217
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width / 2) : round((imagesx($gdimg) - $text_width) / 2));
1218
+                        $text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1219
+                        break;
1220
+
1221
+                    case 'TL':
1222
+                        $text_origin_x = $margin + $originOffsetX;
1223
+                        $text_origin_y = $char_height + $margin + $originOffsetY;
1224
+                        break;
1225
+
1226
+                    case 'TR':
1227
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1228
+                        $text_origin_y = $char_height + $margin + $originOffsetY;
1229
+                        break;
1230
+
1231
+                    case 'BL':
1232
+                        $text_origin_x = $margin + $originOffsetX;
1233
+                        $text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1234
+                        break;
1235
+
1236
+                    case 'BR':
1237
+                    default:
1238
+                        $text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1239
+                        $text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1240
+                        break;
1241
+                }
1242
+
1243
+                if (phpthumb_functions::IsHexColor($bg_color)) {
1244
+                    $text_background_alpha = round(127 * ((100 - min(max(0, $bg_opacity), 100)) / 100));
1245
+                    $text_color_background = phpthumb_functions::ImageHexColorAllocate($gdimg, $bg_color, false, $text_background_alpha);
1246
+                } else {
1247
+                    $text_color_background = phpthumb_functions::ImageHexColorAllocate($gdimg, 'FFFFFF', false, 127);
1248
+                }
1249
+                $x1 = $text_origin_x + $min_x;
1250
+                $y1 = $text_origin_y + $TTFbox[1];
1251
+                $x2 = $text_origin_x + $min_x + $text_width;
1252
+                $y2 = $text_origin_y + $TTFbox[1] - $text_height;
1253
+                $x_TL = false !== stripos($fillextend, "x") ?               0 : min($x1, $x2);
1254
+                $y_TL = false !== stripos($fillextend, "y") ?               0 : min($y1, $y2);
1255
+                $x_BR = false !== stripos($fillextend, "x") ? imagesx($gdimg) : max($x1, $x2);
1256
+                $y_BR = false !== stripos($fillextend, "y") ? imagesy($gdimg) : max($y1, $y2);
1257
+                $this->DebugMessage('WatermarkText() calling imagefilledrectangle($gdimg, '.$x_TL.', '.$y_TL.', '.$x_BR.', '.$y_BR.', $text_color_background)', __FILE__, __LINE__);
1258
+                imagefilledrectangle($gdimg, $x_TL, $y_TL, $x_BR, $y_BR, $text_color_background);
1259
+
1260
+                // end block for background color only
1261
+
1262
+
1263
+                $y_offset = 0;
1264
+                foreach ($textlines as $dummy => $line) {
1265
+
1266
+                    $TTFboxLine = imagettfbbox($size, $angle, $ttffont, $line);
1267
+                    $min_x_line = min($TTFboxLine[0], $TTFboxLine[2], $TTFboxLine[4], $TTFboxLine[6]);
1268
+                    $max_x_line = max($TTFboxLine[0], $TTFboxLine[2], $TTFboxLine[4], $TTFboxLine[6]);
1269
+                    $text_width_line = round($max_x_line - $min_x_line);
1270
+
1271
+                    switch ($alignment) {
1272
+                        // $text_origin_y set above, just re-set $text_origin_x here as needed
1273
+
1274
+                        case 'L':
1275
+                        case 'TL':
1276
+                        case 'BL':
1277
+                            // no change necessary
1278
+                            break;
1279
+
1280
+                        case 'C':
1281
+                        case 'T':
1282
+                        case 'B':
1283
+                            $text_origin_x = ($originOffsetX ? $originOffsetX - round($text_width_line / 2) : round((imagesx($gdimg) - $text_width_line) / 2));
1284
+                            break;
1285
+
1286
+                        case 'R':
1287
+                        case 'TR':
1288
+                        case 'BR':
1289
+                            $text_origin_x = ($originOffsetX ? $originOffsetX - $text_width_line : imagesx($gdimg) - $text_width_line  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1290
+                            break;
1291
+                    }
1292
+
1293
+                    //imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y, $letter_color_text, $ttffont, $text);
1294
+                    $this->DebugMessage('WatermarkText() calling imagettftext($gdimg, '.$size.', '.$angle.', '.$text_origin_x.', '.($text_origin_y + $y_offset).', $letter_color_text, '.$ttffont.', '.$line.')', __FILE__, __LINE__);
1295
+                    imagettftext($gdimg, $size, $angle, $text_origin_x, $text_origin_y + $y_offset, $letter_color_text, $ttffont, $line);
1296
+
1297
+                    $y_offset += $char_height * $lineheight;
1298
+                }
1299
+
1300
+            }
1301
+            return true;
1302
+
1303
+        } else {
1304
+
1305
+            $size = min(5, max(1, $size));
1306
+            $this->DebugMessage('Using built-in font (size='.$size.') for text watermark'.($ttffont ? ' because $ttffont !is_readable('.$ttffont.')' : ''), __FILE__, __LINE__);
1307
+
1308
+            $text_width  = 0;
1309
+            $text_height = 0;
1310
+            foreach ($textlines as $dummy => $line) {
1311
+                $text_width   = max($text_width, imagefontwidth($size) * strlen($line));
1312
+                $text_height += imagefontheight($size);
1313
+            }
1314
+            if ($img_watermark = phpthumb_functions::ImageCreateFunction($text_width, $text_height)) {
1315
+                imagealphablending($img_watermark, false);
1316
+                if (phpthumb_functions::IsHexColor($bg_color)) {
1317
+                    $text_background_alpha = round(127 * ((100 - min(max(0, $bg_opacity), 100)) / 100));
1318
+                    $text_color_background = phpthumb_functions::ImageHexColorAllocate($img_watermark, $bg_color, false, $text_background_alpha);
1319
+                } else {
1320
+                    $text_color_background = phpthumb_functions::ImageHexColorAllocate($img_watermark, 'FFFFFF', false, 127);
1321
+                }
1322
+                $this->DebugMessage('WatermarkText() calling imagefilledrectangle($img_watermark, 0, 0, '.imagesx($img_watermark).', '.imagesy($img_watermark).', $text_color_background)', __FILE__, __LINE__);
1323
+                imagefilledrectangle($img_watermark, 0, 0, imagesx($img_watermark), imagesy($img_watermark), $text_color_background);
1324
+
1325
+                $img_watermark_mask    = false;
1326
+                $mask_color_background = false;
1327
+                $mask_color_watermark  = false;
1328
+                if ($angle && function_exists('imagerotate')) {
1329
+                    // using $img_watermark_mask is pointless if imagerotate function isn't available
1330
+                    if ($img_watermark_mask = phpthumb_functions::ImageCreateFunction($text_width, $text_height)) {
1331
+                        $mask_color_background = imagecolorallocate($img_watermark_mask, 0, 0, 0);
1332
+                        imagealphablending($img_watermark_mask, false);
1333
+                        imagefilledrectangle($img_watermark_mask, 0, 0, imagesx($img_watermark_mask), imagesy($img_watermark_mask), $mask_color_background);
1334
+                        $mask_color_watermark = imagecolorallocate($img_watermark_mask, 255, 255, 255);
1335
+                    }
1336
+                }
1337
+
1338
+                $text_color_watermark = phpthumb_functions::ImageHexColorAllocate($img_watermark, $hex_color);
1339
+                $x_offset = 0;
1340
+                foreach ($textlines as $key => $line) {
1341
+                    switch ($alignment) {
1342
+                        case 'C':
1343
+                            $x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1344
+                            $originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1345
+                            $originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1346
+                            break;
1347
+
1348
+                        case 'T':
1349
+                            $x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1350
+                            $originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1351
+                            $originOffsetY = $margin;
1352
+                            break;
1353
+
1354
+                        case 'B':
1355
+                            $x_offset = round(($text_width - (imagefontwidth($size) * strlen($line))) / 2);
1356
+                            $originOffsetX = (imagesx($gdimg) - imagesx($img_watermark)) / 2;
1357
+                            $originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1358
+                            break;
1359
+
1360
+                        case 'L':
1361
+                            $x_offset = 0;
1362
+                            $originOffsetX = $margin;
1363
+                            $originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1364
+                            break;
1365
+
1366
+                        case 'TL':
1367
+                            $x_offset = 0;
1368
+                            $originOffsetX = $margin;
1369
+                            $originOffsetY = $margin;
1370
+                            break;
1371
+
1372
+                        case 'BL':
1373
+                            $x_offset = 0;
1374
+                            $originOffsetX = $margin;
1375
+                            $originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1376
+                            break;
1377
+
1378
+                        case 'R':
1379
+                            $x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1380
+                            $originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1381
+                            $originOffsetY = (imagesy($gdimg) - imagesy($img_watermark)) / 2;
1382
+                            break;
1383
+
1384
+                        case 'TR':
1385
+                            $x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1386
+                            $originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1387
+                            $originOffsetY = $margin;
1388
+                            break;
1389
+
1390
+                        case 'BR':
1391
+                        default:
1392
+                            if (!empty($originOffsetX) || !empty($originOffsetY)) {
1393
+                                // absolute pixel positioning
1394
+                            } else {
1395
+                                $x_offset = $text_width - (imagefontwidth($size) * strlen($line));
1396
+                                $originOffsetX = imagesx($gdimg) - imagesx($img_watermark) - $margin;
1397
+                                $originOffsetY = imagesy($gdimg) - imagesy($img_watermark) - $margin;
1398
+                            }
1399
+                            break;
1400
+                    }
1401
+                    $this->DebugMessage('WatermarkText() calling imagestring($img_watermark, '.$size.', '.$x_offset.', '.($key * imagefontheight($size)).', '.$line.', $text_color_watermark)', __FILE__, __LINE__);
1402
+                    imagestring($img_watermark, $size, $x_offset, $key * imagefontheight($size), $line, $text_color_watermark);
1403
+                    if ($angle && $img_watermark_mask) {
1404
+                        $this->DebugMessage('WatermarkText() calling imagestring($img_watermark_mask, '.$size.', '.$x_offset.', '.($key * imagefontheight($size) * $lineheight).', '.$text.', $mask_color_watermark)', __FILE__, __LINE__);
1405
+                        imagestring($img_watermark_mask, $size, $x_offset, $key * imagefontheight($size) * $lineheight, $text, $mask_color_watermark);
1406
+                    }
1407
+                }
1408
+                if ($angle && $img_watermark_mask) {
1409
+                    $img_watermark      = imagerotate($img_watermark,      $angle, $text_color_background);
1410
+                    $img_watermark_mask = imagerotate($img_watermark_mask, $angle, $mask_color_background);
1411
+                    self::ApplyMask($img_watermark_mask, $img_watermark);
1412
+                }
1413
+                //phpthumb_filters::WatermarkOverlay($gdimg, $img_watermark, $alignment, $opacity, $margin);
1414
+                $this->DebugMessage('WatermarkText() calling phpthumb_filters::WatermarkOverlay($gdimg, $img_watermark, '.($originOffsetX.'x'.$originOffsetY).', '.$opacity.', 0)', __FILE__, __LINE__);
1415
+                self::WatermarkOverlay($gdimg, $img_watermark, $originOffsetX.'x'.$originOffsetY, $opacity, 0);
1416
+                imagedestroy($img_watermark);
1417
+                return true;
1418
+            }
1419
+
1420
+        }
1421
+        return false;
1422
+    }
1423
+
1424
+
1425
+    public function WatermarkOverlay(&$gdimg_dest, &$img_watermark, $alignment='*', $opacity=50, $margin_x=5, $margin_y=null) {
1426
+
1427
+        if (is_resource($gdimg_dest) && is_resource($img_watermark)) {
1428
+            $img_source_width          = imagesx($gdimg_dest);
1429
+            $img_source_height         = imagesy($gdimg_dest);
1430
+            $watermark_source_width    = imagesx($img_watermark);
1431
+            $watermark_source_height   = imagesy($img_watermark);
1432
+            $watermark_opacity_percent = max(0, min(100, $opacity));
1433
+            $margin_y = (null === $margin_y ? $margin_x : $margin_y);
1434
+            $watermark_margin_x = ((($margin_x > 0) && ($margin_x < 1)) ? round((1 - $margin_x) * $img_source_width)  : $margin_x);
1435
+            $watermark_margin_y = ((($margin_y > 0) && ($margin_y < 1)) ? round((1 - $margin_y) * $img_source_height) : $margin_y);
1436
+            $watermark_destination_x = 0;
1437
+            $watermark_destination_y = 0;
1438
+            if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) {
1439
+                $watermark_destination_x = (int) $matches[ 1];
1440
+                $watermark_destination_y = (int) $matches[ 2];
1441
+            } else {
1442
+                switch ($alignment) {
1443
+                    case '*':
1444
+                        if ($gdimg_tiledwatermark = phpthumb_functions::ImageCreateFunction($img_source_width, $img_source_height)) {
1445
+
1446
+                            imagealphablending($gdimg_tiledwatermark, false);
1447
+                            imagesavealpha($gdimg_tiledwatermark, true);
1448
+                            $text_color_transparent = phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_tiledwatermark, 255, 0, 255, 127);
1449
+                            imagefill($gdimg_tiledwatermark, 0, 0, $text_color_transparent);
1450
+
1451
+                            // set the tiled image transparent color to whatever the untiled image transparency index is
1452
+    //						imagecolortransparent($gdimg_tiledwatermark, imagecolortransparent($img_watermark));
1453
+
1454
+                            // a "cleaner" way of doing it, but can't handle the margin feature :(
1455
+    //						imagesettile($gdimg_tiledwatermark, $img_watermark);
1456
+    //						imagefill($gdimg_tiledwatermark, 0, 0, IMG_COLOR_TILED);
1457
+    //						break;
1458
+
1459
+    //						imagefill($gdimg_tiledwatermark, 0, 0, imagecolortransparent($gdimg_tiledwatermark));
1460
+                            // tile the image as many times as can fit
1461
+                            for ($x = $watermark_margin_x; $x < ($img_source_width + $watermark_source_width); $x += ($watermark_source_width + $watermark_margin_x)) {
1462
+                                for ($y = $watermark_margin_y; $y < ($img_source_height + $watermark_source_height); $y += ($watermark_source_height + $watermark_margin_y)) {
1463
+                                    imagecopy(
1464
+                                        $gdimg_tiledwatermark,
1465
+                                        $img_watermark,
1466
+                                        $x,
1467
+                                        $y,
1468
+                                        0,
1469
+                                        0,
1470
+                                        min($watermark_source_width,  $img_source_width  - $x - $watermark_margin_x),
1471
+                                        min($watermark_source_height, $img_source_height - $y - $watermark_margin_y)
1472
+                                    );
1473
+                                }
1474
+                            }
1475
+
1476
+                            $watermark_source_width  = imagesx($gdimg_tiledwatermark);
1477
+                            $watermark_source_height = imagesy($gdimg_tiledwatermark);
1478
+                            $watermark_destination_x = 0;
1479
+                            $watermark_destination_y = 0;
1480
+
1481
+                            imagedestroy($img_watermark);
1482
+                            $img_watermark = $gdimg_tiledwatermark;
1483
+                        }
1484
+                        break;
1485
+
1486
+                    case 'T':
1487
+                        $watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1488
+                        $watermark_destination_y = $watermark_margin_y;
1489
+                        break;
1490
+
1491
+                    case 'B':
1492
+                        $watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1493
+                        $watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1494
+                        break;
1495
+
1496
+                    case 'L':
1497
+                        $watermark_destination_x = $watermark_margin_x;
1498
+                        $watermark_destination_y = round((($img_source_height / 2) - ($watermark_source_height / 2)) + $watermark_margin_y);
1499
+                        break;
1500
+
1501
+                    case 'R':
1502
+                        $watermark_destination_x = $img_source_width - $watermark_source_width - $watermark_margin_x;
1503
+                        $watermark_destination_y = round((($img_source_height / 2) - ($watermark_source_height / 2)) + $watermark_margin_y);
1504
+                        break;
1505
+
1506
+                    case 'C':
1507
+                        $watermark_destination_x = round(($img_source_width  / 2) - ($watermark_source_width  / 2));
1508
+                        $watermark_destination_y = round(($img_source_height / 2) - ($watermark_source_height / 2));
1509
+                        break;
1510
+
1511
+                    case 'TL':
1512
+                        $watermark_destination_x = $watermark_margin_x;
1513
+                        $watermark_destination_y = $watermark_margin_y;
1514
+                        break;
1515
+
1516
+                    case 'TR':
1517
+                        $watermark_destination_x = $img_source_width - $watermark_source_width - $watermark_margin_x;
1518
+                        $watermark_destination_y = $watermark_margin_y;
1519
+                        break;
1520
+
1521
+                    case 'BL':
1522
+                        $watermark_destination_x = $watermark_margin_x;
1523
+                        $watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1524
+                        break;
1525
+
1526
+                    case 'BR':
1527
+                    default:
1528
+                        $watermark_destination_x = $img_source_width  - $watermark_source_width  - $watermark_margin_x;
1529
+                        $watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1530
+                        break;
1531
+                }
1532
+            }
1533
+            imagealphablending($gdimg_dest, false);
1534
+            imagesavealpha($gdimg_dest, true);
1535
+            imagesavealpha($img_watermark, true);
1536
+            phpthumb_functions::ImageCopyRespectAlpha($gdimg_dest, $img_watermark, $watermark_destination_x, $watermark_destination_y, 0, 0, $watermark_source_width, $watermark_source_height, $watermark_opacity_percent);
1537
+
1538
+            return true;
1539
+        }
1540
+        return false;
1541
+    }
1542 1542
 
1543 1543
 }
Please login to merge, or discard this patch.
Spacing   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
 	public $phpThumbObject = null;
19 19
 
20 20
 
21
-	public function DebugMessage($message, $file='', $line='') {
21
+	public function DebugMessage($message, $file = '', $line = '') {
22 22
 		if (is_object($this->phpThumbObject)) {
23 23
 			return $this->phpThumbObject->DebugMessage($message, $file, $line);
24 24
 		}
@@ -69,14 +69,14 @@  discard block
 block discarded – undo
69 69
 
70 70
 		} else {
71 71
 			// alpha merging requires PHP v4.3.2+
72
-			$this->DebugMessage('Skipping ApplyMask() technique because PHP is v"'. PHP_VERSION .'"', __FILE__, __LINE__);
72
+			$this->DebugMessage('Skipping ApplyMask() technique because PHP is v"'.PHP_VERSION.'"', __FILE__, __LINE__);
73 73
 		}
74 74
 		return true;
75 75
 	}
76 76
 
77 77
 
78 78
     public function Bevel(&$gdimg, $width, $hexcolor1, $hexcolor2) {
79
-        $width     = ($width     ? $width     : 5);
79
+        $width     = ($width ? $width : 5);
80 80
         $hexcolor1 = ($hexcolor1 ? $hexcolor1 : 'FFFFFF');
81 81
         $hexcolor2 = ($hexcolor2 ? $hexcolor2 : '000000');
82 82
 
@@ -86,16 +86,16 @@  discard block
 block discarded – undo
86 86
             $color1 = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor1, false, $alpha);
87 87
             $color2 = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor2, false, $alpha);
88 88
 
89
-            imageline($gdimg,                   $i,                   $i + 1,                   $i, imagesy($gdimg) - $i - 1, $color1); // left
90
-            imageline($gdimg,                   $i,                   $i    , imagesx($gdimg) - $i,                   $i    , $color1); // top
91
-            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i - 1, imagesx($gdimg) - $i,                   $i + 1, $color2); // right
92
-            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i    ,                   $i, imagesy($gdimg) - $i    , $color2); // bottom
89
+            imageline($gdimg, $i, $i + 1, $i, imagesy($gdimg) - $i - 1, $color1); // left
90
+            imageline($gdimg, $i, $i, imagesx($gdimg) - $i, $i, $color1); // top
91
+            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i - 1, imagesx($gdimg) - $i, $i + 1, $color2); // right
92
+            imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, $i, imagesy($gdimg) - $i, $color2); // bottom
93 93
         }
94 94
         return true;
95 95
     }
96 96
 
97 97
 
98
-	public function Blur(&$gdimg, $radius=0.5) {
98
+	public function Blur(&$gdimg, $radius = 0.5) {
99 99
 		// Taken from Torstein Hønsi's phpUnsharpMask (see phpthumb.unsharp.php)
100 100
 
101 101
 		$radius = round(max(0, min($radius, 50)) * 2);
@@ -113,17 +113,17 @@  discard block
 block discarded – undo
113 113
 
114 114
 			// Move copies of the image around one pixel at the time and merge them with weight
115 115
 			// according to the matrix. The same matrix is simply repeated for higher radii.
116
-			for ($i = 0; $i < $radius; $i++)	{
117
-				imagecopy     ($imgBlur, $gdimg, 0, 0, 1, 1, $w - 1, $h - 1);            // up left
118
-				imagecopymerge($imgBlur, $gdimg, 1, 1, 0, 0, $w,     $h,     50.00000);  // down right
119
-				imagecopymerge($imgBlur, $gdimg, 0, 1, 1, 0, $w - 1, $h,     33.33333);  // down left
120
-				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 1, $w,     $h - 1, 25.00000);  // up right
121
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 1, 0, $w - 1, $h,     33.33333);  // left
122
-				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 0, $w,     $h,     25.00000);  // right
123
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 1, $w,     $h - 1, 20.00000);  // up
124
-				imagecopymerge($imgBlur, $gdimg, 0, 1, 0, 0, $w,     $h,     16.666667); // down
125
-				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 0, $w,     $h,     50.000000); // center
126
-				imagecopy     ($gdimg, $imgBlur, 0, 0, 0, 0, $w,     $h);
116
+			for ($i = 0; $i < $radius; $i++) {
117
+				imagecopy($imgBlur, $gdimg, 0, 0, 1, 1, $w - 1, $h - 1); // up left
118
+				imagecopymerge($imgBlur, $gdimg, 1, 1, 0, 0, $w, $h, 50.00000); // down right
119
+				imagecopymerge($imgBlur, $gdimg, 0, 1, 1, 0, $w - 1, $h, 33.33333); // down left
120
+				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 1, $w, $h - 1, 25.00000); // up right
121
+				imagecopymerge($imgBlur, $gdimg, 0, 0, 1, 0, $w - 1, $h, 33.33333); // left
122
+				imagecopymerge($imgBlur, $gdimg, 1, 0, 0, 0, $w, $h, 25.00000); // right
123
+				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 1, $w, $h - 1, 20.00000); // up
124
+				imagecopymerge($imgBlur, $gdimg, 0, 1, 0, 0, $w, $h, 16.666667); // down
125
+				imagecopymerge($imgBlur, $gdimg, 0, 0, 0, 0, $w, $h, 50.000000); // center
126
+				imagecopy($gdimg, $imgBlur, 0, 0, 0, 0, $w, $h);
127 127
 			}
128 128
 			return true;
129 129
 		}
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	}
159 159
 
160 160
 
161
-	public function Brightness(&$gdimg, $amount=0) {
161
+	public function Brightness(&$gdimg, $amount = 0) {
162 162
 		if ($amount == 0) {
163 163
 			return true;
164 164
 		}
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 	}
190 190
 
191 191
 
192
-	public function Contrast(&$gdimg, $amount=0) {
192
+	public function Contrast(&$gdimg, $amount = 0) {
193 193
 		if ($amount == 0) {
194 194
 			return true;
195 195
 		}
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 
228 228
 	public function Colorize(&$gdimg, $amount, $targetColor) {
229
-		$amount      = (is_numeric($amount)                          ? $amount      : 25);
229
+		$amount      = (is_numeric($amount) ? $amount : 25);
230 230
 		$amountPct   = $amount / 100;
231 231
 		$targetColor = (phpthumb_functions::IsHexColor($targetColor) ? $targetColor : 'gray');
232 232
 
@@ -275,20 +275,20 @@  discard block
 block discarded – undo
275 275
 	}
276 276
 
277 277
 
278
-	public function Crop(&$gdimg, $left=0, $right=0, $top=0, $bottom=0) {
278
+	public function Crop(&$gdimg, $left = 0, $right = 0, $top = 0, $bottom = 0) {
279 279
 		if (!$left && !$right && !$top && !$bottom) {
280 280
 			return true;
281 281
 		}
282 282
 		$oldW = imagesx($gdimg);
283 283
 		$oldH = imagesy($gdimg);
284
-		if (($left   > 0) && ($left   < 1)) { $left   = round($left   * $oldW); }
285
-		if (($right  > 0) && ($right  < 1)) { $right  = round($right  * $oldW); }
286
-		if (($top    > 0) && ($top    < 1)) { $top    = round($top    * $oldH); }
284
+		if (($left > 0) && ($left < 1)) { $left   = round($left * $oldW); }
285
+		if (($right > 0) && ($right < 1)) { $right  = round($right * $oldW); }
286
+		if (($top > 0) && ($top < 1)) { $top    = round($top * $oldH); }
287 287
 		if (($bottom > 0) && ($bottom < 1)) { $bottom = round($bottom * $oldH); }
288 288
 		$right  = min($oldW - $left - 1, $right);
289
-		$bottom = min($oldH - $top  - 1, $bottom);
289
+		$bottom = min($oldH - $top - 1, $bottom);
290 290
 		$newW = $oldW - $left - $right;
291
-		$newH = $oldH - $top  - $bottom;
291
+		$newH = $oldH - $top - $bottom;
292 292
 
293 293
 		if ($imgCropped = imagecreatetruecolor($newW, $newH)) {
294 294
 			imagecopy($imgCropped, $gdimg, 0, 0, $left, $top, $newW, $newH);
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 	}
304 304
 
305 305
 
306
-	public function Desaturate(&$gdimg, $amount, $color='') {
306
+	public function Desaturate(&$gdimg, $amount, $color = '') {
307 307
 		if ($amount == 0) {
308 308
 			return true;
309 309
 		}
@@ -315,11 +315,11 @@  discard block
 block discarded – undo
315 315
 		if (phpthumb_functions::gd_version() < 2) {
316 316
 			return false;
317 317
 		}
318
-		$distance =                 ($distance ? $distance : 10);
319
-		$width    =                 ($width    ? $width    : 10);
320
-		$hexcolor =                 ($hexcolor ? $hexcolor : '000000');
321
-		$angle    =                 ($angle    ? $angle    : 225) % 360;
322
-		$alpha    = max(0, min(100, ($alpha    ? $alpha    : 100)));
318
+		$distance = ($distance ? $distance : 10);
319
+		$width    = ($width ? $width : 10);
320
+		$hexcolor = ($hexcolor ? $hexcolor : '000000');
321
+		$angle    = ($angle ? $angle : 225) % 360;
322
+		$alpha    = max(0, min(100, ($alpha ? $alpha : 100)));
323 323
 
324 324
 		if ($alpha <= 0) {
325 325
 			// invisible shadow, nothing to do
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 			$Offset['y'] = sin(deg2rad($angle)) * ($distance + $i);
342 342
 		}
343 343
 
344
-		$tempImageWidth  = imagesx($gdimg)  + abs($Offset['x']);
344
+		$tempImageWidth  = imagesx($gdimg) + abs($Offset['x']);
345 345
 		$tempImageHeight = imagesy($gdimg) + abs($Offset['y']);
346 346
 
347 347
 		if ($gdimg_dropshadow_temp = phpthumb_functions::ImageCreateFunction($tempImageWidth, $tempImageHeight)) {
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
 	}
450 450
 
451 451
 
452
-	public function Flip(&$gdimg, $x=false, $y=false) {
452
+	public function Flip(&$gdimg, $x = false, $y = false) {
453 453
 		if (!$x && !$y) {
454 454
 			return false;
455 455
 		}
@@ -473,21 +473,21 @@  discard block
 block discarded – undo
473 473
 
474 474
 
475 475
 	public function Frame(&$gdimg, $frame_width, $edge_width, $hexcolor_frame, $hexcolor1, $hexcolor2) {
476
-		$frame_width    = ($frame_width    ? $frame_width    : 5);
477
-		$edge_width     = ($edge_width     ? $edge_width     : 1);
476
+		$frame_width    = ($frame_width ? $frame_width : 5);
477
+		$edge_width     = ($edge_width ? $edge_width : 1);
478 478
 		$hexcolor_frame = ($hexcolor_frame ? $hexcolor_frame : 'CCCCCC');
479
-		$hexcolor1      = ($hexcolor1      ? $hexcolor1      : 'FFFFFF');
480
-		$hexcolor2      = ($hexcolor2      ? $hexcolor2      : '000000');
479
+		$hexcolor1      = ($hexcolor1 ? $hexcolor1 : 'FFFFFF');
480
+		$hexcolor2      = ($hexcolor2 ? $hexcolor2 : '000000');
481 481
 
482 482
 		$color_frame = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor_frame);
483 483
 		$color1      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor1);
484 484
 		$color2      = phpthumb_functions::ImageHexColorAllocate($gdimg, $hexcolor2);
485 485
 		for ($i = 0; $i < $edge_width; $i++) {
486 486
 			// outer bevel
487
-			imageline($gdimg,                   $i,                   $i,                   $i, imagesy($gdimg) - $i, $color1); // left
488
-			imageline($gdimg,                   $i,                   $i, imagesx($gdimg) - $i,                   $i, $color1); // top
489
-			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, imagesx($gdimg) - $i,                   $i, $color2); // right
490
-			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i,                   $i, imagesy($gdimg) - $i, $color2); // bottom
487
+			imageline($gdimg, $i, $i, $i, imagesy($gdimg) - $i, $color1); // left
488
+			imageline($gdimg, $i, $i, imagesx($gdimg) - $i, $i, $color1); // top
489
+			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, imagesx($gdimg) - $i, $i, $color2); // right
490
+			imageline($gdimg, imagesx($gdimg) - $i, imagesy($gdimg) - $i, $i, imagesy($gdimg) - $i, $color2); // bottom
491 491
 		}
492 492
 		for ($i = 0; $i < $frame_width; $i++) {
493 493
 			// actual frame
@@ -495,10 +495,10 @@  discard block
 block discarded – undo
495 495
 		}
496 496
 		for ($i = 0; $i < $edge_width; $i++) {
497 497
 			// inner bevel
498
-			imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color2); // left
499
-			imageline($gdimg,                   $frame_width + $edge_width + $i,                   $frame_width + $edge_width + $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color2); // top
500
-			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i, imagesx($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, $color1); // right
501
-			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i,                   $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color1); // bottom
498
+			imageline($gdimg, $frame_width + $edge_width + $i, $frame_width + $edge_width + $i, $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color2); // left
499
+			imageline($gdimg, $frame_width + $edge_width + $i, $frame_width + $edge_width + $i, imagesx($gdimg) - $frame_width - $edge_width - $i, $frame_width + $edge_width + $i, $color2); // top
500
+			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i, imagesx($gdimg) - $frame_width - $edge_width - $i, $frame_width + $edge_width + $i, $color1); // right
501
+			imageline($gdimg, imagesx($gdimg) - $frame_width - $edge_width - $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $frame_width + $edge_width + $i, imagesy($gdimg) - $frame_width - $edge_width - $i, $color1); // bottom
502 502
 		}
503 503
 		return true;
504 504
 	}
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 	}
525 525
 
526 526
 
527
-	public function HistogramAnalysis(&$gdimg, $calculateGray=false) {
527
+	public function HistogramAnalysis(&$gdimg, $calculateGray = false) {
528 528
 		$ImageSX = imagesx($gdimg);
529 529
 		$ImageSY = imagesy($gdimg);
530 530
 		$Analysis = array();
@@ -552,13 +552,13 @@  discard block
 block discarded – undo
552 552
 	}
553 553
 
554 554
 
555
-	public function HistogramStretch(&$gdimg, $band='*', $method=0, $threshold=0.1) {
555
+	public function HistogramStretch(&$gdimg, $band = '*', $method = 0, $threshold = 0.1) {
556 556
 		// equivalent of "Auto Contrast" in Adobe Photoshop
557 557
 		// method 0 stretches according to RGB colors. Gives a more conservative stretch.
558 558
 		// method 1 band stretches according to grayscale which is color-biased (59% green, 30% red, 11% blue). May give a punchier / more aggressive stretch, possibly appearing over-saturated
559 559
 		$Analysis = self::HistogramAnalysis($gdimg, true);
560 560
 		$keys = array('r'=>'red', 'g'=>'green', 'b'=>'blue', 'a'=>'alpha', '*'=>(($method == 0) ? 'all' : 'gray'));
561
-		$band = $band[ 0 ];
561
+		$band = $band[0];
562 562
 		if (!isset($keys[$band])) {
563 563
 			return false;
564 564
 		}
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 		// pixel in the image could throw off the whole system. Instead, count up/down
569 569
 		// from the limit and allow <threshold> (default = 0.1%) of brightest/darkest
570 570
 		// pixels to be clipped to min/max
571
-		$threshold = (float) $threshold / 100;
571
+		$threshold = (float)$threshold / 100;
572 572
 		$clip_threshold = imagesx($gdimg) * imagesx($gdimg) * $threshold;
573 573
 
574 574
 		$countsum  = 0;
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 		}
587 587
 		$range_min = max($range_min, 0);
588 588
 
589
-		$countsum  =   0;
589
+		$countsum  = 0;
590 590
 		$range_max = 255;
591 591
 		for ($i = 255; $i >= 0; $i--) {
592 592
 			if ($method == 0) {
@@ -613,9 +613,9 @@  discard block
 block discarded – undo
613 613
 			for ($y = 0; $y < $ImageSY; $y++) {
614 614
 				$OriginalPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
615 615
 				if ($band == '*') {
616
-					$new['red']   = min(255, max(0, ($OriginalPixel['red']   - $range_min) * $range_scale));
616
+					$new['red']   = min(255, max(0, ($OriginalPixel['red'] - $range_min) * $range_scale));
617 617
 					$new['green'] = min(255, max(0, ($OriginalPixel['green'] - $range_min) * $range_scale));
618
-					$new['blue']  = min(255, max(0, ($OriginalPixel['blue']  - $range_min) * $range_scale));
618
+					$new['blue']  = min(255, max(0, ($OriginalPixel['blue'] - $range_min) * $range_scale));
619 619
 					$new['alpha'] = min(255, max(0, ($OriginalPixel['alpha'] - $range_min) * $range_scale));
620 620
 				} else {
621 621
 					$new = $OriginalPixel;
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	}
631 631
 
632 632
 
633
-	public function HistogramOverlay(&$gdimg, $bands='*', $colors='', $width=0.25, $height=0.25, $alignment='BR', $opacity=50, $margin_x=5, $margin_y=null) {
633
+	public function HistogramOverlay(&$gdimg, $bands = '*', $colors = '', $width = 0.25, $height = 0.25, $alignment = 'BR', $opacity = 50, $margin_x = 5, $margin_y = null) {
634 634
 		$margin_y = (null === $margin_y ? $margin_x : $margin_y);
635 635
 
636 636
 		$Analysis = self::HistogramAnalysis($gdimg, true);
@@ -682,14 +682,14 @@  discard block
 block discarded – undo
682 682
 
683 683
 	public function ImageBorder(&$gdimg, $border_width, $radius_x, $radius_y, $hexcolor_border) {
684 684
 		$border_width = ($border_width ? $border_width : 1);
685
-		$radius_x     = ($radius_x     ? $radius_x     : 0);
686
-		$radius_y     = ($radius_y     ? $radius_y     : 0);
685
+		$radius_x     = ($radius_x ? $radius_x : 0);
686
+		$radius_y     = ($radius_y ? $radius_y : 0);
687 687
 
688 688
 		$output_width  = imagesx($gdimg);
689 689
 		$output_height = imagesy($gdimg);
690 690
 
691 691
 		list($new_width, $new_height) = phpthumb_functions::ProportionalResize($output_width, $output_height, $output_width - max($border_width * 2, $radius_x), $output_height - max($border_width * 2, $radius_y));
692
-		$offset_x = ($radius_x ? $output_width  - $new_width  - $radius_x : 0);
692
+		$offset_x = ($radius_x ? $output_width - $new_width - $radius_x : 0);
693 693
 
694 694
 		if ($gd_border_canvas = phpthumb_functions::ImageCreateFunction($output_width, $output_height)) {
695 695
 
@@ -701,10 +701,10 @@  discard block
 block discarded – undo
701 701
 			$color_border = phpthumb_functions::ImageHexColorAllocate($gd_border_canvas, (phpthumb_functions::IsHexColor($hexcolor_border) ? $hexcolor_border : '000000'));
702 702
 
703 703
 			for ($i = 0; $i < $border_width; $i++) {
704
-				imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x,                      $i, $output_width - $radius_x - ceil($offset_x / 2),                         $i, $color_border); // top
705
-				imageline($gd_border_canvas,             floor($offset_x / 2) + $radius_x, $output_height - 1 - $i, $output_width - $radius_x - ceil($offset_x / 2),    $output_height - 1 - $i, $color_border); // bottom
706
-				imageline($gd_border_canvas,                    floor($offset_x / 2) + $i,               $radius_y,                      floor($offset_x / 2) +  $i, $output_height - $radius_y, $color_border); // left
707
-				imageline($gd_border_canvas, $output_width - 1 - $i - ceil($offset_x / 2),               $radius_y,    $output_width - 1 - $i - ceil($offset_x / 2), $output_height - $radius_y, $color_border); // right
704
+				imageline($gd_border_canvas, floor($offset_x / 2) + $radius_x, $i, $output_width - $radius_x - ceil($offset_x / 2), $i, $color_border); // top
705
+				imageline($gd_border_canvas, floor($offset_x / 2) + $radius_x, $output_height - 1 - $i, $output_width - $radius_x - ceil($offset_x / 2), $output_height - 1 - $i, $color_border); // bottom
706
+				imageline($gd_border_canvas, floor($offset_x / 2) + $i, $radius_y, floor($offset_x / 2) + $i, $output_height - $radius_y, $color_border); // left
707
+				imageline($gd_border_canvas, $output_width - 1 - $i - ceil($offset_x / 2), $radius_y, $output_width - 1 - $i - ceil($offset_x / 2), $output_height - $radius_y, $color_border); // right
708 708
 			}
709 709
 
710 710
 			if ($radius_x && $radius_y) {
@@ -716,17 +716,17 @@  discard block
 block discarded – undo
716 716
 				// Solution: draw non-parallel arcs, from one side of the line thickness at the start angle
717 717
 				//   to the opposite edge of the line thickness at the terminating angle
718 718
 				for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
719
-					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x,              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
720
-					imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2),              $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
721
-					imagearc($gd_border_canvas,                     $output_width - $radius_x - 1 - ceil($offset_x / 2), $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
722
-					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 +                 $radius_x, $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
719
+					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 + $radius_x, $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
720
+					imagearc($gd_border_canvas, $output_width - $radius_x - 1 - ceil($offset_x / 2), $thickness_offset - 1 + $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
721
+					imagearc($gd_border_canvas, $output_width - $radius_x - 1 - ceil($offset_x / 2), $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2, 0, 90, $color_border); // bottom-right
722
+					imagearc($gd_border_canvas, floor($offset_x / 2) + 1 + $radius_x, $output_height - $thickness_offset - $radius_y, $radius_x * 2, $radius_y * 2, 90, 180, $color_border); // bottom-left
723 723
 				}
724 724
 				if ($border_width > 1) {
725 725
 					for ($thickness_offset = 0; $thickness_offset < $border_width; $thickness_offset++) {
726
-						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                                      $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
727
-						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                                      $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
728
-						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2),                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,   0,  90, $color_border); // bottom-right
729
-						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x,                     $output_height - $radius_y, $radius_x * 2, $radius_y * 2,  90, 180, $color_border); // bottom-left
726
+						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x, $radius_y, $radius_x * 2, $radius_y * 2, 180, 270, $color_border); // top-left
727
+						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2), $radius_y, $radius_x * 2, $radius_y * 2, 270, 360, $color_border); // top-right
728
+						imagearc($gd_border_canvas, $output_width - $thickness_offset - $radius_x - 1 - ceil($offset_x / 2), $output_height - $radius_y, $radius_x * 2, $radius_y * 2, 0, 90, $color_border); // bottom-right
729
+						imagearc($gd_border_canvas, floor($offset_x / 2) + $thickness_offset + $radius_x, $output_height - $radius_y, $radius_x * 2, $radius_y * 2, 90, 180, $color_border); // bottom-left
730 730
 					}
731 731
 				}
732 732
 
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 	}
753 753
 
754 754
 
755
-	public static function ImprovedImageRotate(&$gdimg_source, $rotate_angle=0, $config_background_hexcolor='FFFFFF', $bg=null, &$phpThumbObject) {
755
+	public static function ImprovedImageRotate(&$gdimg_source, $rotate_angle = 0, $config_background_hexcolor = 'FFFFFF', $bg = null, &$phpThumbObject) {
756 756
 		while ($rotate_angle < 0) {
757 757
 			$rotate_angle += 360;
758 758
 		}
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 						}
781 781
 					}
782 782
 					$gdimg_rotate_mask = imagerotate($gdimg_rotate_mask, $rotate_angle, $color_mask[0]);
783
-					$gdimg_source      = imagerotate($gdimg_source,      $rotate_angle, $background_color);
783
+					$gdimg_source      = imagerotate($gdimg_source, $rotate_angle, $background_color);
784 784
 
785 785
 					imagealphablending($gdimg_source, false);
786 786
 					imagesavealpha($gdimg_source, true);
@@ -896,10 +896,10 @@  discard block
 block discarded – undo
896 896
 
897 897
 				imagefilledrectangle($gdimg_cornermask, 0, 0, imagesx($gdimg), imagesy($gdimg), $color_transparent);
898 898
 
899
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0,                           0,     $radius_x,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
900
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple,                           0, imagesy($gdimg) - $radius_y,     $radius_x, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
899
+				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, 0, 0, $radius_x, $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
900
+				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, 0, imagesy($gdimg) - $radius_y, $radius_x, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
901 901
 				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x, imagesy($gdimg) - $radius_y, $radius_x * 3, $radius_y * 3, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
902
-				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x,                           0, $radius_x * 3,     $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
902
+				imagecopyresampled($gdimg_cornermask, $gdimg_cornermask_triple, imagesx($gdimg) - $radius_x, 0, $radius_x * 3, $radius_y, $radius_x, $radius_y, $radius_x * 2, $radius_y * 2);
903 903
 
904 904
 				self::ApplyMask($gdimg_cornermask, $gdimg);
905 905
 				imagedestroy($gdimg_cornermask);
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
 	}
919 919
 
920 920
 
921
-	public function Saturation(&$gdimg, $amount, $color='') {
921
+	public function Saturation(&$gdimg, $amount, $color = '') {
922 922
 		if ($amount == 0) {
923 923
 			return true;
924 924
 		} elseif ($amount > 0) {
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 	}
988 988
 
989 989
 
990
-	public function Smooth(&$gdimg, $amount=6) {
990
+	public function Smooth(&$gdimg, $amount = 6) {
991 991
 		$amount = min(25, max(0, $amount));
992 992
 		if ($amount == 0) {
993 993
 			return true;
@@ -1005,7 +1005,7 @@  discard block
 block discarded – undo
1005 1005
 	}
1006 1006
 
1007 1007
 
1008
-	public function SourceTransparentColorMask(&$gdimg, $hexcolor, $min_limit=5, $max_limit=10) {
1008
+	public function SourceTransparentColorMask(&$gdimg, $hexcolor, $min_limit = 5, $max_limit = 10) {
1009 1009
 		$width  = imagesx($gdimg);
1010 1010
 		$height = imagesy($gdimg);
1011 1011
 		if ($gdimg_mask = imagecreatetruecolor($width, $height)) {
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 		return true;
1064 1064
 	}
1065 1065
 
1066
-	public function ReduceColorDepth(&$gdimg, $colors=256, $dither=true) {
1066
+	public function ReduceColorDepth(&$gdimg, $colors = 256, $dither = true) {
1067 1067
 		$colors = max(min($colors, 256), 2);
1068 1068
 		// imagetruecolortopalette usually makes ugly colors, the replacement is a bit better
1069 1069
 		//imagetruecolortopalette($gdimg, $dither, $colors);
@@ -1072,7 +1072,7 @@  discard block
 block discarded – undo
1072 1072
 	}
1073 1073
 
1074 1074
 
1075
-	public function WhiteBalance(&$gdimg, $targetColor='') {
1075
+	public function WhiteBalance(&$gdimg, $targetColor = '') {
1076 1076
 		if (phpthumb_functions::IsHexColor($targetColor)) {
1077 1077
 			$targetPixel = array(
1078 1078
 				'red'   => hexdec(substr($targetColor, 0, 2)),
@@ -1097,9 +1097,9 @@  discard block
 block discarded – undo
1097 1097
 				$currentPixel = phpthumb_functions::GetPixelColor($gdimg, $x, $y);
1098 1098
 				$newColor = phpthumb_functions::ImageColorAllocateAlphaSafe(
1099 1099
 					$gdimg,
1100
-					max(0, min(255, round($currentPixel['red']   * $scaleR))),
1100
+					max(0, min(255, round($currentPixel['red'] * $scaleR))),
1101 1101
 					max(0, min(255, round($currentPixel['green'] * $scaleG))),
1102
-					max(0, min(255, round($currentPixel['blue']  * $scaleB))),
1102
+					max(0, min(255, round($currentPixel['blue'] * $scaleB))),
1103 1103
 					$currentPixel['alpha']
1104 1104
 				);
1105 1105
 				imagesetpixel($gdimg, $x, $y, $newColor);
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 	}
1110 1110
 
1111 1111
 
1112
-	public function WatermarkText(&$gdimg, $text, $size, $alignment, $hex_color='000000', $ttffont='', $opacity=100, $margin=5, $angle=0, $bg_color=false, $bg_opacity=0, $fillextend='', $lineheight=1.0) {
1112
+	public function WatermarkText(&$gdimg, $text, $size, $alignment, $hex_color = '000000', $ttffont = '', $opacity = 100, $margin = 5, $angle = 0, $bg_color = false, $bg_opacity = 0, $fillextend = '', $lineheight = 1.0) {
1113 1113
 		// text watermark requested
1114 1114
 		if (!$text) {
1115 1115
 			return false;
@@ -1117,15 +1117,15 @@  discard block
 block discarded – undo
1117 1117
 		imagealphablending($gdimg, true);
1118 1118
 
1119 1119
 		if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)(@[LCR])?$#i', $alignment, $matches)) {
1120
-			$originOffsetX = (int) $matches[ 1];
1121
-			$originOffsetY = (int) $matches[ 2];
1120
+			$originOffsetX = (int)$matches[1];
1121
+			$originOffsetY = (int)$matches[2];
1122 1122
 			$alignment = (@$matches[4] ? $matches[4] : 'L');
1123 1123
 			$margin = 0;
1124 1124
 		} else {
1125 1125
 			$originOffsetX = 0;
1126 1126
 			$originOffsetY = 0;
1127 1127
 		}
1128
-		$lineheight = min(100.0, max(0.01, (float) $lineheight));
1128
+		$lineheight = min(100.0, max(0.01, (float)$lineheight));
1129 1129
 
1130 1130
 		$metaTextArray = array(
1131 1131
 			'^Fb' =>       $this->phpThumbObject->getimagesizeinfo['filesize'],
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
 
1149 1149
 		if (@is_readable($ttffont) && is_file($ttffont)) {
1150 1150
 
1151
-			$opacity = 100 - (int) max(min($opacity, 100), 0);
1151
+			$opacity = 100 - (int)max(min($opacity, 100), 0);
1152 1152
 			$letter_color_text = phpthumb_functions::ImageHexColorAllocate($gdimg, $hex_color, false, $opacity * 1.27);
1153 1153
 
1154 1154
 			$this->DebugMessage('Using TTF font "'.$ttffont.'"', __FILE__, __LINE__);
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 						break;
1210 1210
 
1211 1211
 					case 'R':
1212
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1212
+						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1213 1213
 						$text_origin_y = ($originOffsetY ? $originOffsetY : round((imagesy($gdimg) - $text_height) / 2) + $char_height);
1214 1214
 						break;
1215 1215
 
@@ -1224,7 +1224,7 @@  discard block
 block discarded – undo
1224 1224
 						break;
1225 1225
 
1226 1226
 					case 'TR':
1227
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1227
+						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1228 1228
 						$text_origin_y = $char_height + $margin + $originOffsetY;
1229 1229
 						break;
1230 1230
 
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
 
1236 1236
 					case 'BR':
1237 1237
 					default:
1238
-						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1238
+						$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width : imagesx($gdimg) - $text_width + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1239 1239
 						$text_origin_y = imagesy($gdimg) + $TTFbox[1] - $margin + $originOffsetY;
1240 1240
 						break;
1241 1241
 				}
@@ -1250,8 +1250,8 @@  discard block
 block discarded – undo
1250 1250
 				$y1 = $text_origin_y + $TTFbox[1];
1251 1251
 				$x2 = $text_origin_x + $min_x + $text_width;
1252 1252
 				$y2 = $text_origin_y + $TTFbox[1] - $text_height;
1253
-				$x_TL = false !== stripos($fillextend, "x") ?               0 : min($x1, $x2);
1254
-				$y_TL = false !== stripos($fillextend, "y") ?               0 : min($y1, $y2);
1253
+				$x_TL = false !== stripos($fillextend, "x") ? 0 : min($x1, $x2);
1254
+				$y_TL = false !== stripos($fillextend, "y") ? 0 : min($y1, $y2);
1255 1255
 				$x_BR = false !== stripos($fillextend, "x") ? imagesx($gdimg) : max($x1, $x2);
1256 1256
 				$y_BR = false !== stripos($fillextend, "y") ? imagesy($gdimg) : max($y1, $y2);
1257 1257
 				$this->DebugMessage('WatermarkText() calling imagefilledrectangle($gdimg, '.$x_TL.', '.$y_TL.', '.$x_BR.', '.$y_BR.', $text_color_background)', __FILE__, __LINE__);
@@ -1286,7 +1286,7 @@  discard block
 block discarded – undo
1286 1286
 						case 'R':
1287 1287
 						case 'TR':
1288 1288
 						case 'BR':
1289
-							$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width_line : imagesx($gdimg) - $text_width_line  + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1289
+							$text_origin_x = ($originOffsetX ? $originOffsetX - $text_width_line : imagesx($gdimg) - $text_width_line + $TTFbox[0] - $min_x + round($size * 0.25) - $margin);
1290 1290
 							break;
1291 1291
 					}
1292 1292
 
@@ -1406,7 +1406,7 @@  discard block
 block discarded – undo
1406 1406
 					}
1407 1407
 				}
1408 1408
 				if ($angle && $img_watermark_mask) {
1409
-					$img_watermark      = imagerotate($img_watermark,      $angle, $text_color_background);
1409
+					$img_watermark      = imagerotate($img_watermark, $angle, $text_color_background);
1410 1410
 					$img_watermark_mask = imagerotate($img_watermark_mask, $angle, $mask_color_background);
1411 1411
 					self::ApplyMask($img_watermark_mask, $img_watermark);
1412 1412
 				}
@@ -1422,7 +1422,7 @@  discard block
 block discarded – undo
1422 1422
 	}
1423 1423
 
1424 1424
 
1425
-	public function WatermarkOverlay(&$gdimg_dest, &$img_watermark, $alignment='*', $opacity=50, $margin_x=5, $margin_y=null) {
1425
+	public function WatermarkOverlay(&$gdimg_dest, &$img_watermark, $alignment = '*', $opacity = 50, $margin_x = 5, $margin_y = null) {
1426 1426
 
1427 1427
 		if (is_resource($gdimg_dest) && is_resource($img_watermark)) {
1428 1428
 			$img_source_width          = imagesx($gdimg_dest);
@@ -1431,13 +1431,13 @@  discard block
 block discarded – undo
1431 1431
 			$watermark_source_height   = imagesy($img_watermark);
1432 1432
 			$watermark_opacity_percent = max(0, min(100, $opacity));
1433 1433
 			$margin_y = (null === $margin_y ? $margin_x : $margin_y);
1434
-			$watermark_margin_x = ((($margin_x > 0) && ($margin_x < 1)) ? round((1 - $margin_x) * $img_source_width)  : $margin_x);
1434
+			$watermark_margin_x = ((($margin_x > 0) && ($margin_x < 1)) ? round((1 - $margin_x) * $img_source_width) : $margin_x);
1435 1435
 			$watermark_margin_y = ((($margin_y > 0) && ($margin_y < 1)) ? round((1 - $margin_y) * $img_source_height) : $margin_y);
1436 1436
 			$watermark_destination_x = 0;
1437 1437
 			$watermark_destination_y = 0;
1438 1438
 			if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) {
1439
-				$watermark_destination_x = (int) $matches[ 1];
1440
-				$watermark_destination_y = (int) $matches[ 2];
1439
+				$watermark_destination_x = (int)$matches[1];
1440
+				$watermark_destination_y = (int)$matches[2];
1441 1441
 			} else {
1442 1442
 				switch ($alignment) {
1443 1443
 					case '*':
@@ -1467,7 +1467,7 @@  discard block
 block discarded – undo
1467 1467
 										$y,
1468 1468
 										0,
1469 1469
 										0,
1470
-										min($watermark_source_width,  $img_source_width  - $x - $watermark_margin_x),
1470
+										min($watermark_source_width, $img_source_width - $x - $watermark_margin_x),
1471 1471
 										min($watermark_source_height, $img_source_height - $y - $watermark_margin_y)
1472 1472
 									);
1473 1473
 								}
@@ -1484,12 +1484,12 @@  discard block
 block discarded – undo
1484 1484
 						break;
1485 1485
 
1486 1486
 					case 'T':
1487
-						$watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1487
+						$watermark_destination_x = round((($img_source_width / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1488 1488
 						$watermark_destination_y = $watermark_margin_y;
1489 1489
 						break;
1490 1490
 
1491 1491
 					case 'B':
1492
-						$watermark_destination_x = round((($img_source_width  / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1492
+						$watermark_destination_x = round((($img_source_width / 2) - ($watermark_source_width / 2)) + $watermark_margin_x);
1493 1493
 						$watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1494 1494
 						break;
1495 1495
 
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 						break;
1505 1505
 
1506 1506
 					case 'C':
1507
-						$watermark_destination_x = round(($img_source_width  / 2) - ($watermark_source_width  / 2));
1507
+						$watermark_destination_x = round(($img_source_width / 2) - ($watermark_source_width / 2));
1508 1508
 						$watermark_destination_y = round(($img_source_height / 2) - ($watermark_source_height / 2));
1509 1509
 						break;
1510 1510
 
@@ -1525,7 +1525,7 @@  discard block
 block discarded – undo
1525 1525
 
1526 1526
 					case 'BR':
1527 1527
 					default:
1528
-						$watermark_destination_x = $img_source_width  - $watermark_source_width  - $watermark_margin_x;
1528
+						$watermark_destination_x = $img_source_width - $watermark_source_width - $watermark_margin_x;
1529 1529
 						$watermark_destination_y = $img_source_height - $watermark_source_height - $watermark_margin_y;
1530 1530
 						break;
1531 1531
 				}
Please login to merge, or discard this patch.
htdocs/modules/system/class/thumbs/phpthumb.functions.php 2 patches
Indentation   +1027 added lines, -1027 removed lines patch added patch discarded remove patch
@@ -11,911 +11,911 @@  discard block
 block discarded – undo
11 11
 
12 12
 class phpthumb_functions {
13 13
 
14
-	public static function user_function_exists($functionname) {
15
-		if (function_exists('get_defined_functions')) {
16
-			static $get_defined_functions = array();
17
-			if (empty($get_defined_functions)) {
18
-				$get_defined_functions = get_defined_functions();
19
-			}
20
-			return in_array(strtolower($functionname), $get_defined_functions['user']);
21
-		}
22
-		return function_exists($functionname);
23
-	}
24
-
25
-
26
-	public static function builtin_function_exists($functionname) {
27
-		if (function_exists('get_defined_functions')) {
28
-			static $get_defined_functions = array();
29
-			if (empty($get_defined_functions)) {
30
-				$get_defined_functions = get_defined_functions();
31
-			}
32
-			return in_array(strtolower($functionname), $get_defined_functions['internal']);
33
-		}
34
-		return function_exists($functionname);
35
-	}
36
-
37
-
38
-	public static function version_compare_replacement_sub($version1, $version2, $operator='') {
39
-		// If you specify the third optional operator argument, you can test for a particular relationship.
40
-		// The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
41
-		// Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
42
-
43
-		// If a part contains special version strings these are handled in the following order:
44
-		// (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
45
-		static $versiontype_lookup = array();
46
-		if (empty($versiontype_lookup)) {
47
-			$versiontype_lookup['dev']   = 10001;
48
-			$versiontype_lookup['a']     = 10002;
49
-			$versiontype_lookup['alpha'] = 10002;
50
-			$versiontype_lookup['b']     = 10003;
51
-			$versiontype_lookup['beta']  = 10003;
52
-			$versiontype_lookup['RC']    = 10004;
53
-			$versiontype_lookup['rc']    = 10004;
54
-			$versiontype_lookup['#']     = 10005;
55
-			$versiontype_lookup['pl']    = 10006;
56
-			$versiontype_lookup['p']     = 10006;
57
-		}
58
-		$version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
59
-		$version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
60
-
61
-		switch ($operator) {
62
-			case '<':
63
-			case 'lt':
64
-				return (int) ($version1 < $version2);
65
-				break;
66
-			case '<=':
67
-			case 'le':
68
-				return (int) ($version1 <= $version2);
69
-				break;
70
-			case '>':
71
-			case 'gt':
72
-				return (int) ($version1 > $version2);
73
-				break;
74
-			case '>=':
75
-			case 'ge':
76
-				return (int) ($version1 >= $version2);
77
-				break;
78
-			case '==':
79
-			case '=':
80
-			case 'eq':
81
-				return (int) ($version1 == $version2);
82
-				break;
83
-			case '!=':
84
-			case '<>':
85
-			case 'ne':
86
-				return (int) ($version1 != $version2);
87
-				break;
88
-		}
89
-		if ($version1 == $version2) {
90
-			return 0;
91
-		} elseif ($version1 < $version2) {
92
-			return -1;
93
-		}
94
-		return 1;
95
-	}
96
-
97
-
98
-	public static function version_compare_replacement($version1, $version2, $operator='') {
99
-		if (function_exists('version_compare')) {
100
-			// built into PHP v4.1.0+
101
-			return version_compare($version1, $version2, $operator);
102
-		}
103
-
104
-		// The function first replaces _, - and + with a dot . in the version strings
105
-		$version1 = strtr($version1, '_-+', '...');
106
-		$version2 = strtr($version2, '_-+', '...');
107
-
108
-		// and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
109
-		// Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
110
-		$version1 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version1);
111
-		$version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version2);
112
-
113
-		$parts1 = explode('.', $version1);
114
-		$parts2 = explode('.', $version1);
115
-		$parts_count = max(count($parts1), count($parts2));
116
-		for ($i = 0; $i < $parts_count; $i++) {
117
-			$comparison = self::version_compare_replacement_sub($version1, $version2, $operator);
118
-			if ($comparison != 0) {
119
-				return $comparison;
120
-			}
121
-		}
122
-		return 0;
123
-	}
124
-
125
-	public static function escapeshellarg_replacement($arg) {
126
-		if (function_exists('escapeshellarg') && !self::FunctionIsDisabled('escapeshellarg')) {
127
-			return escapeshellarg($arg);
128
-		}
129
-		return '\''.str_replace('\'', '\\\'', $arg).'\'';
130
-	}
131
-
132
-	public static function phpinfo_array() {
133
-		static $phpinfo_array = array();
134
-		if (empty($phpinfo_array)) {
135
-			ob_start();
136
-			phpinfo();
137
-			$phpinfo = ob_get_contents();
138
-			ob_end_clean();
139
-			$phpinfo_array = explode("\n", $phpinfo);
140
-		}
141
-		return $phpinfo_array;
142
-	}
143
-
144
-
145
-	public static function exif_info() {
146
-		static $exif_info = array();
147
-		if (empty($exif_info)) {
148
-			// based on code by johnschaefer at gmx dot de
149
-			// from PHP help on gd_info()
150
-			$exif_info = array(
151
-				'EXIF Support'           => '',
152
-				'EXIF Version'           => '',
153
-				'Supported EXIF Version' => '',
154
-				'Supported filetypes'    => ''
155
-			);
156
-			$phpinfo_array = self::phpinfo_array();
157
-			foreach ($phpinfo_array as $line) {
158
-				$line = trim(strip_tags($line));
159
-				foreach ($exif_info as $key => $value) {
160
-					if (strpos($line, $key) === 0) {
161
-						$newvalue = trim(str_replace($key, '', $line));
162
-						$exif_info[$key] = $newvalue;
163
-					}
164
-				}
165
-			}
166
-		}
167
-		return $exif_info;
168
-	}
169
-
170
-
171
-	public static function ImageTypeToMIMEtype($imagetype) {
172
-		if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
173
-			// PHP v4.3.0+
174
-			return image_type_to_mime_type($imagetype);
175
-		}
176
-		static $image_type_to_mime_type = array(
177
-			1  => 'image/gif',                     // IMAGETYPE_GIF
178
-			2  => 'image/jpeg',                    // IMAGETYPE_JPEG
179
-			3  => 'image/png',                     // IMAGETYPE_PNG
180
-			4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
181
-			5  => 'image/psd',                     // IMAGETYPE_PSD
182
-			6  => 'image/bmp',                     // IMAGETYPE_BMP
183
-			7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
184
-			8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
185
-			9  => 'application/octet-stream',      // IMAGETYPE_JPC
186
-			10 => 'image/jp2',                     // IMAGETYPE_JP2
187
-			11 => 'application/octet-stream',      // IMAGETYPE_JPX
188
-			12 => 'application/octet-stream',      // IMAGETYPE_JB2
189
-			13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
190
-			14 => 'image/iff',                     // IMAGETYPE_IFF
191
-			15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
192
-			16 => 'image/xbm',                     // IMAGETYPE_XBM
193
-
194
-			'gif'  => 'image/gif',                 // IMAGETYPE_GIF
195
-			'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
196
-			'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
197
-			'png'  => 'image/png',                 // IMAGETYPE_PNG
198
-			'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
199
-			'ico'  => 'image/x-icon',
200
-		);
201
-
202
-		return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
203
-	}
204
-
205
-
206
-	public static function TranslateWHbyAngle($width, $height, $angle) {
207
-		if (($angle % 180) == 0) {
208
-			return array($width, $height);
209
-		}
210
-		$newwidth  = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
211
-		$newheight = (abs(sin(deg2rad($angle))) * $width)  + (abs(cos(deg2rad($angle))) * $height);
212
-		return array($newwidth, $newheight);
213
-	}
214
-
215
-	public static function HexCharDisplay($string) {
216
-		$len = strlen($string);
217
-		$output = '';
218
-		for ($i = 0; $i < $len; $i++) {
219
-			$output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
220
-		}
221
-		return $output;
222
-	}
223
-
224
-
225
-	public static function IsHexColor($HexColorString) {
226
-		return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
227
-	}
228
-
229
-
230
-	public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
231
-		if (self::version_compare_replacement(PHP_VERSION, '4.3.2', '>=') && ($alpha !== false)) {
232
-			return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int) $alpha);
233
-		} else {
234
-			return imagecolorallocate($gdimg_hexcolorallocate, $R, $G, $B);
235
-		}
236
-	}
237
-
238
-	public static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
239
-		if (!is_resource($gdimg_hexcolorallocate)) {
240
-			die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
241
-		}
242
-		if (self::IsHexColor($HexColorString)) {
243
-			$R = hexdec(substr($HexColorString, 0, 2));
244
-			$G = hexdec(substr($HexColorString, 2, 2));
245
-			$B = hexdec(substr($HexColorString, 4, 2));
246
-			return self::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
247
-		}
248
-		if ($dieOnInvalid) {
249
-			die('Invalid hex color string: "'.$HexColorString.'"');
250
-		}
251
-		return imagecolorallocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
252
-	}
253
-
254
-
255
-	public static function HexColorXOR($hexcolor) {
256
-		return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
257
-	}
258
-
259
-
260
-	public static function GetPixelColor(&$img, $x, $y) {
261
-		if (!is_resource($img)) {
262
-			return false;
263
-		}
264
-		return @imagecolorsforindex($img, @imagecolorat($img, $x, $y));
265
-	}
266
-
267
-
268
-	public static function PixelColorDifferencePercent($currentPixel, $targetPixel) {
269
-		$diff = 0;
270
-		foreach ($targetPixel as $channel => $currentvalue) {
271
-			$diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
272
-		}
273
-		return $diff * 100;
274
-	}
275
-
276
-	public static function GrayscaleValue($r, $g, $b) {
277
-		return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
278
-	}
279
-
280
-
281
-	public static function GrayscalePixel($OriginalPixel) {
282
-		$gray = self::GrayscaleValue($OriginalPixel[ 'red'], $OriginalPixel[ 'green'], $OriginalPixel[ 'blue']);
283
-		return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
284
-	}
285
-
286
-
287
-	public static function GrayscalePixelRGB($rgb) {
288
-		$r = ($rgb >> 16) & 0xFF;
289
-		$g = ($rgb >>  8) & 0xFF;
290
-		$b =  $rgb        & 0xFF;
291
-		return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
292
-	}
293
-
294
-
295
-	public static function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
296
-		$maxwidth  = (null === $maxwidth  ? $width  : $maxwidth);
297
-		$maxheight = (null === $maxheight ? $height : $maxheight);
298
-		$scale_x = 1;
299
-		$scale_y = 1;
300
-		if (($width > $maxwidth) || ($width < $maxwidth)) {
301
-			$scale_x = ($maxwidth / $width);
302
-		}
303
-		if (($height > $maxheight) || ($height < $maxheight)) {
304
-			$scale_y = ($maxheight / $height);
305
-		}
306
-		$scale = min($scale_x, $scale_y);
307
-		if (!$allow_enlarge) {
308
-			$scale = min($scale, 1);
309
-		}
310
-		if (!$allow_reduce) {
311
-			$scale = max($scale, 1);
312
-		}
313
-		return $scale;
314
-	}
315
-
316
-	public static function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
317
-		// ron at korving dot demon dot nl
318
-		// http://www.php.net/imagecopyresampled
319
-
320
-		$scaleX = ($src_w - 1) / $dst_w;
321
-		$scaleY = ($src_h - 1) / $dst_h;
322
-
323
-		$scaleX2 = $scaleX / 2.0;
324
-		$scaleY2 = $scaleY / 2.0;
325
-
326
-		$isTrueColor = imageistruecolor($src_img);
327
-
328
-		for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
329
-			$sY   = $y * $scaleY;
330
-			$siY  = (int) $sY;
331
-			$siY2 = (int) $sY + $scaleY2;
332
-
333
-			for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
334
-				$sX   = $x * $scaleX;
335
-				$siX  = (int) $sX;
336
-				$siX2 = (int) $sX + $scaleX2;
337
-
338
-				if ($isTrueColor) {
339
-
340
-					$c1 = imagecolorat($src_img, $siX, $siY2);
341
-					$c2 = imagecolorat($src_img, $siX, $siY);
342
-					$c3 = imagecolorat($src_img, $siX2, $siY2);
343
-					$c4 = imagecolorat($src_img, $siX2, $siY);
344
-
345
-					$r = (( $c1             +  $c2             +  $c3             +  $c4            ) >> 2) & 0xFF0000;
346
-					$g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
347
-					$b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
348
-
349
-				} else {
350
-
351
-					$c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
352
-					$c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
353
-					$c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
354
-					$c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
355
-
356
-					$r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red'] )  << 14;
357
-					$g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) <<  6;
358
-					$b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >>  2;
359
-
360
-				}
361
-				imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
362
-			}
363
-		}
364
-		return true;
365
-	}
366
-
367
-
368
-	public static function ImageCreateFunction($x_size, $y_size) {
369
-		$ImageCreateFunction = 'imagecreate';
370
-		if (self::gd_version() >= 2.0) {
371
-			$ImageCreateFunction = 'imagecreatetruecolor';
372
-		}
373
-		if (!function_exists($ImageCreateFunction)) {
374
-			return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
375
-		}
376
-		if (($x_size <= 0) || ($y_size <= 0)) {
377
-			return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
378
-		}
379
-		return $ImageCreateFunction(round($x_size), round($y_size));
380
-	}
381
-
382
-
383
-	public static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
384
-		$opacipct = $opacity_pct / 100;
385
-		for ($x = $src_x; $x < $src_w; $x++) {
386
-			for ($y = $src_y; $y < $src_h; $y++) {
387
-				$RealPixel    = self::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
388
-				$OverlayPixel = self::GetPixelColor($src_im, $x, $y);
389
-				$alphapct = $OverlayPixel['alpha'] / 127;
390
-				$overlaypct = (1 - $alphapct) * $opacipct;
391
-
392
-				$newcolor = self::ImageColorAllocateAlphaSafe(
393
-					$dst_im,
394
-					round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
395
-					round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
396
-					round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
397
-					//$RealPixel['alpha']);
398
-					0);
399
-
400
-				imagesetpixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
401
-			}
402
-		}
403
-		return true;
404
-	}
405
-
406
-
407
-	public static function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
408
-		$old_aspect_ratio = $old_width / $old_height;
409
-		if (($new_width === false) && ($new_height === false)) {
410
-			return false;
411
-		} elseif ($new_width === false) {
412
-			$new_width = $new_height * $old_aspect_ratio;
413
-		} elseif ($new_height === false) {
414
-			$new_height = $new_width / $old_aspect_ratio;
415
-		}
416
-		$new_aspect_ratio = $new_width / $new_height;
417
-		if ($new_aspect_ratio == $old_aspect_ratio) {
418
-			// great, done
419
-		} elseif ($new_aspect_ratio < $old_aspect_ratio) {
420
-			// limited by width
421
-			$new_height = $new_width / $old_aspect_ratio;
422
-		} elseif ($new_aspect_ratio > $old_aspect_ratio) {
423
-			// limited by height
424
-			$new_width = $new_height * $old_aspect_ratio;
425
-		}
426
-		return array(
427
-			(int) round($new_width),
428
-			(int) round($new_height)
429
-		);
430
-	}
431
-
432
-
433
-	public static function FunctionIsDisabled($function) {
434
-		static $DisabledFunctions = null;
435
-		if (null === $DisabledFunctions) {
436
-			$disable_functions_local  = explode(',',     strtolower(@ini_get('disable_functions')));
437
-			$disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
438
-			foreach ($disable_functions_local as $key => $value) {
439
-				$DisabledFunctions[trim($value)] = 'local';
440
-			}
441
-			foreach ($disable_functions_global as $key => $value) {
442
-				$DisabledFunctions[trim($value)] = 'global';
443
-			}
444
-			if (@ini_get('safe_mode')) {
445
-				$DisabledFunctions['shell_exec']     = 'local';
446
-				$DisabledFunctions['set_time_limit'] = 'local';
447
-			}
448
-		}
449
-		return isset($DisabledFunctions[strtolower($function)]);
450
-	}
451
-
452
-
453
-	public static function SafeExec($command) {
454
-		static $AllowedExecFunctions = array();
455
-		if (empty($AllowedExecFunctions)) {
456
-			$AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
457
-			foreach ($AllowedExecFunctions as $key => $value) {
458
-				$AllowedExecFunctions[$key] = !self::FunctionIsDisabled($key);
459
-			}
460
-		}
461
-		$command .= ' 2>&1'; // force redirect stderr to stdout
462
-		foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
463
-			if (!$is_allowed) {
464
-				continue;
465
-			}
466
-			$returnvalue = false;
467
-			switch ($execfunction) {
468
-				case 'passthru':
469
-				case 'system':
470
-					ob_start();
471
-					$execfunction($command);
472
-					$returnvalue = ob_get_contents();
473
-					ob_end_clean();
474
-					break;
475
-
476
-				case 'exec':
477
-					$output = array();
478
-					$lastline = $execfunction($command, $output);
479
-					$returnvalue = implode("\n", $output);
480
-					break;
481
-
482
-				case 'shell_exec':
483
-					ob_start();
484
-					$returnvalue = $execfunction($command);
485
-					ob_end_clean();
486
-					break;
487
-			}
488
-			return $returnvalue;
489
-		}
490
-		return false;
491
-	}
492
-
493
-
494
-	public static function ApacheLookupURIarray($filename) {
495
-		// apache_lookup_uri() only works when PHP is installed as an Apache module.
496
-		if (PHP_SAPI == 'apache') {
497
-			//$property_exists_exists = function_exists('property_exists');
498
-			$keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
499
-			if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
500
-				$apacheLookupURIarray = array();
501
-				foreach ($keys as $key) {
502
-					$apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
503
-				}
504
-				return $apacheLookupURIarray;
505
-			}
506
-		}
507
-		return false;
508
-	}
509
-
510
-
511
-	public static function gd_is_bundled() {
512
-		static $isbundled = null;
513
-		if (null === $isbundled) {
514
-			$gd_info = gd_info();
515
-			$isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
516
-		}
517
-		return $isbundled;
518
-	}
519
-
520
-
521
-	public static function gd_version($fullstring=false) {
522
-		static $cache_gd_version = array();
523
-		if (empty($cache_gd_version)) {
524
-			$gd_info = gd_info();
525
-			if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
526
-				$cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
527
-				$cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
528
-			} else {
529
-				$cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
530
-				$cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
531
-			}
532
-		}
533
-		return $cache_gd_version[ (int) $fullstring ];
534
-	}
535
-
536
-
537
-	public static function filesize_remote($remotefile, $timeout=10) {
538
-		$size = false;
539
-		$url = self::ParseURLbetter($remotefile);
540
-		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
541
-			fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
542
-			if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
543
-				stream_set_timeout($fp, $timeout);
544
-			}
545
-			while (!feof($fp)) {
546
-				$headerline = fgets($fp, 4096);
547
-				if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
548
-					$size = (int) $matches[ 1];
549
-					break;
550
-				}
551
-			}
552
-			fclose ($fp);
553
-		}
554
-		return $size;
555
-	}
556
-
557
-
558
-	public static function filedate_remote($remotefile, $timeout=10) {
559
-		$date = false;
560
-		$url = self::ParseURLbetter($remotefile);
561
-		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
562
-			fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
563
-			if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
564
-				stream_set_timeout($fp, $timeout);
565
-			}
566
-			while (!feof($fp)) {
567
-				$headerline = fgets($fp, 4096);
568
-				if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
569
-					$date = strtotime($matches[1]) - date('Z');
570
-					break;
571
-				}
572
-			}
573
-			fclose ($fp);
574
-		}
575
-		return $date;
576
-	}
577
-
578
-
579
-	public static function md5_file_safe($filename) {
580
-		// md5_file() doesn't exist in PHP < 4.2.0
581
-		if (function_exists('md5_file')) {
582
-			return md5_file($filename);
583
-		}
584
-		if ($fp = @fopen($filename, 'rb')) {
585
-			$rawData = '';
586
-			do {
587
-				$buffer = fread($fp, 8192);
588
-				$rawData .= $buffer;
589
-			} while (strlen($buffer) > 0);
590
-			fclose($fp);
591
-			return md5($rawData);
592
-		}
593
-		return false;
594
-	}
595
-
596
-
597
-	public static function nonempty_min() {
598
-		$arg_list = func_get_args();
599
-		$acceptable = array();
600
-		foreach ($arg_list as $arg) {
601
-			if ($arg) {
602
-				$acceptable[] = $arg;
603
-			}
604
-		}
605
-		return min($acceptable);
606
-	}
607
-
608
-
609
-	public static function LittleEndian2String($number, $minbytes=1) {
610
-		$intstring = '';
611
-		while ($number > 0) {
612
-			$intstring .= chr($number & 255);
613
-			$number    >>= 8;
614
-		}
615
-		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
616
-	}
617
-
618
-	public static function OneOfThese() {
619
-		// return the first useful (non-empty/non-zero/non-false) value from those passed
620
-		$arg_list = func_get_args();
621
-		foreach ($arg_list as $key => $value) {
622
-			if ($value) {
623
-				return $value;
624
-			}
625
-		}
626
-		return false;
627
-	}
628
-
629
-	public static function CaseInsensitiveInArray($needle, $haystack) {
630
-		$needle = strtolower($needle);
631
-		foreach ($haystack as $key => $value) {
632
-			if (is_array($value)) {
633
-				// skip?
634
-			} elseif ($needle == strtolower($value)) {
635
-				return true;
636
-			}
637
-		}
638
-		return false;
639
-	}
640
-
641
-	public static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
642
-		if (!function_exists('fsockopen') || self::FunctionIsDisabled('fsockopen')) {
643
-			$errstr = 'fsockopen() unavailable';
644
-			return false;
645
-		}
646
-		//if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
647
-		if ($fp = @fsockopen((($port == 443) ? 'ssl://' : '').$host, $port, $errno, $errstr, $timeout)) { // https://github.com/JamesHeinrich/phpThumb/issues/39
648
-			$out  = 'GET '.$file.' HTTP/1.0'."\r\n";
649
-			$out .= 'Host: '.$host."\r\n";
650
-			$out .= 'Connection: Close'."\r\n\r\n";
651
-			fwrite($fp, $out);
652
-
653
-			$isHeader = true;
654
-			$Data_header = '';
655
-			$Data_body   = '';
656
-			$header_newlocation = '';
657
-			while (!feof($fp)) {
658
-				$line = fgets($fp, 1024);
659
-				if ($isHeader) {
660
-					$Data_header .= $line;
661
-				} else {
662
-					$Data_body .= $line;
663
-				}
664
-				if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
665
-					list( , $errno, $errstr) = $matches;
666
-					$errno = (int) $errno;
667
-				} elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
668
-					$header_newlocation = $matches[1];
669
-				}
670
-				if ($isHeader && ($line == "\r\n")) {
671
-					$isHeader = false;
672
-					if ($successonly) {
673
-						switch ($errno) {
674
-							case 200:
675
-								// great, continue
676
-								break;
677
-
678
-							default:
679
-								$errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
680
-								fclose($fp);
681
-								return false;
682
-								break;
683
-						}
684
-					}
685
-				}
686
-			}
687
-			fclose($fp);
688
-			return $Data_body;
689
-		}
690
-		return null;
691
-	}
692
-
693
-	public static function CleanUpURLencoding($url, $queryseperator='&') {
694
-		if (!preg_match('#^http#i', $url)) {
695
-			return $url;
696
-		}
697
-		$parse_url = self::ParseURLbetter($url);
698
-		$pathelements = explode('/', $parse_url['path']);
699
-		$CleanPathElements = array();
700
-		$TranslationMatrix = array(' '=>'%20');
701
-		foreach ($pathelements as $key => $pathelement) {
702
-			$CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
703
-		}
704
-		foreach ($CleanPathElements as $key => $value) {
705
-			if ($value === '') {
706
-				unset($CleanPathElements[$key]);
707
-			}
708
-		}
709
-
710
-		$queries = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
711
-		$CleanQueries = array();
712
-		foreach ($queries as $key => $query) {
713
-			@list($param, $value) = explode('=', $query);
714
-			$CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
715
-		}
716
-		foreach ($CleanQueries as $key => $value) {
717
-			if ($value === '') {
718
-				unset($CleanQueries[$key]);
719
-			}
720
-		}
721
-
722
-		$cleaned_url  = $parse_url['scheme'].'://';
723
-		$cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
724
-		$cleaned_url .= $parse_url['host'];
725
-		$cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':'.$parse_url['port'] : '');
726
-		$cleaned_url .= '/'.implode('/', $CleanPathElements);
727
-		$cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
728
-		return $cleaned_url;
729
-	}
730
-
731
-	public static function ParseURLbetter($url) {
732
-		$parsedURL = @parse_url($url);
733
-		if (!@$parsedURL['port']) {
734
-			switch (strtolower(@$parsedURL['scheme'])) {
735
-				case 'ftp':
736
-					$parsedURL['port'] = 21;
737
-					break;
738
-				case 'https':
739
-					$parsedURL['port'] = 443;
740
-					break;
741
-				case 'http':
742
-					$parsedURL['port'] = 80;
743
-					break;
744
-			}
745
-		}
746
-		return $parsedURL;
747
-	}
748
-
749
-	public static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
750
-		$error   = '';
751
-		$errstr  = '';
752
-		$rawData = '';
753
-
754
-		$parsed_url = self::ParseURLbetter($url);
755
-		$alreadyLookedAtURLs[trim($url)] = true;
756
-
757
-		while (true) {
758
-			$tryagain = false;
759
-			$rawData = self::URLreadFsock(@$parsed_url[ 'host'], @$parsed_url[ 'path'].'?'.@$parsed_url[ 'query'], $errstr, true, (@$parsed_url[ 'port'] ? @$parsed_url[ 'port'] : 80), $timeout);
760
-			if ($followredirects && preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
761
-				$matches[1] = trim(@$matches[1]);
762
-				if (!@$alreadyLookedAtURLs[$matches[1]]) {
763
-					// loop through and examine new URL
764
-					$error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
765
-
766
-					$tryagain = true;
767
-					$alreadyLookedAtURLs[$matches[1]] = true;
768
-					$parsed_url = self::ParseURLbetter($matches[ 1]);
769
-				}
770
-			}
771
-			if (!$tryagain) {
772
-				break;
773
-			}
774
-		}
775
-
776
-		if ($rawData === false) {
777
-			$error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
778
-			return false;
779
-		} elseif ($rawData === null) {
780
-			// fall through
781
-			$error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
782
-		} else {
783
-			return $rawData;
784
-		}
785
-
786
-		if (function_exists('curl_version') && !self::FunctionIsDisabled('curl_exec')) {
787
-			$ch = curl_init();
788
-			curl_setopt($ch, CURLOPT_URL, $url);
789
-			curl_setopt($ch, CURLOPT_HEADER, false);
790
-			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
791
-			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
792
-			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
793
-			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
794
-			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, (bool) $followredirects);
795
-			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
796
-			$rawData = curl_exec($ch);
797
-			curl_close($ch);
798
-			if (strlen($rawData) > 0) {
799
-				$error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
800
-				return $rawData;
801
-			}
802
-			$error .= 'CURL available but returned no data; ';
803
-		} else {
804
-			$error .= 'CURL unavailable; ';
805
-		}
806
-
807
-		$BrokenURLfopenPHPversions = array('4.4.2');
808
-		if (in_array(PHP_VERSION, $BrokenURLfopenPHPversions)) {
809
-			$error .= 'fopen(URL) broken in PHP v'. PHP_VERSION .'; ';
810
-		} elseif (@ini_get('allow_url_fopen')) {
811
-			$rawData = '';
812
-			$error_fopen = '';
813
-			ob_start();
814
-			if ($fp = fopen($url, 'rb')) {
815
-				do {
816
-					$buffer = fread($fp, 8192);
817
-					$rawData .= $buffer;
818
-				} while (strlen($buffer) > 0);
819
-				fclose($fp);
820
-			} else {
821
-				$error_fopen .= trim(strip_tags(ob_get_contents()));
822
-			}
823
-			ob_end_clean();
824
-			$error .= $error_fopen;
825
-			if (!$error_fopen) {
826
-				$error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
827
-				return $rawData;
828
-			}
829
-			$error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
830
-		} else {
831
-			$error .= '"allow_url_fopen" disabled; ';
832
-		}
833
-
834
-		return false;
835
-	}
836
-
837
-	public static function EnsureDirectoryExists($dirname, $mask = 0755) {
838
-		$directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
839
-		$startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
840
-		$open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
841
-		foreach ($open_basedirs as $key => $open_basedir) {
842
-			if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
843
-				$startoffset = substr_count($open_basedir, DIRECTORY_SEPARATOR) + 1;
844
-				break;
845
-			}
846
-		}
847
-		$i = $startoffset;
848
-		$endoffset = count($directory_elements);
849
-		for ($i = $startoffset; $i <= $endoffset; $i++) {
850
-			$test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
851
-			if (!$test_directory) {
852
-				continue;
853
-			}
854
-			if (!@is_dir($test_directory)) {
855
-				if (@file_exists($test_directory)) {
856
-					// directory name already exists as a file
857
-					return false;
858
-				}
859
-				@mkdir($test_directory, $mask);
860
-				@chmod($test_directory, $mask);
861
-				if (!@is_dir($test_directory) || !@is_writable($test_directory)) {
862
-					return false;
863
-				}
864
-			}
865
-		}
866
-		return true;
867
-	}
868
-
869
-
870
-	public static function GetAllFilesInSubfolders($dirname) {
871
-		$AllFiles = array();
872
-		$dirname = rtrim(realpath($dirname), '/\\');
873
-		if ($dirhandle = @opendir($dirname)) {
874
-			while (($file = readdir($dirhandle)) !== false) {
875
-				$fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
876
-				if (is_file($fullfilename)) {
877
-					$AllFiles[] = $fullfilename;
878
-				} elseif (is_dir($fullfilename)) {
879
-					switch ($file) {
880
-						case '.':
881
-						case '..':
882
-							break;
883
-
884
-						default:
885
-							$AllFiles[] = $fullfilename;
886
-							$subfiles = self::GetAllFilesInSubfolders($fullfilename);
887
-							foreach ($subfiles as $filename) {
888
-								$AllFiles[] = $filename;
889
-							}
890
-							break;
891
-					}
892
-				} else {
893
-					// ignore?
894
-				}
895
-			}
896
-			closedir($dirhandle);
897
-		}
898
-		sort($AllFiles);
899
-		return array_unique($AllFiles);
900
-	}
901
-
902
-
903
-	public static function SanitizeFilename($filename) {
904
-		$filename = preg_replace('/[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]/', '_', $filename);
905
-		if (self::version_compare_replacement(PHP_VERSION, '4.1.0', '>=')) {
906
-			$filename = trim($filename, '.');
907
-		}
908
-		return $filename;
909
-	}
910
-
911
-	public static function PasswordStrength($password) {
912
-		$strength = 0;
913
-		$strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
914
-		$strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
915
-		$strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
916
-		$strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
917
-		return $strength;
918
-	}
14
+    public static function user_function_exists($functionname) {
15
+        if (function_exists('get_defined_functions')) {
16
+            static $get_defined_functions = array();
17
+            if (empty($get_defined_functions)) {
18
+                $get_defined_functions = get_defined_functions();
19
+            }
20
+            return in_array(strtolower($functionname), $get_defined_functions['user']);
21
+        }
22
+        return function_exists($functionname);
23
+    }
24
+
25
+
26
+    public static function builtin_function_exists($functionname) {
27
+        if (function_exists('get_defined_functions')) {
28
+            static $get_defined_functions = array();
29
+            if (empty($get_defined_functions)) {
30
+                $get_defined_functions = get_defined_functions();
31
+            }
32
+            return in_array(strtolower($functionname), $get_defined_functions['internal']);
33
+        }
34
+        return function_exists($functionname);
35
+    }
36
+
37
+
38
+    public static function version_compare_replacement_sub($version1, $version2, $operator='') {
39
+        // If you specify the third optional operator argument, you can test for a particular relationship.
40
+        // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
41
+        // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
42
+
43
+        // If a part contains special version strings these are handled in the following order:
44
+        // (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
45
+        static $versiontype_lookup = array();
46
+        if (empty($versiontype_lookup)) {
47
+            $versiontype_lookup['dev']   = 10001;
48
+            $versiontype_lookup['a']     = 10002;
49
+            $versiontype_lookup['alpha'] = 10002;
50
+            $versiontype_lookup['b']     = 10003;
51
+            $versiontype_lookup['beta']  = 10003;
52
+            $versiontype_lookup['RC']    = 10004;
53
+            $versiontype_lookup['rc']    = 10004;
54
+            $versiontype_lookup['#']     = 10005;
55
+            $versiontype_lookup['pl']    = 10006;
56
+            $versiontype_lookup['p']     = 10006;
57
+        }
58
+        $version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
59
+        $version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
60
+
61
+        switch ($operator) {
62
+            case '<':
63
+            case 'lt':
64
+                return (int) ($version1 < $version2);
65
+                break;
66
+            case '<=':
67
+            case 'le':
68
+                return (int) ($version1 <= $version2);
69
+                break;
70
+            case '>':
71
+            case 'gt':
72
+                return (int) ($version1 > $version2);
73
+                break;
74
+            case '>=':
75
+            case 'ge':
76
+                return (int) ($version1 >= $version2);
77
+                break;
78
+            case '==':
79
+            case '=':
80
+            case 'eq':
81
+                return (int) ($version1 == $version2);
82
+                break;
83
+            case '!=':
84
+            case '<>':
85
+            case 'ne':
86
+                return (int) ($version1 != $version2);
87
+                break;
88
+        }
89
+        if ($version1 == $version2) {
90
+            return 0;
91
+        } elseif ($version1 < $version2) {
92
+            return -1;
93
+        }
94
+        return 1;
95
+    }
96
+
97
+
98
+    public static function version_compare_replacement($version1, $version2, $operator='') {
99
+        if (function_exists('version_compare')) {
100
+            // built into PHP v4.1.0+
101
+            return version_compare($version1, $version2, $operator);
102
+        }
103
+
104
+        // The function first replaces _, - and + with a dot . in the version strings
105
+        $version1 = strtr($version1, '_-+', '...');
106
+        $version2 = strtr($version2, '_-+', '...');
107
+
108
+        // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
109
+        // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
110
+        $version1 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version1);
111
+        $version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version2);
112
+
113
+        $parts1 = explode('.', $version1);
114
+        $parts2 = explode('.', $version1);
115
+        $parts_count = max(count($parts1), count($parts2));
116
+        for ($i = 0; $i < $parts_count; $i++) {
117
+            $comparison = self::version_compare_replacement_sub($version1, $version2, $operator);
118
+            if ($comparison != 0) {
119
+                return $comparison;
120
+            }
121
+        }
122
+        return 0;
123
+    }
124
+
125
+    public static function escapeshellarg_replacement($arg) {
126
+        if (function_exists('escapeshellarg') && !self::FunctionIsDisabled('escapeshellarg')) {
127
+            return escapeshellarg($arg);
128
+        }
129
+        return '\''.str_replace('\'', '\\\'', $arg).'\'';
130
+    }
131
+
132
+    public static function phpinfo_array() {
133
+        static $phpinfo_array = array();
134
+        if (empty($phpinfo_array)) {
135
+            ob_start();
136
+            phpinfo();
137
+            $phpinfo = ob_get_contents();
138
+            ob_end_clean();
139
+            $phpinfo_array = explode("\n", $phpinfo);
140
+        }
141
+        return $phpinfo_array;
142
+    }
143
+
144
+
145
+    public static function exif_info() {
146
+        static $exif_info = array();
147
+        if (empty($exif_info)) {
148
+            // based on code by johnschaefer at gmx dot de
149
+            // from PHP help on gd_info()
150
+            $exif_info = array(
151
+                'EXIF Support'           => '',
152
+                'EXIF Version'           => '',
153
+                'Supported EXIF Version' => '',
154
+                'Supported filetypes'    => ''
155
+            );
156
+            $phpinfo_array = self::phpinfo_array();
157
+            foreach ($phpinfo_array as $line) {
158
+                $line = trim(strip_tags($line));
159
+                foreach ($exif_info as $key => $value) {
160
+                    if (strpos($line, $key) === 0) {
161
+                        $newvalue = trim(str_replace($key, '', $line));
162
+                        $exif_info[$key] = $newvalue;
163
+                    }
164
+                }
165
+            }
166
+        }
167
+        return $exif_info;
168
+    }
169
+
170
+
171
+    public static function ImageTypeToMIMEtype($imagetype) {
172
+        if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
173
+            // PHP v4.3.0+
174
+            return image_type_to_mime_type($imagetype);
175
+        }
176
+        static $image_type_to_mime_type = array(
177
+            1  => 'image/gif',                     // IMAGETYPE_GIF
178
+            2  => 'image/jpeg',                    // IMAGETYPE_JPEG
179
+            3  => 'image/png',                     // IMAGETYPE_PNG
180
+            4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
181
+            5  => 'image/psd',                     // IMAGETYPE_PSD
182
+            6  => 'image/bmp',                     // IMAGETYPE_BMP
183
+            7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
184
+            8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
185
+            9  => 'application/octet-stream',      // IMAGETYPE_JPC
186
+            10 => 'image/jp2',                     // IMAGETYPE_JP2
187
+            11 => 'application/octet-stream',      // IMAGETYPE_JPX
188
+            12 => 'application/octet-stream',      // IMAGETYPE_JB2
189
+            13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
190
+            14 => 'image/iff',                     // IMAGETYPE_IFF
191
+            15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
192
+            16 => 'image/xbm',                     // IMAGETYPE_XBM
193
+
194
+            'gif'  => 'image/gif',                 // IMAGETYPE_GIF
195
+            'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
196
+            'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
197
+            'png'  => 'image/png',                 // IMAGETYPE_PNG
198
+            'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
199
+            'ico'  => 'image/x-icon',
200
+        );
201
+
202
+        return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
203
+    }
204
+
205
+
206
+    public static function TranslateWHbyAngle($width, $height, $angle) {
207
+        if (($angle % 180) == 0) {
208
+            return array($width, $height);
209
+        }
210
+        $newwidth  = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
211
+        $newheight = (abs(sin(deg2rad($angle))) * $width)  + (abs(cos(deg2rad($angle))) * $height);
212
+        return array($newwidth, $newheight);
213
+    }
214
+
215
+    public static function HexCharDisplay($string) {
216
+        $len = strlen($string);
217
+        $output = '';
218
+        for ($i = 0; $i < $len; $i++) {
219
+            $output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
220
+        }
221
+        return $output;
222
+    }
223
+
224
+
225
+    public static function IsHexColor($HexColorString) {
226
+        return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
227
+    }
228
+
229
+
230
+    public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
231
+        if (self::version_compare_replacement(PHP_VERSION, '4.3.2', '>=') && ($alpha !== false)) {
232
+            return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int) $alpha);
233
+        } else {
234
+            return imagecolorallocate($gdimg_hexcolorallocate, $R, $G, $B);
235
+        }
236
+    }
237
+
238
+    public static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
239
+        if (!is_resource($gdimg_hexcolorallocate)) {
240
+            die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
241
+        }
242
+        if (self::IsHexColor($HexColorString)) {
243
+            $R = hexdec(substr($HexColorString, 0, 2));
244
+            $G = hexdec(substr($HexColorString, 2, 2));
245
+            $B = hexdec(substr($HexColorString, 4, 2));
246
+            return self::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
247
+        }
248
+        if ($dieOnInvalid) {
249
+            die('Invalid hex color string: "'.$HexColorString.'"');
250
+        }
251
+        return imagecolorallocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
252
+    }
253
+
254
+
255
+    public static function HexColorXOR($hexcolor) {
256
+        return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
257
+    }
258
+
259
+
260
+    public static function GetPixelColor(&$img, $x, $y) {
261
+        if (!is_resource($img)) {
262
+            return false;
263
+        }
264
+        return @imagecolorsforindex($img, @imagecolorat($img, $x, $y));
265
+    }
266
+
267
+
268
+    public static function PixelColorDifferencePercent($currentPixel, $targetPixel) {
269
+        $diff = 0;
270
+        foreach ($targetPixel as $channel => $currentvalue) {
271
+            $diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
272
+        }
273
+        return $diff * 100;
274
+    }
275
+
276
+    public static function GrayscaleValue($r, $g, $b) {
277
+        return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
278
+    }
279
+
280
+
281
+    public static function GrayscalePixel($OriginalPixel) {
282
+        $gray = self::GrayscaleValue($OriginalPixel[ 'red'], $OriginalPixel[ 'green'], $OriginalPixel[ 'blue']);
283
+        return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
284
+    }
285
+
286
+
287
+    public static function GrayscalePixelRGB($rgb) {
288
+        $r = ($rgb >> 16) & 0xFF;
289
+        $g = ($rgb >>  8) & 0xFF;
290
+        $b =  $rgb        & 0xFF;
291
+        return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
292
+    }
293
+
294
+
295
+    public static function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
296
+        $maxwidth  = (null === $maxwidth  ? $width  : $maxwidth);
297
+        $maxheight = (null === $maxheight ? $height : $maxheight);
298
+        $scale_x = 1;
299
+        $scale_y = 1;
300
+        if (($width > $maxwidth) || ($width < $maxwidth)) {
301
+            $scale_x = ($maxwidth / $width);
302
+        }
303
+        if (($height > $maxheight) || ($height < $maxheight)) {
304
+            $scale_y = ($maxheight / $height);
305
+        }
306
+        $scale = min($scale_x, $scale_y);
307
+        if (!$allow_enlarge) {
308
+            $scale = min($scale, 1);
309
+        }
310
+        if (!$allow_reduce) {
311
+            $scale = max($scale, 1);
312
+        }
313
+        return $scale;
314
+    }
315
+
316
+    public static function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
317
+        // ron at korving dot demon dot nl
318
+        // http://www.php.net/imagecopyresampled
319
+
320
+        $scaleX = ($src_w - 1) / $dst_w;
321
+        $scaleY = ($src_h - 1) / $dst_h;
322
+
323
+        $scaleX2 = $scaleX / 2.0;
324
+        $scaleY2 = $scaleY / 2.0;
325
+
326
+        $isTrueColor = imageistruecolor($src_img);
327
+
328
+        for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
329
+            $sY   = $y * $scaleY;
330
+            $siY  = (int) $sY;
331
+            $siY2 = (int) $sY + $scaleY2;
332
+
333
+            for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
334
+                $sX   = $x * $scaleX;
335
+                $siX  = (int) $sX;
336
+                $siX2 = (int) $sX + $scaleX2;
337
+
338
+                if ($isTrueColor) {
339
+
340
+                    $c1 = imagecolorat($src_img, $siX, $siY2);
341
+                    $c2 = imagecolorat($src_img, $siX, $siY);
342
+                    $c3 = imagecolorat($src_img, $siX2, $siY2);
343
+                    $c4 = imagecolorat($src_img, $siX2, $siY);
344
+
345
+                    $r = (( $c1             +  $c2             +  $c3             +  $c4            ) >> 2) & 0xFF0000;
346
+                    $g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
347
+                    $b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
348
+
349
+                } else {
350
+
351
+                    $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
352
+                    $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
353
+                    $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
354
+                    $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
355
+
356
+                    $r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red'] )  << 14;
357
+                    $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) <<  6;
358
+                    $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >>  2;
359
+
360
+                }
361
+                imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
362
+            }
363
+        }
364
+        return true;
365
+    }
366
+
367
+
368
+    public static function ImageCreateFunction($x_size, $y_size) {
369
+        $ImageCreateFunction = 'imagecreate';
370
+        if (self::gd_version() >= 2.0) {
371
+            $ImageCreateFunction = 'imagecreatetruecolor';
372
+        }
373
+        if (!function_exists($ImageCreateFunction)) {
374
+            return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
375
+        }
376
+        if (($x_size <= 0) || ($y_size <= 0)) {
377
+            return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
378
+        }
379
+        return $ImageCreateFunction(round($x_size), round($y_size));
380
+    }
381
+
382
+
383
+    public static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
384
+        $opacipct = $opacity_pct / 100;
385
+        for ($x = $src_x; $x < $src_w; $x++) {
386
+            for ($y = $src_y; $y < $src_h; $y++) {
387
+                $RealPixel    = self::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
388
+                $OverlayPixel = self::GetPixelColor($src_im, $x, $y);
389
+                $alphapct = $OverlayPixel['alpha'] / 127;
390
+                $overlaypct = (1 - $alphapct) * $opacipct;
391
+
392
+                $newcolor = self::ImageColorAllocateAlphaSafe(
393
+                    $dst_im,
394
+                    round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
395
+                    round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
396
+                    round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
397
+                    //$RealPixel['alpha']);
398
+                    0);
399
+
400
+                imagesetpixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
401
+            }
402
+        }
403
+        return true;
404
+    }
405
+
406
+
407
+    public static function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
408
+        $old_aspect_ratio = $old_width / $old_height;
409
+        if (($new_width === false) && ($new_height === false)) {
410
+            return false;
411
+        } elseif ($new_width === false) {
412
+            $new_width = $new_height * $old_aspect_ratio;
413
+        } elseif ($new_height === false) {
414
+            $new_height = $new_width / $old_aspect_ratio;
415
+        }
416
+        $new_aspect_ratio = $new_width / $new_height;
417
+        if ($new_aspect_ratio == $old_aspect_ratio) {
418
+            // great, done
419
+        } elseif ($new_aspect_ratio < $old_aspect_ratio) {
420
+            // limited by width
421
+            $new_height = $new_width / $old_aspect_ratio;
422
+        } elseif ($new_aspect_ratio > $old_aspect_ratio) {
423
+            // limited by height
424
+            $new_width = $new_height * $old_aspect_ratio;
425
+        }
426
+        return array(
427
+            (int) round($new_width),
428
+            (int) round($new_height)
429
+        );
430
+    }
431
+
432
+
433
+    public static function FunctionIsDisabled($function) {
434
+        static $DisabledFunctions = null;
435
+        if (null === $DisabledFunctions) {
436
+            $disable_functions_local  = explode(',',     strtolower(@ini_get('disable_functions')));
437
+            $disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
438
+            foreach ($disable_functions_local as $key => $value) {
439
+                $DisabledFunctions[trim($value)] = 'local';
440
+            }
441
+            foreach ($disable_functions_global as $key => $value) {
442
+                $DisabledFunctions[trim($value)] = 'global';
443
+            }
444
+            if (@ini_get('safe_mode')) {
445
+                $DisabledFunctions['shell_exec']     = 'local';
446
+                $DisabledFunctions['set_time_limit'] = 'local';
447
+            }
448
+        }
449
+        return isset($DisabledFunctions[strtolower($function)]);
450
+    }
451
+
452
+
453
+    public static function SafeExec($command) {
454
+        static $AllowedExecFunctions = array();
455
+        if (empty($AllowedExecFunctions)) {
456
+            $AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
457
+            foreach ($AllowedExecFunctions as $key => $value) {
458
+                $AllowedExecFunctions[$key] = !self::FunctionIsDisabled($key);
459
+            }
460
+        }
461
+        $command .= ' 2>&1'; // force redirect stderr to stdout
462
+        foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
463
+            if (!$is_allowed) {
464
+                continue;
465
+            }
466
+            $returnvalue = false;
467
+            switch ($execfunction) {
468
+                case 'passthru':
469
+                case 'system':
470
+                    ob_start();
471
+                    $execfunction($command);
472
+                    $returnvalue = ob_get_contents();
473
+                    ob_end_clean();
474
+                    break;
475
+
476
+                case 'exec':
477
+                    $output = array();
478
+                    $lastline = $execfunction($command, $output);
479
+                    $returnvalue = implode("\n", $output);
480
+                    break;
481
+
482
+                case 'shell_exec':
483
+                    ob_start();
484
+                    $returnvalue = $execfunction($command);
485
+                    ob_end_clean();
486
+                    break;
487
+            }
488
+            return $returnvalue;
489
+        }
490
+        return false;
491
+    }
492
+
493
+
494
+    public static function ApacheLookupURIarray($filename) {
495
+        // apache_lookup_uri() only works when PHP is installed as an Apache module.
496
+        if (PHP_SAPI == 'apache') {
497
+            //$property_exists_exists = function_exists('property_exists');
498
+            $keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
499
+            if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
500
+                $apacheLookupURIarray = array();
501
+                foreach ($keys as $key) {
502
+                    $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
503
+                }
504
+                return $apacheLookupURIarray;
505
+            }
506
+        }
507
+        return false;
508
+    }
509
+
510
+
511
+    public static function gd_is_bundled() {
512
+        static $isbundled = null;
513
+        if (null === $isbundled) {
514
+            $gd_info = gd_info();
515
+            $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
516
+        }
517
+        return $isbundled;
518
+    }
519
+
520
+
521
+    public static function gd_version($fullstring=false) {
522
+        static $cache_gd_version = array();
523
+        if (empty($cache_gd_version)) {
524
+            $gd_info = gd_info();
525
+            if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
526
+                $cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
527
+                $cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
528
+            } else {
529
+                $cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
530
+                $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
531
+            }
532
+        }
533
+        return $cache_gd_version[ (int) $fullstring ];
534
+    }
535
+
536
+
537
+    public static function filesize_remote($remotefile, $timeout=10) {
538
+        $size = false;
539
+        $url = self::ParseURLbetter($remotefile);
540
+        if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
541
+            fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
542
+            if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
543
+                stream_set_timeout($fp, $timeout);
544
+            }
545
+            while (!feof($fp)) {
546
+                $headerline = fgets($fp, 4096);
547
+                if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
548
+                    $size = (int) $matches[ 1];
549
+                    break;
550
+                }
551
+            }
552
+            fclose ($fp);
553
+        }
554
+        return $size;
555
+    }
556
+
557
+
558
+    public static function filedate_remote($remotefile, $timeout=10) {
559
+        $date = false;
560
+        $url = self::ParseURLbetter($remotefile);
561
+        if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
562
+            fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
563
+            if (self::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
564
+                stream_set_timeout($fp, $timeout);
565
+            }
566
+            while (!feof($fp)) {
567
+                $headerline = fgets($fp, 4096);
568
+                if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
569
+                    $date = strtotime($matches[1]) - date('Z');
570
+                    break;
571
+                }
572
+            }
573
+            fclose ($fp);
574
+        }
575
+        return $date;
576
+    }
577
+
578
+
579
+    public static function md5_file_safe($filename) {
580
+        // md5_file() doesn't exist in PHP < 4.2.0
581
+        if (function_exists('md5_file')) {
582
+            return md5_file($filename);
583
+        }
584
+        if ($fp = @fopen($filename, 'rb')) {
585
+            $rawData = '';
586
+            do {
587
+                $buffer = fread($fp, 8192);
588
+                $rawData .= $buffer;
589
+            } while (strlen($buffer) > 0);
590
+            fclose($fp);
591
+            return md5($rawData);
592
+        }
593
+        return false;
594
+    }
595
+
596
+
597
+    public static function nonempty_min() {
598
+        $arg_list = func_get_args();
599
+        $acceptable = array();
600
+        foreach ($arg_list as $arg) {
601
+            if ($arg) {
602
+                $acceptable[] = $arg;
603
+            }
604
+        }
605
+        return min($acceptable);
606
+    }
607
+
608
+
609
+    public static function LittleEndian2String($number, $minbytes=1) {
610
+        $intstring = '';
611
+        while ($number > 0) {
612
+            $intstring .= chr($number & 255);
613
+            $number    >>= 8;
614
+        }
615
+        return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
616
+    }
617
+
618
+    public static function OneOfThese() {
619
+        // return the first useful (non-empty/non-zero/non-false) value from those passed
620
+        $arg_list = func_get_args();
621
+        foreach ($arg_list as $key => $value) {
622
+            if ($value) {
623
+                return $value;
624
+            }
625
+        }
626
+        return false;
627
+    }
628
+
629
+    public static function CaseInsensitiveInArray($needle, $haystack) {
630
+        $needle = strtolower($needle);
631
+        foreach ($haystack as $key => $value) {
632
+            if (is_array($value)) {
633
+                // skip?
634
+            } elseif ($needle == strtolower($value)) {
635
+                return true;
636
+            }
637
+        }
638
+        return false;
639
+    }
640
+
641
+    public static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
642
+        if (!function_exists('fsockopen') || self::FunctionIsDisabled('fsockopen')) {
643
+            $errstr = 'fsockopen() unavailable';
644
+            return false;
645
+        }
646
+        //if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
647
+        if ($fp = @fsockopen((($port == 443) ? 'ssl://' : '').$host, $port, $errno, $errstr, $timeout)) { // https://github.com/JamesHeinrich/phpThumb/issues/39
648
+            $out  = 'GET '.$file.' HTTP/1.0'."\r\n";
649
+            $out .= 'Host: '.$host."\r\n";
650
+            $out .= 'Connection: Close'."\r\n\r\n";
651
+            fwrite($fp, $out);
652
+
653
+            $isHeader = true;
654
+            $Data_header = '';
655
+            $Data_body   = '';
656
+            $header_newlocation = '';
657
+            while (!feof($fp)) {
658
+                $line = fgets($fp, 1024);
659
+                if ($isHeader) {
660
+                    $Data_header .= $line;
661
+                } else {
662
+                    $Data_body .= $line;
663
+                }
664
+                if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
665
+                    list( , $errno, $errstr) = $matches;
666
+                    $errno = (int) $errno;
667
+                } elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
668
+                    $header_newlocation = $matches[1];
669
+                }
670
+                if ($isHeader && ($line == "\r\n")) {
671
+                    $isHeader = false;
672
+                    if ($successonly) {
673
+                        switch ($errno) {
674
+                            case 200:
675
+                                // great, continue
676
+                                break;
677
+
678
+                            default:
679
+                                $errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
680
+                                fclose($fp);
681
+                                return false;
682
+                                break;
683
+                        }
684
+                    }
685
+                }
686
+            }
687
+            fclose($fp);
688
+            return $Data_body;
689
+        }
690
+        return null;
691
+    }
692
+
693
+    public static function CleanUpURLencoding($url, $queryseperator='&') {
694
+        if (!preg_match('#^http#i', $url)) {
695
+            return $url;
696
+        }
697
+        $parse_url = self::ParseURLbetter($url);
698
+        $pathelements = explode('/', $parse_url['path']);
699
+        $CleanPathElements = array();
700
+        $TranslationMatrix = array(' '=>'%20');
701
+        foreach ($pathelements as $key => $pathelement) {
702
+            $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
703
+        }
704
+        foreach ($CleanPathElements as $key => $value) {
705
+            if ($value === '') {
706
+                unset($CleanPathElements[$key]);
707
+            }
708
+        }
709
+
710
+        $queries = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
711
+        $CleanQueries = array();
712
+        foreach ($queries as $key => $query) {
713
+            @list($param, $value) = explode('=', $query);
714
+            $CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
715
+        }
716
+        foreach ($CleanQueries as $key => $value) {
717
+            if ($value === '') {
718
+                unset($CleanQueries[$key]);
719
+            }
720
+        }
721
+
722
+        $cleaned_url  = $parse_url['scheme'].'://';
723
+        $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
724
+        $cleaned_url .= $parse_url['host'];
725
+        $cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':'.$parse_url['port'] : '');
726
+        $cleaned_url .= '/'.implode('/', $CleanPathElements);
727
+        $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
728
+        return $cleaned_url;
729
+    }
730
+
731
+    public static function ParseURLbetter($url) {
732
+        $parsedURL = @parse_url($url);
733
+        if (!@$parsedURL['port']) {
734
+            switch (strtolower(@$parsedURL['scheme'])) {
735
+                case 'ftp':
736
+                    $parsedURL['port'] = 21;
737
+                    break;
738
+                case 'https':
739
+                    $parsedURL['port'] = 443;
740
+                    break;
741
+                case 'http':
742
+                    $parsedURL['port'] = 80;
743
+                    break;
744
+            }
745
+        }
746
+        return $parsedURL;
747
+    }
748
+
749
+    public static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
750
+        $error   = '';
751
+        $errstr  = '';
752
+        $rawData = '';
753
+
754
+        $parsed_url = self::ParseURLbetter($url);
755
+        $alreadyLookedAtURLs[trim($url)] = true;
756
+
757
+        while (true) {
758
+            $tryagain = false;
759
+            $rawData = self::URLreadFsock(@$parsed_url[ 'host'], @$parsed_url[ 'path'].'?'.@$parsed_url[ 'query'], $errstr, true, (@$parsed_url[ 'port'] ? @$parsed_url[ 'port'] : 80), $timeout);
760
+            if ($followredirects && preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
761
+                $matches[1] = trim(@$matches[1]);
762
+                if (!@$alreadyLookedAtURLs[$matches[1]]) {
763
+                    // loop through and examine new URL
764
+                    $error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
765
+
766
+                    $tryagain = true;
767
+                    $alreadyLookedAtURLs[$matches[1]] = true;
768
+                    $parsed_url = self::ParseURLbetter($matches[ 1]);
769
+                }
770
+            }
771
+            if (!$tryagain) {
772
+                break;
773
+            }
774
+        }
775
+
776
+        if ($rawData === false) {
777
+            $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
778
+            return false;
779
+        } elseif ($rawData === null) {
780
+            // fall through
781
+            $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
782
+        } else {
783
+            return $rawData;
784
+        }
785
+
786
+        if (function_exists('curl_version') && !self::FunctionIsDisabled('curl_exec')) {
787
+            $ch = curl_init();
788
+            curl_setopt($ch, CURLOPT_URL, $url);
789
+            curl_setopt($ch, CURLOPT_HEADER, false);
790
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
791
+            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
792
+            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
793
+            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
794
+            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, (bool) $followredirects);
795
+            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
796
+            $rawData = curl_exec($ch);
797
+            curl_close($ch);
798
+            if (strlen($rawData) > 0) {
799
+                $error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
800
+                return $rawData;
801
+            }
802
+            $error .= 'CURL available but returned no data; ';
803
+        } else {
804
+            $error .= 'CURL unavailable; ';
805
+        }
806
+
807
+        $BrokenURLfopenPHPversions = array('4.4.2');
808
+        if (in_array(PHP_VERSION, $BrokenURLfopenPHPversions)) {
809
+            $error .= 'fopen(URL) broken in PHP v'. PHP_VERSION .'; ';
810
+        } elseif (@ini_get('allow_url_fopen')) {
811
+            $rawData = '';
812
+            $error_fopen = '';
813
+            ob_start();
814
+            if ($fp = fopen($url, 'rb')) {
815
+                do {
816
+                    $buffer = fread($fp, 8192);
817
+                    $rawData .= $buffer;
818
+                } while (strlen($buffer) > 0);
819
+                fclose($fp);
820
+            } else {
821
+                $error_fopen .= trim(strip_tags(ob_get_contents()));
822
+            }
823
+            ob_end_clean();
824
+            $error .= $error_fopen;
825
+            if (!$error_fopen) {
826
+                $error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
827
+                return $rawData;
828
+            }
829
+            $error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
830
+        } else {
831
+            $error .= '"allow_url_fopen" disabled; ';
832
+        }
833
+
834
+        return false;
835
+    }
836
+
837
+    public static function EnsureDirectoryExists($dirname, $mask = 0755) {
838
+        $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
839
+        $startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
840
+        $open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
841
+        foreach ($open_basedirs as $key => $open_basedir) {
842
+            if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
843
+                $startoffset = substr_count($open_basedir, DIRECTORY_SEPARATOR) + 1;
844
+                break;
845
+            }
846
+        }
847
+        $i = $startoffset;
848
+        $endoffset = count($directory_elements);
849
+        for ($i = $startoffset; $i <= $endoffset; $i++) {
850
+            $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
851
+            if (!$test_directory) {
852
+                continue;
853
+            }
854
+            if (!@is_dir($test_directory)) {
855
+                if (@file_exists($test_directory)) {
856
+                    // directory name already exists as a file
857
+                    return false;
858
+                }
859
+                @mkdir($test_directory, $mask);
860
+                @chmod($test_directory, $mask);
861
+                if (!@is_dir($test_directory) || !@is_writable($test_directory)) {
862
+                    return false;
863
+                }
864
+            }
865
+        }
866
+        return true;
867
+    }
868
+
869
+
870
+    public static function GetAllFilesInSubfolders($dirname) {
871
+        $AllFiles = array();
872
+        $dirname = rtrim(realpath($dirname), '/\\');
873
+        if ($dirhandle = @opendir($dirname)) {
874
+            while (($file = readdir($dirhandle)) !== false) {
875
+                $fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
876
+                if (is_file($fullfilename)) {
877
+                    $AllFiles[] = $fullfilename;
878
+                } elseif (is_dir($fullfilename)) {
879
+                    switch ($file) {
880
+                        case '.':
881
+                        case '..':
882
+                            break;
883
+
884
+                        default:
885
+                            $AllFiles[] = $fullfilename;
886
+                            $subfiles = self::GetAllFilesInSubfolders($fullfilename);
887
+                            foreach ($subfiles as $filename) {
888
+                                $AllFiles[] = $filename;
889
+                            }
890
+                            break;
891
+                    }
892
+                } else {
893
+                    // ignore?
894
+                }
895
+            }
896
+            closedir($dirhandle);
897
+        }
898
+        sort($AllFiles);
899
+        return array_unique($AllFiles);
900
+    }
901
+
902
+
903
+    public static function SanitizeFilename($filename) {
904
+        $filename = preg_replace('/[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]/', '_', $filename);
905
+        if (self::version_compare_replacement(PHP_VERSION, '4.1.0', '>=')) {
906
+            $filename = trim($filename, '.');
907
+        }
908
+        return $filename;
909
+    }
910
+
911
+    public static function PasswordStrength($password) {
912
+        $strength = 0;
913
+        $strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
914
+        $strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
915
+        $strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
916
+        $strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
917
+        return $strength;
918
+    }
919 919
 
920 920
 }
921 921
 
@@ -924,147 +924,147 @@  discard block
 block discarded – undo
924 924
 
925 925
 
926 926
 if (!function_exists('gd_info')) {
927
-	// built into PHP v4.3.0+ (with bundled GD2 library)
928
-	function gd_info() {
929
-		static $gd_info = array();
930
-		if (empty($gd_info)) {
931
-			// based on code by johnschaefer at gmx dot de
932
-			// from PHP help on gd_info()
933
-			$gd_info = array(
934
-				'GD Version'         => '',
935
-				'FreeType Support'   => false,
936
-				'FreeType Linkage'   => '',
937
-				'T1Lib Support'      => false,
938
-				'GIF Read Support'   => false,
939
-				'GIF Create Support' => false,
940
-				'JPG Support'        => false,
941
-				'PNG Support'        => false,
942
-				'WBMP Support'       => false,
943
-				'XBM Support'        => false
944
-			);
945
-			$phpinfo_array = phpthumb_functions::phpinfo_array();
946
-			foreach ($phpinfo_array as $line) {
947
-				$line = trim(strip_tags($line));
948
-				foreach ($gd_info as $key => $value) {
949
-					//if (strpos($line, $key) !== false) {
950
-					if (strpos($line, $key) === 0) {
951
-						$newvalue = trim(str_replace($key, '', $line));
952
-						$gd_info[$key] = $newvalue;
953
-					}
954
-				}
955
-			}
956
-			if (empty($gd_info['GD Version'])) {
957
-				// probable cause: "phpinfo() disabled for security reasons"
958
-				if (function_exists('imagetypes')) {
959
-					$imagetypes = imagetypes();
960
-					if ($imagetypes & IMG_PNG) {
961
-						$gd_info['PNG Support'] = true;
962
-					}
963
-					if ($imagetypes & IMG_GIF) {
964
-						$gd_info['GIF Create Support'] = true;
965
-					}
966
-					if ($imagetypes & IMG_JPG) {
967
-						$gd_info['JPG Support'] = true;
968
-					}
969
-					if ($imagetypes & IMG_WBMP) {
970
-						$gd_info['WBMP Support'] = true;
971
-					}
972
-				}
973
-				// to determine capability of GIF creation, try to use imagecreatefromgif on a 1px GIF
974
-				if (function_exists('imagecreatefromgif')) {
975
-					if ($tempfilename = phpthumb::phpThumb_tempnam()) {
976
-						if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
977
-							fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
978
-							fclose($fp_tempfile);
979
-							@chmod($tempfilename, $this->getParameter('config_file_create_mask'));
980
-
981
-							// if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
982
-							$gd_info['GIF Read Support'] = (bool) @imagecreatefromgif($tempfilename);
983
-						}
984
-						unlink($tempfilename);
985
-					}
986
-				}
987
-				if (function_exists('imagecreatetruecolor') && @imagecreatetruecolor(1, 1)) {
988
-					$gd_info['GD Version'] = '2.0.1 or higher (assumed)';
989
-				} elseif (function_exists('imagecreate') && @imagecreate(1, 1)) {
990
-					$gd_info['GD Version'] = '1.6.0 or higher (assumed)';
991
-				}
992
-			}
993
-		}
994
-		return $gd_info;
995
-	}
927
+    // built into PHP v4.3.0+ (with bundled GD2 library)
928
+    function gd_info() {
929
+        static $gd_info = array();
930
+        if (empty($gd_info)) {
931
+            // based on code by johnschaefer at gmx dot de
932
+            // from PHP help on gd_info()
933
+            $gd_info = array(
934
+                'GD Version'         => '',
935
+                'FreeType Support'   => false,
936
+                'FreeType Linkage'   => '',
937
+                'T1Lib Support'      => false,
938
+                'GIF Read Support'   => false,
939
+                'GIF Create Support' => false,
940
+                'JPG Support'        => false,
941
+                'PNG Support'        => false,
942
+                'WBMP Support'       => false,
943
+                'XBM Support'        => false
944
+            );
945
+            $phpinfo_array = phpthumb_functions::phpinfo_array();
946
+            foreach ($phpinfo_array as $line) {
947
+                $line = trim(strip_tags($line));
948
+                foreach ($gd_info as $key => $value) {
949
+                    //if (strpos($line, $key) !== false) {
950
+                    if (strpos($line, $key) === 0) {
951
+                        $newvalue = trim(str_replace($key, '', $line));
952
+                        $gd_info[$key] = $newvalue;
953
+                    }
954
+                }
955
+            }
956
+            if (empty($gd_info['GD Version'])) {
957
+                // probable cause: "phpinfo() disabled for security reasons"
958
+                if (function_exists('imagetypes')) {
959
+                    $imagetypes = imagetypes();
960
+                    if ($imagetypes & IMG_PNG) {
961
+                        $gd_info['PNG Support'] = true;
962
+                    }
963
+                    if ($imagetypes & IMG_GIF) {
964
+                        $gd_info['GIF Create Support'] = true;
965
+                    }
966
+                    if ($imagetypes & IMG_JPG) {
967
+                        $gd_info['JPG Support'] = true;
968
+                    }
969
+                    if ($imagetypes & IMG_WBMP) {
970
+                        $gd_info['WBMP Support'] = true;
971
+                    }
972
+                }
973
+                // to determine capability of GIF creation, try to use imagecreatefromgif on a 1px GIF
974
+                if (function_exists('imagecreatefromgif')) {
975
+                    if ($tempfilename = phpthumb::phpThumb_tempnam()) {
976
+                        if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
977
+                            fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
978
+                            fclose($fp_tempfile);
979
+                            @chmod($tempfilename, $this->getParameter('config_file_create_mask'));
980
+
981
+                            // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
982
+                            $gd_info['GIF Read Support'] = (bool) @imagecreatefromgif($tempfilename);
983
+                        }
984
+                        unlink($tempfilename);
985
+                    }
986
+                }
987
+                if (function_exists('imagecreatetruecolor') && @imagecreatetruecolor(1, 1)) {
988
+                    $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
989
+                } elseif (function_exists('imagecreate') && @imagecreate(1, 1)) {
990
+                    $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
991
+                }
992
+            }
993
+        }
994
+        return $gd_info;
995
+    }
996 996
 }
997 997
 
998 998
 
999 999
 if (!function_exists('is_executable')) {
1000
-	// in PHP v3+, but v5.0+ for Windows
1001
-	function is_executable($filename) {
1002
-		// poor substitute, but better than nothing
1003
-		return file_exists($filename);
1004
-	}
1000
+    // in PHP v3+, but v5.0+ for Windows
1001
+    function is_executable($filename) {
1002
+        // poor substitute, but better than nothing
1003
+        return file_exists($filename);
1004
+    }
1005 1005
 }
1006 1006
 
1007 1007
 
1008 1008
 if (!function_exists('preg_quote')) {
1009
-	// included in PHP v3.0.9+, but may be unavailable if not compiled in
1010
-	function preg_quote($string, $delimiter='\\') {
1011
-		static $preg_quote_array = array();
1012
-		if (empty($preg_quote_array)) {
1013
-			$escapeables = '.\\+*?[^]$(){}=!<>|:';
1014
-			for ($i = 0, $iMax = strlen($escapeables); $i < $iMax; $i++) {
1015
-				$strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
1016
-			}
1017
-		}
1018
-		return strtr($string, $strtr_preg_quote);
1019
-	}
1009
+    // included in PHP v3.0.9+, but may be unavailable if not compiled in
1010
+    function preg_quote($string, $delimiter='\\') {
1011
+        static $preg_quote_array = array();
1012
+        if (empty($preg_quote_array)) {
1013
+            $escapeables = '.\\+*?[^]$(){}=!<>|:';
1014
+            for ($i = 0, $iMax = strlen($escapeables); $i < $iMax; $i++) {
1015
+                $strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
1016
+            }
1017
+        }
1018
+        return strtr($string, $strtr_preg_quote);
1019
+    }
1020 1020
 }
1021 1021
 
1022 1022
 if (!function_exists('file_get_contents')) {
1023
-	// included in PHP v4.3.0+
1024
-	function file_get_contents($filename) {
1025
-		if (preg_match('#^(f|ht)tp\://#i', $filename)) {
1026
-			return SafeURLread($filename, $error);
1027
-		}
1028
-		if ($fp = @fopen($filename, 'rb')) {
1029
-			$rawData = '';
1030
-			do {
1031
-				$buffer = fread($fp, 8192);
1032
-				$rawData .= $buffer;
1033
-			} while (strlen($buffer) > 0);
1034
-			fclose($fp);
1035
-			return $rawData;
1036
-		}
1037
-		return false;
1038
-	}
1023
+    // included in PHP v4.3.0+
1024
+    function file_get_contents($filename) {
1025
+        if (preg_match('#^(f|ht)tp\://#i', $filename)) {
1026
+            return SafeURLread($filename, $error);
1027
+        }
1028
+        if ($fp = @fopen($filename, 'rb')) {
1029
+            $rawData = '';
1030
+            do {
1031
+                $buffer = fread($fp, 8192);
1032
+                $rawData .= $buffer;
1033
+            } while (strlen($buffer) > 0);
1034
+            fclose($fp);
1035
+            return $rawData;
1036
+        }
1037
+        return false;
1038
+    }
1039 1039
 }
1040 1040
 
1041 1041
 
1042 1042
 if (!function_exists('file_put_contents')) {
1043
-	// included in PHP v5.0.0+
1044
-	function file_put_contents($filename, $filedata) {
1045
-		if ($fp = @fopen($filename, 'wb')) {
1046
-			fwrite($fp, $filedata);
1047
-			fclose($fp);
1048
-			return true;
1049
-		}
1050
-		return false;
1051
-	}
1043
+    // included in PHP v5.0.0+
1044
+    function file_put_contents($filename, $filedata) {
1045
+        if ($fp = @fopen($filename, 'wb')) {
1046
+            fwrite($fp, $filedata);
1047
+            fclose($fp);
1048
+            return true;
1049
+        }
1050
+        return false;
1051
+    }
1052 1052
 }
1053 1053
 
1054 1054
 if (!function_exists('imagealphablending')) {
1055
-	// built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1056
-	function imagealphablending(&$img, $blendmode=true) {
1057
-		// do nothing, this function is declared here just to
1058
-		// prevent runtime errors if GD2 is not available
1059
-		return true;
1060
-	}
1055
+    // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1056
+    function imagealphablending(&$img, $blendmode=true) {
1057
+        // do nothing, this function is declared here just to
1058
+        // prevent runtime errors if GD2 is not available
1059
+        return true;
1060
+    }
1061 1061
 }
1062 1062
 
1063 1063
 if (!function_exists('imagesavealpha')) {
1064
-	// built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1065
-	function imagesavealpha(&$img, $blendmode=true) {
1066
-		// do nothing, this function is declared here just to
1067
-		// prevent runtime errors if GD2 is not available
1068
-		return true;
1069
-	}
1064
+    // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1065
+    function imagesavealpha(&$img, $blendmode=true) {
1066
+        // do nothing, this function is declared here just to
1067
+        // prevent runtime errors if GD2 is not available
1068
+        return true;
1069
+    }
1070 1070
 }
Please login to merge, or discard this patch.
Spacing   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	}
36 36
 
37 37
 
38
-	public static function version_compare_replacement_sub($version1, $version2, $operator='') {
38
+	public static function version_compare_replacement_sub($version1, $version2, $operator = '') {
39 39
 		// If you specify the third optional operator argument, you can test for a particular relationship.
40 40
 		// The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
41 41
 		// Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
@@ -61,29 +61,29 @@  discard block
 block discarded – undo
61 61
 		switch ($operator) {
62 62
 			case '<':
63 63
 			case 'lt':
64
-				return (int) ($version1 < $version2);
64
+				return (int)($version1 < $version2);
65 65
 				break;
66 66
 			case '<=':
67 67
 			case 'le':
68
-				return (int) ($version1 <= $version2);
68
+				return (int)($version1 <= $version2);
69 69
 				break;
70 70
 			case '>':
71 71
 			case 'gt':
72
-				return (int) ($version1 > $version2);
72
+				return (int)($version1 > $version2);
73 73
 				break;
74 74
 			case '>=':
75 75
 			case 'ge':
76
-				return (int) ($version1 >= $version2);
76
+				return (int)($version1 >= $version2);
77 77
 				break;
78 78
 			case '==':
79 79
 			case '=':
80 80
 			case 'eq':
81
-				return (int) ($version1 == $version2);
81
+				return (int)($version1 == $version2);
82 82
 				break;
83 83
 			case '!=':
84 84
 			case '<>':
85 85
 			case 'ne':
86
-				return (int) ($version1 != $version2);
86
+				return (int)($version1 != $version2);
87 87
 				break;
88 88
 		}
89 89
 		if ($version1 == $version2) {
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	}
96 96
 
97 97
 
98
-	public static function version_compare_replacement($version1, $version2, $operator='') {
98
+	public static function version_compare_replacement($version1, $version2, $operator = '') {
99 99
 		if (function_exists('version_compare')) {
100 100
 			// built into PHP v4.1.0+
101 101
 			return version_compare($version1, $version2, $operator);
@@ -174,28 +174,28 @@  discard block
 block discarded – undo
174 174
 			return image_type_to_mime_type($imagetype);
175 175
 		}
176 176
 		static $image_type_to_mime_type = array(
177
-			1  => 'image/gif',                     // IMAGETYPE_GIF
178
-			2  => 'image/jpeg',                    // IMAGETYPE_JPEG
179
-			3  => 'image/png',                     // IMAGETYPE_PNG
177
+			1  => 'image/gif', // IMAGETYPE_GIF
178
+			2  => 'image/jpeg', // IMAGETYPE_JPEG
179
+			3  => 'image/png', // IMAGETYPE_PNG
180 180
 			4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
181
-			5  => 'image/psd',                     // IMAGETYPE_PSD
182
-			6  => 'image/bmp',                     // IMAGETYPE_BMP
183
-			7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
184
-			8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
185
-			9  => 'application/octet-stream',      // IMAGETYPE_JPC
186
-			10 => 'image/jp2',                     // IMAGETYPE_JP2
187
-			11 => 'application/octet-stream',      // IMAGETYPE_JPX
188
-			12 => 'application/octet-stream',      // IMAGETYPE_JB2
181
+			5  => 'image/psd', // IMAGETYPE_PSD
182
+			6  => 'image/bmp', // IMAGETYPE_BMP
183
+			7  => 'image/tiff', // IMAGETYPE_TIFF_II (intel byte order)
184
+			8  => 'image/tiff', // IMAGETYPE_TIFF_MM (motorola byte order)
185
+			9  => 'application/octet-stream', // IMAGETYPE_JPC
186
+			10 => 'image/jp2', // IMAGETYPE_JP2
187
+			11 => 'application/octet-stream', // IMAGETYPE_JPX
188
+			12 => 'application/octet-stream', // IMAGETYPE_JB2
189 189
 			13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
190
-			14 => 'image/iff',                     // IMAGETYPE_IFF
191
-			15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
192
-			16 => 'image/xbm',                     // IMAGETYPE_XBM
193
-
194
-			'gif'  => 'image/gif',                 // IMAGETYPE_GIF
195
-			'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
196
-			'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
197
-			'png'  => 'image/png',                 // IMAGETYPE_PNG
198
-			'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
190
+			14 => 'image/iff', // IMAGETYPE_IFF
191
+			15 => 'image/vnd.wap.wbmp', // IMAGETYPE_WBMP
192
+			16 => 'image/xbm', // IMAGETYPE_XBM
193
+
194
+			'gif'  => 'image/gif', // IMAGETYPE_GIF
195
+			'jpg'  => 'image/jpeg', // IMAGETYPE_JPEG
196
+			'jpeg' => 'image/jpeg', // IMAGETYPE_JPEG
197
+			'png'  => 'image/png', // IMAGETYPE_PNG
198
+			'bmp'  => 'image/bmp', // IMAGETYPE_BMP
199 199
 			'ico'  => 'image/x-icon',
200 200
 		);
201 201
 
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 			return array($width, $height);
209 209
 		}
210 210
 		$newwidth  = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
211
-		$newheight = (abs(sin(deg2rad($angle))) * $width)  + (abs(cos(deg2rad($angle))) * $height);
211
+		$newheight = (abs(sin(deg2rad($angle))) * $width) + (abs(cos(deg2rad($angle))) * $height);
212 212
 		return array($newwidth, $newheight);
213 213
 	}
214 214
 
@@ -227,15 +227,15 @@  discard block
 block discarded – undo
227 227
 	}
228 228
 
229 229
 
230
-	public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
230
+	public static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha = false) {
231 231
 		if (self::version_compare_replacement(PHP_VERSION, '4.3.2', '>=') && ($alpha !== false)) {
232
-			return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int) $alpha);
232
+			return imagecolorallocatealpha($gdimg_hexcolorallocate, $R, $G, $B, (int)$alpha);
233 233
 		} else {
234 234
 			return imagecolorallocate($gdimg_hexcolorallocate, $R, $G, $B);
235 235
 		}
236 236
 	}
237 237
 
238
-	public static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
238
+	public static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid = false, $alpha = false) {
239 239
 		if (!is_resource($gdimg_hexcolorallocate)) {
240 240
 			die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
241 241
 		}
@@ -279,21 +279,21 @@  discard block
 block discarded – undo
279 279
 
280 280
 
281 281
 	public static function GrayscalePixel($OriginalPixel) {
282
-		$gray = self::GrayscaleValue($OriginalPixel[ 'red'], $OriginalPixel[ 'green'], $OriginalPixel[ 'blue']);
282
+		$gray = self::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
283 283
 		return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
284 284
 	}
285 285
 
286 286
 
287 287
 	public static function GrayscalePixelRGB($rgb) {
288 288
 		$r = ($rgb >> 16) & 0xFF;
289
-		$g = ($rgb >>  8) & 0xFF;
290
-		$b =  $rgb        & 0xFF;
289
+		$g = ($rgb >> 8) & 0xFF;
290
+		$b = $rgb & 0xFF;
291 291
 		return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
292 292
 	}
293 293
 
294 294
 
295
-	public static function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
296
-		$maxwidth  = (null === $maxwidth  ? $width  : $maxwidth);
295
+	public static function ScaleToFitInBox($width, $height, $maxwidth = null, $maxheight = null, $allow_enlarge = true, $allow_reduce = true) {
296
+		$maxwidth  = (null === $maxwidth ? $width : $maxwidth);
297 297
 		$maxheight = (null === $maxheight ? $height : $maxheight);
298 298
 		$scale_x = 1;
299 299
 		$scale_y = 1;
@@ -327,13 +327,13 @@  discard block
 block discarded – undo
327 327
 
328 328
 		for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
329 329
 			$sY   = $y * $scaleY;
330
-			$siY  = (int) $sY;
331
-			$siY2 = (int) $sY + $scaleY2;
330
+			$siY  = (int)$sY;
331
+			$siY2 = (int)$sY + $scaleY2;
332 332
 
333 333
 			for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
334 334
 				$sX   = $x * $scaleX;
335
-				$siX  = (int) $sX;
336
-				$siX2 = (int) $sX + $scaleX2;
335
+				$siX  = (int)$sX;
336
+				$siX2 = (int)$sX + $scaleX2;
337 337
 
338 338
 				if ($isTrueColor) {
339 339
 
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 					$c3 = imagecolorat($src_img, $siX2, $siY2);
343 343
 					$c4 = imagecolorat($src_img, $siX2, $siY);
344 344
 
345
-					$r = (( $c1             +  $c2             +  $c3             +  $c4            ) >> 2) & 0xFF0000;
345
+					$r = (($c1 + $c2 + $c3 + $c4) >> 2) & 0xFF0000;
346 346
 					$g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
347 347
 					$b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
348 348
 
@@ -353,12 +353,12 @@  discard block
 block discarded – undo
353 353
 					$c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
354 354
 					$c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
355 355
 
356
-					$r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red'] )  << 14;
357
-					$g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) <<  6;
358
-					$b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >>  2;
356
+					$r = ($c1['red'] + $c2['red'] + $c3['red'] + $c4['red']) << 14;
357
+					$g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
358
+					$b = ($c1['blue'] + $c2['blue'] + $c3['blue'] + $c4['blue']) >> 2;
359 359
 
360 360
 				}
361
-				imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
361
+				imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r + $g + $b);
362 362
 			}
363 363
 		}
364 364
 		return true;
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	}
381 381
 
382 382
 
383
-	public static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
383
+	public static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct = 100) {
384 384
 		$opacipct = $opacity_pct / 100;
385 385
 		for ($x = $src_x; $x < $src_w; $x++) {
386 386
 			for ($y = $src_y; $y < $src_h; $y++) {
@@ -391,9 +391,9 @@  discard block
 block discarded – undo
391 391
 
392 392
 				$newcolor = self::ImageColorAllocateAlphaSafe(
393 393
 					$dst_im,
394
-					round($RealPixel['red']   * (1 - $overlaypct)) + ($OverlayPixel['red']   * $overlaypct),
394
+					round($RealPixel['red'] * (1 - $overlaypct)) + ($OverlayPixel['red'] * $overlaypct),
395 395
 					round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
396
-					round($RealPixel['blue']  * (1 - $overlaypct)) + ($OverlayPixel['blue']  * $overlaypct),
396
+					round($RealPixel['blue'] * (1 - $overlaypct)) + ($OverlayPixel['blue'] * $overlaypct),
397 397
 					//$RealPixel['alpha']);
398 398
 					0);
399 399
 
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 	}
405 405
 
406 406
 
407
-	public static function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
407
+	public static function ProportionalResize($old_width, $old_height, $new_width = false, $new_height = false) {
408 408
 		$old_aspect_ratio = $old_width / $old_height;
409 409
 		if (($new_width === false) && ($new_height === false)) {
410 410
 			return false;
@@ -424,8 +424,8 @@  discard block
 block discarded – undo
424 424
 			$new_width = $new_height * $old_aspect_ratio;
425 425
 		}
426 426
 		return array(
427
-			(int) round($new_width),
428
-			(int) round($new_height)
427
+			(int)round($new_width),
428
+			(int)round($new_height)
429 429
 		);
430 430
 	}
431 431
 
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	public static function FunctionIsDisabled($function) {
434 434
 		static $DisabledFunctions = null;
435 435
 		if (null === $DisabledFunctions) {
436
-			$disable_functions_local  = explode(',',     strtolower(@ini_get('disable_functions')));
436
+			$disable_functions_local  = explode(',', strtolower(@ini_get('disable_functions')));
437 437
 			$disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
438 438
 			foreach ($disable_functions_local as $key => $value) {
439 439
 				$DisabledFunctions[trim($value)] = 'local';
@@ -518,23 +518,23 @@  discard block
 block discarded – undo
518 518
 	}
519 519
 
520 520
 
521
-	public static function gd_version($fullstring=false) {
521
+	public static function gd_version($fullstring = false) {
522 522
 		static $cache_gd_version = array();
523 523
 		if (empty($cache_gd_version)) {
524 524
 			$gd_info = gd_info();
525 525
 			if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
526
-				$cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
527
-				$cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
526
+				$cache_gd_version[1] = $gd_info['GD Version']; // e.g. "bundled (2.0.15 compatible)"
527
+				$cache_gd_version[0] = (float)$matches[1]; // e.g. "2.0" (not "bundled (2.0.15 compatible)")
528 528
 			} else {
529
-				$cache_gd_version[1] = $gd_info['GD Version'];                       // e.g. "1.6.2 or higher"
530
-				$cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
529
+				$cache_gd_version[1] = $gd_info['GD Version']; // e.g. "1.6.2 or higher"
530
+				$cache_gd_version[0] = (float)substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
531 531
 			}
532 532
 		}
533
-		return $cache_gd_version[ (int) $fullstring ];
533
+		return $cache_gd_version[(int)$fullstring];
534 534
 	}
535 535
 
536 536
 
537
-	public static function filesize_remote($remotefile, $timeout=10) {
537
+	public static function filesize_remote($remotefile, $timeout = 10) {
538 538
 		$size = false;
539 539
 		$url = self::ParseURLbetter($remotefile);
540 540
 		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
@@ -545,17 +545,17 @@  discard block
 block discarded – undo
545 545
 			while (!feof($fp)) {
546 546
 				$headerline = fgets($fp, 4096);
547 547
 				if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
548
-					$size = (int) $matches[ 1];
548
+					$size = (int)$matches[1];
549 549
 					break;
550 550
 				}
551 551
 			}
552
-			fclose ($fp);
552
+			fclose($fp);
553 553
 		}
554 554
 		return $size;
555 555
 	}
556 556
 
557 557
 
558
-	public static function filedate_remote($remotefile, $timeout=10) {
558
+	public static function filedate_remote($remotefile, $timeout = 10) {
559 559
 		$date = false;
560 560
 		$url = self::ParseURLbetter($remotefile);
561 561
 		if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 					break;
571 571
 				}
572 572
 			}
573
-			fclose ($fp);
573
+			fclose($fp);
574 574
 		}
575 575
 		return $date;
576 576
 	}
@@ -606,11 +606,11 @@  discard block
 block discarded – undo
606 606
 	}
607 607
 
608 608
 
609
-	public static function LittleEndian2String($number, $minbytes=1) {
609
+	public static function LittleEndian2String($number, $minbytes = 1) {
610 610
 		$intstring = '';
611 611
 		while ($number > 0) {
612 612
 			$intstring .= chr($number & 255);
613
-			$number    >>= 8;
613
+			$number >>= 8;
614 614
 		}
615 615
 		return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
616 616
 	}
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 		return false;
639 639
 	}
640 640
 
641
-	public static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
641
+	public static function URLreadFsock($host, $file, &$errstr, $successonly = true, $port = 80, $timeout = 10) {
642 642
 		if (!function_exists('fsockopen') || self::FunctionIsDisabled('fsockopen')) {
643 643
 			$errstr = 'fsockopen() unavailable';
644 644
 			return false;
@@ -662,8 +662,8 @@  discard block
 block discarded – undo
662 662
 					$Data_body .= $line;
663 663
 				}
664 664
 				if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
665
-					list( , $errno, $errstr) = $matches;
666
-					$errno = (int) $errno;
665
+					list(, $errno, $errstr) = $matches;
666
+					$errno = (int)$errno;
667 667
 				} elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
668 668
 					$header_newlocation = $matches[1];
669 669
 				}
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 		return null;
691 691
 	}
692 692
 
693
-	public static function CleanUpURLencoding($url, $queryseperator='&') {
693
+	public static function CleanUpURLencoding($url, $queryseperator = '&') {
694 694
 		if (!preg_match('#^http#i', $url)) {
695 695
 			return $url;
696 696
 		}
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
 		return $parsedURL;
747 747
 	}
748 748
 
749
-	public static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
749
+	public static function SafeURLread($url, &$error, $timeout = 10, $followredirects = true) {
750 750
 		$error   = '';
751 751
 		$errstr  = '';
752 752
 		$rawData = '';
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
 
757 757
 		while (true) {
758 758
 			$tryagain = false;
759
-			$rawData = self::URLreadFsock(@$parsed_url[ 'host'], @$parsed_url[ 'path'].'?'.@$parsed_url[ 'query'], $errstr, true, (@$parsed_url[ 'port'] ? @$parsed_url[ 'port'] : 80), $timeout);
759
+			$rawData = self::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
760 760
 			if ($followredirects && preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
761 761
 				$matches[1] = trim(@$matches[1]);
762 762
 				if (!@$alreadyLookedAtURLs[$matches[1]]) {
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 
766 766
 					$tryagain = true;
767 767
 					$alreadyLookedAtURLs[$matches[1]] = true;
768
-					$parsed_url = self::ParseURLbetter($matches[ 1]);
768
+					$parsed_url = self::ParseURLbetter($matches[1]);
769 769
 				}
770 770
 			}
771 771
 			if (!$tryagain) {
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
 			curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
792 792
 			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
793 793
 			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
794
-			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, (bool) $followredirects);
794
+			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, (bool)$followredirects);
795 795
 			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
796 796
 			$rawData = curl_exec($ch);
797 797
 			curl_close($ch);
@@ -806,7 +806,7 @@  discard block
 block discarded – undo
806 806
 
807 807
 		$BrokenURLfopenPHPversions = array('4.4.2');
808 808
 		if (in_array(PHP_VERSION, $BrokenURLfopenPHPversions)) {
809
-			$error .= 'fopen(URL) broken in PHP v'. PHP_VERSION .'; ';
809
+			$error .= 'fopen(URL) broken in PHP v'.PHP_VERSION.'; ';
810 810
 		} elseif (@ini_get('allow_url_fopen')) {
811 811
 			$rawData = '';
812 812
 			$error_fopen = '';
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
 
837 837
 	public static function EnsureDirectoryExists($dirname, $mask = 0755) {
838 838
 		$directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
839
-		$startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
839
+		$startoffset = (!$directory_elements[0] ? 2 : 1); // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
840 840
 		$open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
841 841
 		foreach ($open_basedirs as $key => $open_basedir) {
842 842
 			if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
@@ -910,10 +910,10 @@  discard block
 block discarded – undo
910 910
 
911 911
 	public static function PasswordStrength($password) {
912 912
 		$strength = 0;
913
-		$strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
914
-		$strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
915
-		$strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
916
-		$strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
913
+		$strength += strlen(preg_replace('#[^a-z]#', '', $password)) * 0.5; // lowercase characters are weak
914
+		$strength += strlen(preg_replace('#[^A-Z]#', '', $password)) * 0.8; // uppercase characters are somewhat better
915
+		$strength += strlen(preg_replace('#[^0-9]#', '', $password)) * 1.0; // numbers are somewhat better
916
+		$strength += strlen(preg_replace('#[a-zA-Z0-9]#', '', $password)) * 2.0; // other non-alphanumeric characters are best
917 917
 		return $strength;
918 918
 	}
919 919
 
@@ -979,7 +979,7 @@  discard block
 block discarded – undo
979 979
 							@chmod($tempfilename, $this->getParameter('config_file_create_mask'));
980 980
 
981 981
 							// if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
982
-							$gd_info['GIF Read Support'] = (bool) @imagecreatefromgif($tempfilename);
982
+							$gd_info['GIF Read Support'] = (bool)@imagecreatefromgif($tempfilename);
983 983
 						}
984 984
 						unlink($tempfilename);
985 985
 					}
@@ -1007,7 +1007,7 @@  discard block
 block discarded – undo
1007 1007
 
1008 1008
 if (!function_exists('preg_quote')) {
1009 1009
 	// included in PHP v3.0.9+, but may be unavailable if not compiled in
1010
-	function preg_quote($string, $delimiter='\\') {
1010
+	function preg_quote($string, $delimiter = '\\') {
1011 1011
 		static $preg_quote_array = array();
1012 1012
 		if (empty($preg_quote_array)) {
1013 1013
 			$escapeables = '.\\+*?[^]$(){}=!<>|:';
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
 
1054 1054
 if (!function_exists('imagealphablending')) {
1055 1055
 	// built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
1056
-	function imagealphablending(&$img, $blendmode=true) {
1056
+	function imagealphablending(&$img, $blendmode = true) {
1057 1057
 		// do nothing, this function is declared here just to
1058 1058
 		// prevent runtime errors if GD2 is not available
1059 1059
 		return true;
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
 
1063 1063
 if (!function_exists('imagesavealpha')) {
1064 1064
 	// built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
1065
-	function imagesavealpha(&$img, $blendmode=true) {
1065
+	function imagesavealpha(&$img, $blendmode = true) {
1066 1066
 		// do nothing, this function is declared here just to
1067 1067
 		// prevent runtime errors if GD2 is not available
1068 1068
 		return true;
Please login to merge, or discard this patch.
htdocs/modules/system/class/thumbs/phpthumb.bmp.php 2 patches
Indentation   +846 added lines, -846 removed lines patch added patch discarded remove patch
@@ -20,851 +20,851 @@
 block discarded – undo
20 20
 
21 21
 class phpthumb_bmp {
22 22
 
23
-	public function phpthumb_bmp2gd(&$BMPdata, $truecolor=true) {
24
-		$ThisFileInfo = array();
25
-		if ($this->getid3_bmp($BMPdata, $ThisFileInfo, true, true)) {
26
-			$gd = $this->PlotPixelsGD($ThisFileInfo['bmp'], $truecolor);
27
-			return $gd;
28
-		}
29
-		return false;
30
-	}
31
-
32
-	public function phpthumb_bmpfile2gd($filename, $truecolor=true) {
33
-		if ($fp = @fopen($filename, 'rb')) {
34
-			$BMPdata = fread($fp, filesize($filename));
35
-			fclose($fp);
36
-			return $this->phpthumb_bmp2gd($BMPdata, $truecolor);
37
-		}
38
-		return false;
39
-	}
40
-
41
-	public function GD2BMPstring(&$gd_image) {
42
-		$imageX = imagesx($gd_image);
43
-		$imageY = imagesy($gd_image);
44
-
45
-		$BMP = '';
46
-		for ($y = ($imageY - 1); $y >= 0; $y--) {
47
-			$thisline = '';
48
-			for ($x = 0; $x < $imageX; $x++) {
49
-				$argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
50
-				$thisline .= chr($argb['blue']).chr($argb['green']).chr($argb['red']);
51
-			}
52
-			while (strlen($thisline) % 4) {
53
-				$thisline .= "\x00";
54
-			}
55
-			$BMP .= $thisline;
56
-		}
57
-
58
-		$bmpSize = strlen($BMP) + 14 + 40;
59
-		// BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
60
-		$BITMAPFILEHEADER  = 'BM';                                                           // WORD    bfType;
61
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String($bmpSize, 4); // DWORD   bfSize;
62
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved1;
63
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved2;
64
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(      54, 4); // DWORD   bfOffBits;
65
-
66
-		// BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
67
-		$BITMAPINFOHEADER  = phpthumb_functions::LittleEndian2String(      40, 4); // DWORD  biSize;
68
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageX, 4); // LONG   biWidth;
69
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageY, 4); // LONG   biHeight;
70
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       1, 2); // WORD   biPlanes;
71
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(      24, 2); // WORD   biBitCount;
72
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biCompression;
73
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biSizeImage;
74
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biXPelsPerMeter;
75
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biYPelsPerMeter;
76
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrUsed;
77
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrImportant;
78
-
79
-		return $BITMAPFILEHEADER.$BITMAPINFOHEADER.$BMP;
80
-	}
81
-
82
-	public function getid3_bmp(&$BMPdata, &$ThisFileInfo, $ExtractPalette=false, $ExtractData=false) {
83
-
84
-		// shortcuts
85
-		$ThisFileInfo['bmp']['header']['raw'] = array();
86
-		$thisfile_bmp                         = &$ThisFileInfo['bmp'];
87
-		$thisfile_bmp_header                  = &$thisfile_bmp['header'];
88
-		$thisfile_bmp_header_raw              = &$thisfile_bmp_header['raw'];
89
-
90
-		// BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
91
-		// all versions
92
-		// WORD    bfType;
93
-		// DWORD   bfSize;
94
-		// WORD    bfReserved1;
95
-		// WORD    bfReserved2;
96
-		// DWORD   bfOffBits;
97
-
98
-		$offset = 0;
99
-		$overalloffset = 0;
100
-		$BMPheader = substr($BMPdata, $overalloffset, 14 + 40);
101
-		$overalloffset += (14 + 40);
102
-
103
-		$thisfile_bmp_header_raw['identifier']  = substr($BMPheader, $offset, 2);
104
-		$offset += 2;
105
-
106
-		if ($thisfile_bmp_header_raw['identifier'] != 'BM') {
107
-			$ThisFileInfo['error'][] = 'Expecting "BM" at offset '. (int) (@$ThisFileInfo[ 'avdataoffset']) .', found "'. $thisfile_bmp_header_raw[ 'identifier'].'"';
108
-			unset($ThisFileInfo['fileformat']);
109
-			unset($ThisFileInfo['bmp']);
110
-			return false;
111
-		}
112
-
113
-		$thisfile_bmp_header_raw['filesize']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
114
-		$offset += 4;
115
-		$thisfile_bmp_header_raw['reserved1']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
116
-		$offset += 2;
117
-		$thisfile_bmp_header_raw['reserved2']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
118
-		$offset += 2;
119
-		$thisfile_bmp_header_raw['data_offset'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
120
-		$offset += 4;
121
-		$thisfile_bmp_header_raw['header_size'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
122
-		$offset += 4;
123
-
124
-
125
-		// check if the hardcoded-to-1 "planes" is at offset 22 or 26
126
-		$planes22 = $this->LittleEndian2Int(substr($BMPheader, 22, 2));
127
-		$planes26 = $this->LittleEndian2Int(substr($BMPheader, 26, 2));
128
-		if (($planes22 == 1) && ($planes26 != 1)) {
129
-			$thisfile_bmp['type_os']      = 'OS/2';
130
-			$thisfile_bmp['type_version'] = 1;
131
-		} elseif (($planes26 == 1) && ($planes22 != 1)) {
132
-			$thisfile_bmp['type_os']      = 'Windows';
133
-			$thisfile_bmp['type_version'] = 1;
134
-		} elseif ($thisfile_bmp_header_raw['header_size'] == 12) {
135
-			$thisfile_bmp['type_os']      = 'OS/2';
136
-			$thisfile_bmp['type_version'] = 1;
137
-		} elseif ($thisfile_bmp_header_raw['header_size'] == 40) {
138
-			$thisfile_bmp['type_os']      = 'Windows';
139
-			$thisfile_bmp['type_version'] = 1;
140
-		} elseif ($thisfile_bmp_header_raw['header_size'] == 84) {
141
-			$thisfile_bmp['type_os']      = 'Windows';
142
-			$thisfile_bmp['type_version'] = 4;
143
-		} elseif ($thisfile_bmp_header_raw['header_size'] == 100) {
144
-			$thisfile_bmp['type_os']      = 'Windows';
145
-			$thisfile_bmp['type_version'] = 5;
146
-		} else {
147
-			$ThisFileInfo['error'][] = 'Unknown BMP subtype (or not a BMP file)';
148
-			unset($ThisFileInfo['fileformat']);
149
-			unset($ThisFileInfo['bmp']);
150
-			return false;
151
-		}
152
-
153
-		$ThisFileInfo['fileformat']                  = 'bmp';
154
-		$ThisFileInfo['video']['dataformat']         = 'bmp';
155
-		$ThisFileInfo['video']['lossless']           = true;
156
-		$ThisFileInfo['video']['pixel_aspect_ratio'] = (float) 1;
157
-
158
-		if ($thisfile_bmp['type_os'] == 'OS/2') {
159
-
160
-			// OS/2-format BMP
161
-			// http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm
162
-
163
-			// DWORD  Size;             /* Size of this structure in bytes */
164
-			// DWORD  Width;            /* Bitmap width in pixels */
165
-			// DWORD  Height;           /* Bitmap height in pixel */
166
-			// WORD   NumPlanes;        /* Number of bit planes (color depth) */
167
-			// WORD   BitsPerPixel;     /* Number of bits per pixel per plane */
168
-
169
-			$thisfile_bmp_header_raw['width']          = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
170
-			$offset += 2;
171
-			$thisfile_bmp_header_raw['height']         = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
172
-			$offset += 2;
173
-			$thisfile_bmp_header_raw['planes']         = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
174
-			$offset += 2;
175
-			$thisfile_bmp_header_raw['bits_per_pixel'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
176
-			$offset += 2;
177
-
178
-			$ThisFileInfo['video']['resolution_x']    = $thisfile_bmp_header_raw['width'];
179
-			$ThisFileInfo['video']['resolution_y']    = $thisfile_bmp_header_raw['height'];
180
-			$ThisFileInfo['video']['codec']           = 'BI_RGB '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
181
-			$ThisFileInfo['video']['bits_per_sample'] = $thisfile_bmp_header_raw['bits_per_pixel'];
182
-
183
-			if ($thisfile_bmp['type_version'] >= 2) {
184
-				// DWORD  Compression;      /* Bitmap compression scheme */
185
-				// DWORD  ImageDataSize;    /* Size of bitmap data in bytes */
186
-				// DWORD  XResolution;      /* X resolution of display device */
187
-				// DWORD  YResolution;      /* Y resolution of display device */
188
-				// DWORD  ColorsUsed;       /* Number of color table indices used */
189
-				// DWORD  ColorsImportant;  /* Number of important color indices */
190
-				// WORD   Units;            /* Type of units used to measure resolution */
191
-				// WORD   Reserved;         /* Pad structure to 4-byte boundary */
192
-				// WORD   Recording;        /* Recording algorithm */
193
-				// WORD   Rendering;        /* Halftoning algorithm used */
194
-				// DWORD  Size1;            /* Reserved for halftoning algorithm use */
195
-				// DWORD  Size2;            /* Reserved for halftoning algorithm use */
196
-				// DWORD  ColorEncoding;    /* Color model used in bitmap */
197
-				// DWORD  Identifier;       /* Reserved for application use */
198
-
199
-				$thisfile_bmp_header_raw['compression']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
200
-				$offset += 4;
201
-				$thisfile_bmp_header_raw['bmp_data_size']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
202
-				$offset += 4;
203
-				$thisfile_bmp_header_raw['resolution_h']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
204
-				$offset += 4;
205
-				$thisfile_bmp_header_raw['resolution_v']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
206
-				$offset += 4;
207
-				$thisfile_bmp_header_raw['colors_used']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
208
-				$offset += 4;
209
-				$thisfile_bmp_header_raw['colors_important'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
210
-				$offset += 4;
211
-				$thisfile_bmp_header_raw['resolution_units'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
212
-				$offset += 2;
213
-				$thisfile_bmp_header_raw['reserved1']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
214
-				$offset += 2;
215
-				$thisfile_bmp_header_raw['recording']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
216
-				$offset += 2;
217
-				$thisfile_bmp_header_raw['rendering']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
218
-				$offset += 2;
219
-				$thisfile_bmp_header_raw['size1']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
220
-				$offset += 4;
221
-				$thisfile_bmp_header_raw['size2']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
222
-				$offset += 4;
223
-				$thisfile_bmp_header_raw['color_encoding']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
224
-				$offset += 4;
225
-				$thisfile_bmp_header_raw['identifier']       = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
226
-				$offset += 4;
227
-
228
-				$thisfile_bmp_header['compression']          = $this->BMPcompressionOS2Lookup($thisfile_bmp_header_raw['compression']);
229
-
230
-				$ThisFileInfo['video']['codec'] = $thisfile_bmp_header['compression'].' '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
231
-			}
232
-
233
-		} elseif ($thisfile_bmp['type_os'] == 'Windows') {
234
-
235
-			// Windows-format BMP
236
-
237
-			// BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
238
-			// all versions
239
-			// DWORD  biSize;
240
-			// LONG   biWidth;
241
-			// LONG   biHeight;
242
-			// WORD   biPlanes;
243
-			// WORD   biBitCount;
244
-			// DWORD  biCompression;
245
-			// DWORD  biSizeImage;
246
-			// LONG   biXPelsPerMeter;
247
-			// LONG   biYPelsPerMeter;
248
-			// DWORD  biClrUsed;
249
-			// DWORD  biClrImportant;
250
-
251
-			$thisfile_bmp_header_raw['width']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
252
-			$offset += 4;
253
-			$thisfile_bmp_header_raw['height']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
254
-			$offset += 4;
255
-			$thisfile_bmp_header_raw['planes']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
256
-			$offset += 2;
257
-			$thisfile_bmp_header_raw['bits_per_pixel']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
258
-			$offset += 2;
259
-			$thisfile_bmp_header_raw['compression']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
260
-			$offset += 4;
261
-			$thisfile_bmp_header_raw['bmp_data_size']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
262
-			$offset += 4;
263
-			$thisfile_bmp_header_raw['resolution_h']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
264
-			$offset += 4;
265
-			$thisfile_bmp_header_raw['resolution_v']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
266
-			$offset += 4;
267
-			$thisfile_bmp_header_raw['colors_used']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
268
-			$offset += 4;
269
-			$thisfile_bmp_header_raw['colors_important'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
270
-			$offset += 4;
271
-
272
-			$thisfile_bmp_header['compression'] = $this->BMPcompressionWindowsLookup($thisfile_bmp_header_raw['compression']);
273
-			$ThisFileInfo['video']['resolution_x']    = $thisfile_bmp_header_raw['width'];
274
-			$ThisFileInfo['video']['resolution_y']    = $thisfile_bmp_header_raw['height'];
275
-			$ThisFileInfo['video']['codec']           = $thisfile_bmp_header['compression'].' '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
276
-			$ThisFileInfo['video']['bits_per_sample'] = $thisfile_bmp_header_raw['bits_per_pixel'];
277
-
278
-			if (($thisfile_bmp['type_version'] >= 4) || ($thisfile_bmp_header_raw['compression'] == 3)) {
279
-				// should only be v4+, but BMPs with type_version==1 and BI_BITFIELDS compression have been seen
280
-				$BMPheader .= substr($BMPdata, $overalloffset, 44);
281
-				$overalloffset += 44;
282
-
283
-				// BITMAPV4HEADER - [44 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_2k1e.asp
284
-				// Win95+, WinNT4.0+
285
-				// DWORD        bV4RedMask;
286
-				// DWORD        bV4GreenMask;
287
-				// DWORD        bV4BlueMask;
288
-				// DWORD        bV4AlphaMask;
289
-				// DWORD        bV4CSType;
290
-				// CIEXYZTRIPLE bV4Endpoints;
291
-				// DWORD        bV4GammaRed;
292
-				// DWORD        bV4GammaGreen;
293
-				// DWORD        bV4GammaBlue;
294
-				$thisfile_bmp_header_raw['red_mask']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
295
-				$offset += 4;
296
-				$thisfile_bmp_header_raw['green_mask']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
297
-				$offset += 4;
298
-				$thisfile_bmp_header_raw['blue_mask']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
299
-				$offset += 4;
300
-				$thisfile_bmp_header_raw['alpha_mask']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
301
-				$offset += 4;
302
-				$thisfile_bmp_header_raw['cs_type']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
303
-				$offset += 4;
304
-				$thisfile_bmp_header_raw['ciexyz_red']   =                         substr($BMPheader, $offset, 4);
305
-				$offset += 4;
306
-				$thisfile_bmp_header_raw['ciexyz_green'] =                         substr($BMPheader, $offset, 4);
307
-				$offset += 4;
308
-				$thisfile_bmp_header_raw['ciexyz_blue']  =                         substr($BMPheader, $offset, 4);
309
-				$offset += 4;
310
-				$thisfile_bmp_header_raw['gamma_red']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
311
-				$offset += 4;
312
-				$thisfile_bmp_header_raw['gamma_green']  = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
313
-				$offset += 4;
314
-				$thisfile_bmp_header_raw['gamma_blue']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
315
-				$offset += 4;
316
-
317
-				$thisfile_bmp_header['ciexyz_red']   = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_red']));
318
-				$thisfile_bmp_header['ciexyz_green'] = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_green']));
319
-				$thisfile_bmp_header['ciexyz_blue']  = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_blue']));
320
-			}
321
-
322
-			if ($thisfile_bmp['type_version'] >= 5) {
323
-				$BMPheader .= substr($BMPdata, $overalloffset, 16);
324
-				$overalloffset += 16;
325
-
326
-				// BITMAPV5HEADER - [16 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_7c36.asp
327
-				// Win98+, Win2000+
328
-				// DWORD        bV5Intent;
329
-				// DWORD        bV5ProfileData;
330
-				// DWORD        bV5ProfileSize;
331
-				// DWORD        bV5Reserved;
332
-				$thisfile_bmp_header_raw['intent']              = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
333
-				$offset += 4;
334
-				$thisfile_bmp_header_raw['profile_data_offset'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
335
-				$offset += 4;
336
-				$thisfile_bmp_header_raw['profile_data_size']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
337
-				$offset += 4;
338
-				$thisfile_bmp_header_raw['reserved3']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
339
-				$offset += 4;
340
-			}
341
-
342
-		} else {
343
-
344
-			$ThisFileInfo['error'][] = 'Unknown BMP format in header.';
345
-			return false;
346
-
347
-		}
348
-
349
-		if ($ExtractPalette || $ExtractData) {
350
-			$PaletteEntries = 0;
351
-			if ($thisfile_bmp_header_raw['bits_per_pixel'] < 16) {
352
-				$PaletteEntries = pow(2, $thisfile_bmp_header_raw['bits_per_pixel']);
353
-			} elseif (isset($thisfile_bmp_header_raw['colors_used']) && ($thisfile_bmp_header_raw['colors_used'] > 0) && ($thisfile_bmp_header_raw['colors_used'] <= 256)) {
354
-				$PaletteEntries = $thisfile_bmp_header_raw['colors_used'];
355
-			}
356
-			if ($PaletteEntries > 0) {
357
-				$BMPpalette = substr($BMPdata, $overalloffset, 4 * $PaletteEntries);
358
-				$overalloffset += 4 * $PaletteEntries;
359
-
360
-				$paletteoffset = 0;
361
-				for ($i = 0; $i < $PaletteEntries; $i++) {
362
-					// RGBQUAD          - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_5f8y.asp
363
-					// BYTE    rgbBlue;
364
-					// BYTE    rgbGreen;
365
-					// BYTE    rgbRed;
366
-					// BYTE    rgbReserved;
367
-					$blue  = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
368
-					$green = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
369
-					$red   = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
370
-					if (($thisfile_bmp['type_os'] == 'OS/2') && ($thisfile_bmp['type_version'] == 1)) {
371
-						// no padding byte
372
-					} else {
373
-						$paletteoffset++; // padding byte
374
-					}
375
-					$thisfile_bmp['palette'][$i] = (($red << 16) | ($green << 8) | ($blue));
376
-				}
377
-			}
378
-		}
379
-
380
-		if ($ExtractData) {
381
-			$RowByteLength = ceil(($thisfile_bmp_header_raw['width'] * ($thisfile_bmp_header_raw['bits_per_pixel'] / 8)) / 4) * 4; // round up to nearest DWORD boundary
382
-
383
-			$BMPpixelData = substr($BMPdata, $thisfile_bmp_header_raw['data_offset'], $thisfile_bmp_header_raw['height'] * $RowByteLength);
384
-			$overalloffset = $thisfile_bmp_header_raw['data_offset'] + ($thisfile_bmp_header_raw['height'] * $RowByteLength);
385
-
386
-			$pixeldataoffset = 0;
387
-			switch (@$thisfile_bmp_header_raw['compression']) {
388
-
389
-				case 0: // BI_RGB
390
-					switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
391
-						case 1:
392
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
393
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col = $col) {
394
-									$paletteindexbyte = ord($BMPpixelData{$pixeldataoffset++});
395
-									for ($i = 7; $i >= 0; $i--) {
396
-										$paletteindex = ($paletteindexbyte & (0x01 << $i)) >> $i;
397
-										$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
398
-										$col++;
399
-									}
400
-								}
401
-								while (($pixeldataoffset % 4) != 0) {
402
-									// lines are padded to nearest DWORD
403
-									$pixeldataoffset++;
404
-								}
405
-							}
406
-							break;
407
-
408
-						case 4:
409
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
410
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col = $col) {
411
-									$paletteindexbyte = ord($BMPpixelData{$pixeldataoffset++});
412
-									for ($i = 1; $i >= 0; $i--) {
413
-										$paletteindex = ($paletteindexbyte & (0x0F << (4 * $i))) >> (4 * $i);
414
-										$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
415
-										$col++;
416
-									}
417
-								}
418
-								while (($pixeldataoffset % 4) != 0) {
419
-									// lines are padded to nearest DWORD
420
-									$pixeldataoffset++;
421
-								}
422
-							}
423
-							break;
424
-
425
-						case 8:
426
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
427
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
428
-									$paletteindex = ord($BMPpixelData{$pixeldataoffset++});
429
-									$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
430
-								}
431
-								while (($pixeldataoffset % 4) != 0) {
432
-									// lines are padded to nearest DWORD
433
-									$pixeldataoffset++;
434
-								}
435
-							}
436
-							break;
437
-
438
-						case 24:
439
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
440
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
441
-									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
442
-									$pixeldataoffset += 3;
443
-								}
444
-								while (($pixeldataoffset % 4) != 0) {
445
-									// lines are padded to nearest DWORD
446
-									$pixeldataoffset++;
447
-								}
448
-							}
449
-							break;
450
-
451
-						case 32:
452
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
453
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
454
-									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+3}) << 24) | (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
455
-									$pixeldataoffset += 4;
456
-								}
457
-								while (($pixeldataoffset % 4) != 0) {
458
-									// lines are padded to nearest DWORD
459
-									$pixeldataoffset++;
460
-								}
461
-							}
462
-							break;
463
-
464
-						case 16:
465
-							// ?
466
-							break;
467
-
468
-						default:
469
-							$ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
470
-							break;
471
-					}
472
-					break;
473
-
474
-
475
-				case 1: // BI_RLE8 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
476
-					switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
477
-						case 8:
478
-							$pixelcounter = 0;
479
-							while ($pixeldataoffset < strlen($BMPpixelData)) {
480
-								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
481
-								$secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
482
-								if ($firstbyte == 0) {
483
-
484
-									// escaped/absolute mode - the first byte of the pair can be set to zero to
485
-									// indicate an escape character that denotes the end of a line, the end of
486
-									// a bitmap, or a delta, depending on the value of the second byte.
487
-									switch ($secondbyte) {
488
-										case 0:
489
-											// end of line
490
-											// no need for special processing, just ignore
491
-											break;
492
-
493
-										case 1:
494
-											// end of bitmap
495
-											$pixeldataoffset = strlen($BMPpixelData); // force to exit loop just in case
496
-											break;
497
-
498
-										case 2:
499
-											// delta - The 2 bytes following the escape contain unsigned values
500
-											// indicating the horizontal and vertical offsets of the next pixel
501
-											// from the current position.
502
-											$colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
503
-											$rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
504
-											$col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
505
-											$row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
506
-											$pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
507
-											break;
508
-
509
-										default:
510
-											// In absolute mode, the first byte is zero and the second byte is a
511
-											// value in the range 03H through FFH. The second byte represents the
512
-											// number of bytes that follow, each of which contains the color index
513
-											// of a single pixel. Each run must be aligned on a word boundary.
514
-											for ($i = 0; $i < $secondbyte; $i++) {
515
-												$paletteindex = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
516
-												$col = $pixelcounter % $thisfile_bmp_header_raw['width'];
517
-												$row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
518
-												$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
519
-												$pixelcounter++;
520
-											}
521
-											while (($pixeldataoffset % 2) != 0) {
522
-												// Each run must be aligned on a word boundary.
523
-												$pixeldataoffset++;
524
-											}
525
-											break;
526
-									}
527
-
528
-								} else {
529
-
530
-									// encoded mode - the first byte specifies the number of consecutive pixels
531
-									// to be drawn using the color index contained in the second byte.
532
-									for ($i = 0; $i < $firstbyte; $i++) {
533
-										$col = $pixelcounter % $thisfile_bmp_header_raw['width'];
534
-										$row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
535
-										$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$secondbyte];
536
-										$pixelcounter++;
537
-									}
538
-
539
-								}
540
-							}
541
-							break;
542
-
543
-						default:
544
-							$ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
545
-							break;
546
-					}
547
-					break;
548
-
549
-
550
-
551
-				case 2: // BI_RLE4 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
552
-					switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
553
-						case 4:
554
-							$pixelcounter = 0;
555
-							while ($pixeldataoffset < strlen($BMPpixelData)) {
556
-								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
557
-								$secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
558
-								if ($firstbyte == 0) {
559
-
560
-									// escaped/absolute mode - the first byte of the pair can be set to zero to
561
-									// indicate an escape character that denotes the end of a line, the end of
562
-									// a bitmap, or a delta, depending on the value of the second byte.
563
-									switch ($secondbyte) {
564
-										case 0:
565
-											// end of line
566
-											// no need for special processing, just ignore
567
-											break;
568
-
569
-										case 1:
570
-											// end of bitmap
571
-											$pixeldataoffset = strlen($BMPpixelData); // force to exit loop just in case
572
-											break;
573
-
574
-										case 2:
575
-											// delta - The 2 bytes following the escape contain unsigned values
576
-											// indicating the horizontal and vertical offsets of the next pixel
577
-											// from the current position.
578
-											$colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
579
-											$rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
580
-											$col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
581
-											$row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
582
-											$pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
583
-											break;
584
-
585
-										default:
586
-											// In absolute mode, the first byte is zero. The second byte contains the number
587
-											// of color indexes that follow. Subsequent bytes contain color indexes in their
588
-											// high- and low-order 4 bits, one color index for each pixel. In absolute mode,
589
-											// each run must be aligned on a word boundary.
590
-											$paletteindexes = array();
591
-											for ($i = 0, $iMax = ceil($secondbyte / 2); $i < $iMax; $i++) {
592
-												$paletteindexbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
593
-												$paletteindexes[] = ($paletteindexbyte & 0xF0) >> 4;
594
-												$paletteindexes[] = ($paletteindexbyte & 0x0F);
595
-											}
596
-											while (($pixeldataoffset % 2) != 0) {
597
-												// Each run must be aligned on a word boundary.
598
-												$pixeldataoffset++;
599
-											}
600
-
601
-											foreach ($paletteindexes as $dummy => $paletteindex) {
602
-												$col = $pixelcounter % $thisfile_bmp_header_raw['width'];
603
-												$row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
604
-												$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
605
-												$pixelcounter++;
606
-											}
607
-											break;
608
-									}
609
-
610
-								} else {
611
-
612
-									// encoded mode - the first byte of the pair contains the number of pixels to be
613
-									// drawn using the color indexes in the second byte. The second byte contains two
614
-									// color indexes, one in its high-order 4 bits and one in its low-order 4 bits.
615
-									// The first of the pixels is drawn using the color specified by the high-order
616
-									// 4 bits, the second is drawn using the color in the low-order 4 bits, the third
617
-									// is drawn using the color in the high-order 4 bits, and so on, until all the
618
-									// pixels specified by the first byte have been drawn.
619
-									$paletteindexes[0] = ($secondbyte & 0xF0) >> 4;
620
-									$paletteindexes[1] = ($secondbyte & 0x0F);
621
-									for ($i = 0; $i < $firstbyte; $i++) {
622
-										$col = $pixelcounter % $thisfile_bmp_header_raw['width'];
623
-										$row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
624
-										$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindexes[($i % 2)]];
625
-										$pixelcounter++;
626
-									}
627
-
628
-								}
629
-							}
630
-							break;
631
-
632
-						default:
633
-							$ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
634
-							break;
635
-					}
636
-					break;
637
-
638
-
639
-				case 3: // BI_BITFIELDS
640
-					switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
641
-						case 16:
642
-						case 32:
643
-							$redshift   = 0;
644
-							$greenshift = 0;
645
-							$blueshift  = 0;
646
-							if (!$thisfile_bmp_header_raw['red_mask'] || !$thisfile_bmp_header_raw['green_mask'] || !$thisfile_bmp_header_raw['blue_mask']) {
647
-								$ThisFileInfo['error'][] = 'missing $thisfile_bmp_header_raw[(red|green|blue)_mask]';
648
-								return false;
649
-							}
650
-							while ((($thisfile_bmp_header_raw['red_mask'] >> $redshift) & 0x01) == 0) {
651
-								$redshift++;
652
-							}
653
-							while ((($thisfile_bmp_header_raw['green_mask'] >> $greenshift) & 0x01) == 0) {
654
-								$greenshift++;
655
-							}
656
-							while ((($thisfile_bmp_header_raw['blue_mask'] >> $blueshift) & 0x01) == 0) {
657
-								$blueshift++;
658
-							}
659
-							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
660
-								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
661
-									$pixelvalue = $this->LittleEndian2Int(substr($BMPpixelData, $pixeldataoffset, $thisfile_bmp_header_raw['bits_per_pixel'] / 8));
662
-									$pixeldataoffset += $thisfile_bmp_header_raw['bits_per_pixel'] / 8;
663
-
664
-									$red   = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'red_mask'])   >> $redshift)   / ($thisfile_bmp_header_raw[ 'red_mask']   >> $redshift))   * 255);
665
-									$green = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'green_mask']) >> $greenshift) / ($thisfile_bmp_header_raw[ 'green_mask'] >> $greenshift)) * 255);
666
-									$blue  = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'blue_mask'])  >> $blueshift)  / ($thisfile_bmp_header_raw[ 'blue_mask']  >> $blueshift))  * 255);
667
-									$thisfile_bmp['data'][$row][$col] = (($red << 16) | ($green << 8) | ($blue));
668
-								}
669
-								while (($pixeldataoffset % 4) != 0) {
670
-									// lines are padded to nearest DWORD
671
-									$pixeldataoffset++;
672
-								}
673
-							}
674
-							break;
675
-
676
-						default:
677
-							$ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
678
-							break;
679
-					}
680
-					break;
681
-
682
-
683
-				default: // unhandled compression type
684
-					$ThisFileInfo['error'][] = 'Unknown/unhandled compression type value ('.$thisfile_bmp_header_raw['compression'].') - cannot decompress pixel data';
685
-					break;
686
-			}
687
-		}
688
-
689
-		return true;
690
-	}
691
-
692
-	public function IntColor2RGB($color) {
693
-		$red   = ($color & 0x00FF0000) >> 16;
694
-		$green = ($color & 0x0000FF00) >> 8;
695
-		$blue  = ($color & 0x000000FF);
696
-		return array($red, $green, $blue);
697
-	}
698
-
699
-	public function PlotPixelsGD(&$BMPdata, $truecolor=true) {
700
-		$imagewidth  = $BMPdata['header']['raw']['width'];
701
-		$imageheight = $BMPdata['header']['raw']['height'];
702
-
703
-		if ($truecolor) {
704
-
705
-			$gd = @imagecreatetruecolor($imagewidth, $imageheight);
706
-
707
-		} else {
708
-
709
-			$gd = @imagecreate($imagewidth, $imageheight);
710
-			if (!empty($BMPdata['palette'])) {
711
-				// create GD palette from BMP palette
712
-				foreach ($BMPdata['palette'] as $dummy => $color) {
713
-					list($r, $g, $b) = $this->IntColor2RGB($color);
714
-					imagecolorallocate($gd, $r, $g, $b);
715
-				}
716
-			} else {
717
-				// create 216-color websafe palette
718
-				for ($r = 0x00; $r <= 0xFF; $r += 0x33) {
719
-					for ($g = 0x00; $g <= 0xFF; $g += 0x33) {
720
-						for ($b = 0x00; $b <= 0xFF; $b += 0x33) {
721
-							imagecolorallocate($gd, $r, $g, $b);
722
-						}
723
-					}
724
-				}
725
-			}
726
-
727
-		}
728
-		if (!is_resource($gd)) {
729
-			return false;
730
-		}
731
-
732
-		foreach ($BMPdata['data'] as $row => $colarray) {
733
-			if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
734
-				set_time_limit(30);
735
-			}
736
-			foreach ($colarray as $col => $color) {
737
-				list($red, $green, $blue) = $this->IntColor2RGB($color);
738
-				if ($truecolor) {
739
-					$pixelcolor = imagecolorallocate($gd, $red, $green, $blue);
740
-				} else {
741
-					$pixelcolor = imagecolorclosest($gd, $red, $green, $blue);
742
-				}
743
-				imagesetpixel($gd, $col, $row, $pixelcolor);
744
-			}
745
-		}
746
-		return $gd;
747
-	}
748
-
749
-	public function PlotBMP(&$BMPinfo) {
750
-		$starttime = time();
751
-		if (!isset($BMPinfo['bmp']['data']) || !is_array($BMPinfo['bmp']['data'])) {
752
-			echo 'ERROR: no pixel data<BR>';
753
-			return false;
754
-		}
755
-		if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
756
-			set_time_limit((int) round($BMPinfo[ 'resolution_x'] * $BMPinfo[ 'resolution_y'] / 10000));
757
-		}
758
-		$im = $this->PlotPixelsGD($BMPinfo['bmp']);
759
-		if (headers_sent()) {
760
-			echo 'plotted '.($BMPinfo['resolution_x'] * $BMPinfo['resolution_y']).' pixels in '.(time() - $starttime).' seconds<BR>';
761
-			imagedestroy($im);
762
-			exit;
763
-		}
764
-		header('Content-Type: image/png');
765
-		imagepng($im);
766
-		imagedestroy($im);
767
-		return true;
768
-	}
769
-
770
-	public function BMPcompressionWindowsLookup($compressionid) {
771
-		static $BMPcompressionWindowsLookup = array(
772
-			0 => 'BI_RGB',
773
-			1 => 'BI_RLE8',
774
-			2 => 'BI_RLE4',
775
-			3 => 'BI_BITFIELDS',
776
-			4 => 'BI_JPEG',
777
-			5 => 'BI_PNG'
778
-		);
779
-		return (isset($BMPcompressionWindowsLookup[$compressionid]) ? $BMPcompressionWindowsLookup[$compressionid] : 'invalid');
780
-	}
781
-
782
-	public function BMPcompressionOS2Lookup($compressionid) {
783
-		static $BMPcompressionOS2Lookup = array(
784
-			0 => 'BI_RGB',
785
-			1 => 'BI_RLE8',
786
-			2 => 'BI_RLE4',
787
-			3 => 'Huffman 1D',
788
-			4 => 'BI_RLE24',
789
-		);
790
-		return (isset($BMPcompressionOS2Lookup[$compressionid]) ? $BMPcompressionOS2Lookup[$compressionid] : 'invalid');
791
-	}
792
-
793
-
794
-	// from getid3.lib.php
795
-
796
-	public function trunc($floatnumber) {
797
-		// truncates a floating-point number at the decimal point
798
-		// returns int (if possible, otherwise float)
799
-		if ($floatnumber >= 1) {
800
-			$truncatednumber = floor($floatnumber);
801
-		} elseif ($floatnumber <= -1) {
802
-			$truncatednumber = ceil($floatnumber);
803
-		} else {
804
-			$truncatednumber = 0;
805
-		}
806
-		if ($truncatednumber <= 1073741824) { // 2^30
807
-			$truncatednumber = (int) $truncatednumber;
808
-		}
809
-		return $truncatednumber;
810
-	}
811
-
812
-	public function LittleEndian2Int($byteword) {
813
-		$intvalue = 0;
814
-		$byteword = strrev($byteword);
815
-		$bytewordlen = strlen($byteword);
816
-		for ($i = 0; $i < $bytewordlen; $i++) {
817
-			$intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
818
-		}
819
-		return $intvalue;
820
-	}
821
-
822
-	public function BigEndian2Int($byteword) {
823
-		return $this->LittleEndian2Int(strrev($byteword));
824
-	}
825
-
826
-	public function BigEndian2Bin($byteword) {
827
-		$binvalue = '';
828
-		$bytewordlen = strlen($byteword);
829
-		for ($i = 0; $i < $bytewordlen; $i++) {
830
-			$binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
831
-		}
832
-		return $binvalue;
833
-	}
834
-
835
-	public function FixedPoint2_30($rawdata) {
836
-		$binarystring = $this->BigEndian2Bin($rawdata);
837
-		return $this->Bin2Dec(substr($binarystring, 0, 2)) + (float) ($this->Bin2Dec(substr($binarystring, 2, 30)) / 1073741824);
838
-	}
839
-
840
-	public function Bin2Dec($binstring, $signed=false) {
841
-		$signmult = 1;
842
-		if ($signed) {
843
-			if ($binstring{0} == '1') {
844
-				$signmult = -1;
845
-			}
846
-			$binstring = substr($binstring, 1);
847
-		}
848
-		$decvalue = 0;
849
-		for ($i = 0, $iMax = strlen($binstring); $i < $iMax; $i++) {
850
-			$decvalue += ((int) $binstring[ strlen($binstring) - $i - 1 ]) * pow(2, $i);
851
-		}
852
-		return $this->CastAsInt($decvalue * $signmult);
853
-	}
854
-
855
-	public function CastAsInt($floatnum) {
856
-		// convert to float if not already
857
-		$floatnum = (float) $floatnum;
858
-
859
-		// convert a float to type int, only if possible
860
-		if ($this->trunc($floatnum) == $floatnum) {
861
-			// it's not floating point
862
-			if ($floatnum <= 1073741824) { // 2^30
863
-				// it's within int range
864
-				$floatnum = (int) $floatnum;
865
-			}
866
-		}
867
-		return $floatnum;
868
-	}
23
+    public function phpthumb_bmp2gd(&$BMPdata, $truecolor=true) {
24
+        $ThisFileInfo = array();
25
+        if ($this->getid3_bmp($BMPdata, $ThisFileInfo, true, true)) {
26
+            $gd = $this->PlotPixelsGD($ThisFileInfo['bmp'], $truecolor);
27
+            return $gd;
28
+        }
29
+        return false;
30
+    }
31
+
32
+    public function phpthumb_bmpfile2gd($filename, $truecolor=true) {
33
+        if ($fp = @fopen($filename, 'rb')) {
34
+            $BMPdata = fread($fp, filesize($filename));
35
+            fclose($fp);
36
+            return $this->phpthumb_bmp2gd($BMPdata, $truecolor);
37
+        }
38
+        return false;
39
+    }
40
+
41
+    public function GD2BMPstring(&$gd_image) {
42
+        $imageX = imagesx($gd_image);
43
+        $imageY = imagesy($gd_image);
44
+
45
+        $BMP = '';
46
+        for ($y = ($imageY - 1); $y >= 0; $y--) {
47
+            $thisline = '';
48
+            for ($x = 0; $x < $imageX; $x++) {
49
+                $argb = phpthumb_functions::GetPixelColor($gd_image, $x, $y);
50
+                $thisline .= chr($argb['blue']).chr($argb['green']).chr($argb['red']);
51
+            }
52
+            while (strlen($thisline) % 4) {
53
+                $thisline .= "\x00";
54
+            }
55
+            $BMP .= $thisline;
56
+        }
57
+
58
+        $bmpSize = strlen($BMP) + 14 + 40;
59
+        // BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
60
+        $BITMAPFILEHEADER  = 'BM';                                                           // WORD    bfType;
61
+        $BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String($bmpSize, 4); // DWORD   bfSize;
62
+        $BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved1;
63
+        $BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved2;
64
+        $BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(      54, 4); // DWORD   bfOffBits;
65
+
66
+        // BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
67
+        $BITMAPINFOHEADER  = phpthumb_functions::LittleEndian2String(      40, 4); // DWORD  biSize;
68
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageX, 4); // LONG   biWidth;
69
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageY, 4); // LONG   biHeight;
70
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       1, 2); // WORD   biPlanes;
71
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(      24, 2); // WORD   biBitCount;
72
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biCompression;
73
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biSizeImage;
74
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biXPelsPerMeter;
75
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biYPelsPerMeter;
76
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrUsed;
77
+        $BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrImportant;
78
+
79
+        return $BITMAPFILEHEADER.$BITMAPINFOHEADER.$BMP;
80
+    }
81
+
82
+    public function getid3_bmp(&$BMPdata, &$ThisFileInfo, $ExtractPalette=false, $ExtractData=false) {
83
+
84
+        // shortcuts
85
+        $ThisFileInfo['bmp']['header']['raw'] = array();
86
+        $thisfile_bmp                         = &$ThisFileInfo['bmp'];
87
+        $thisfile_bmp_header                  = &$thisfile_bmp['header'];
88
+        $thisfile_bmp_header_raw              = &$thisfile_bmp_header['raw'];
89
+
90
+        // BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
91
+        // all versions
92
+        // WORD    bfType;
93
+        // DWORD   bfSize;
94
+        // WORD    bfReserved1;
95
+        // WORD    bfReserved2;
96
+        // DWORD   bfOffBits;
97
+
98
+        $offset = 0;
99
+        $overalloffset = 0;
100
+        $BMPheader = substr($BMPdata, $overalloffset, 14 + 40);
101
+        $overalloffset += (14 + 40);
102
+
103
+        $thisfile_bmp_header_raw['identifier']  = substr($BMPheader, $offset, 2);
104
+        $offset += 2;
105
+
106
+        if ($thisfile_bmp_header_raw['identifier'] != 'BM') {
107
+            $ThisFileInfo['error'][] = 'Expecting "BM" at offset '. (int) (@$ThisFileInfo[ 'avdataoffset']) .', found "'. $thisfile_bmp_header_raw[ 'identifier'].'"';
108
+            unset($ThisFileInfo['fileformat']);
109
+            unset($ThisFileInfo['bmp']);
110
+            return false;
111
+        }
112
+
113
+        $thisfile_bmp_header_raw['filesize']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
114
+        $offset += 4;
115
+        $thisfile_bmp_header_raw['reserved1']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
116
+        $offset += 2;
117
+        $thisfile_bmp_header_raw['reserved2']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
118
+        $offset += 2;
119
+        $thisfile_bmp_header_raw['data_offset'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
120
+        $offset += 4;
121
+        $thisfile_bmp_header_raw['header_size'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
122
+        $offset += 4;
123
+
124
+
125
+        // check if the hardcoded-to-1 "planes" is at offset 22 or 26
126
+        $planes22 = $this->LittleEndian2Int(substr($BMPheader, 22, 2));
127
+        $planes26 = $this->LittleEndian2Int(substr($BMPheader, 26, 2));
128
+        if (($planes22 == 1) && ($planes26 != 1)) {
129
+            $thisfile_bmp['type_os']      = 'OS/2';
130
+            $thisfile_bmp['type_version'] = 1;
131
+        } elseif (($planes26 == 1) && ($planes22 != 1)) {
132
+            $thisfile_bmp['type_os']      = 'Windows';
133
+            $thisfile_bmp['type_version'] = 1;
134
+        } elseif ($thisfile_bmp_header_raw['header_size'] == 12) {
135
+            $thisfile_bmp['type_os']      = 'OS/2';
136
+            $thisfile_bmp['type_version'] = 1;
137
+        } elseif ($thisfile_bmp_header_raw['header_size'] == 40) {
138
+            $thisfile_bmp['type_os']      = 'Windows';
139
+            $thisfile_bmp['type_version'] = 1;
140
+        } elseif ($thisfile_bmp_header_raw['header_size'] == 84) {
141
+            $thisfile_bmp['type_os']      = 'Windows';
142
+            $thisfile_bmp['type_version'] = 4;
143
+        } elseif ($thisfile_bmp_header_raw['header_size'] == 100) {
144
+            $thisfile_bmp['type_os']      = 'Windows';
145
+            $thisfile_bmp['type_version'] = 5;
146
+        } else {
147
+            $ThisFileInfo['error'][] = 'Unknown BMP subtype (or not a BMP file)';
148
+            unset($ThisFileInfo['fileformat']);
149
+            unset($ThisFileInfo['bmp']);
150
+            return false;
151
+        }
152
+
153
+        $ThisFileInfo['fileformat']                  = 'bmp';
154
+        $ThisFileInfo['video']['dataformat']         = 'bmp';
155
+        $ThisFileInfo['video']['lossless']           = true;
156
+        $ThisFileInfo['video']['pixel_aspect_ratio'] = (float) 1;
157
+
158
+        if ($thisfile_bmp['type_os'] == 'OS/2') {
159
+
160
+            // OS/2-format BMP
161
+            // http://netghost.narod.ru/gff/graphics/summary/os2bmp.htm
162
+
163
+            // DWORD  Size;             /* Size of this structure in bytes */
164
+            // DWORD  Width;            /* Bitmap width in pixels */
165
+            // DWORD  Height;           /* Bitmap height in pixel */
166
+            // WORD   NumPlanes;        /* Number of bit planes (color depth) */
167
+            // WORD   BitsPerPixel;     /* Number of bits per pixel per plane */
168
+
169
+            $thisfile_bmp_header_raw['width']          = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
170
+            $offset += 2;
171
+            $thisfile_bmp_header_raw['height']         = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
172
+            $offset += 2;
173
+            $thisfile_bmp_header_raw['planes']         = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
174
+            $offset += 2;
175
+            $thisfile_bmp_header_raw['bits_per_pixel'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
176
+            $offset += 2;
177
+
178
+            $ThisFileInfo['video']['resolution_x']    = $thisfile_bmp_header_raw['width'];
179
+            $ThisFileInfo['video']['resolution_y']    = $thisfile_bmp_header_raw['height'];
180
+            $ThisFileInfo['video']['codec']           = 'BI_RGB '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
181
+            $ThisFileInfo['video']['bits_per_sample'] = $thisfile_bmp_header_raw['bits_per_pixel'];
182
+
183
+            if ($thisfile_bmp['type_version'] >= 2) {
184
+                // DWORD  Compression;      /* Bitmap compression scheme */
185
+                // DWORD  ImageDataSize;    /* Size of bitmap data in bytes */
186
+                // DWORD  XResolution;      /* X resolution of display device */
187
+                // DWORD  YResolution;      /* Y resolution of display device */
188
+                // DWORD  ColorsUsed;       /* Number of color table indices used */
189
+                // DWORD  ColorsImportant;  /* Number of important color indices */
190
+                // WORD   Units;            /* Type of units used to measure resolution */
191
+                // WORD   Reserved;         /* Pad structure to 4-byte boundary */
192
+                // WORD   Recording;        /* Recording algorithm */
193
+                // WORD   Rendering;        /* Halftoning algorithm used */
194
+                // DWORD  Size1;            /* Reserved for halftoning algorithm use */
195
+                // DWORD  Size2;            /* Reserved for halftoning algorithm use */
196
+                // DWORD  ColorEncoding;    /* Color model used in bitmap */
197
+                // DWORD  Identifier;       /* Reserved for application use */
198
+
199
+                $thisfile_bmp_header_raw['compression']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
200
+                $offset += 4;
201
+                $thisfile_bmp_header_raw['bmp_data_size']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
202
+                $offset += 4;
203
+                $thisfile_bmp_header_raw['resolution_h']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
204
+                $offset += 4;
205
+                $thisfile_bmp_header_raw['resolution_v']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
206
+                $offset += 4;
207
+                $thisfile_bmp_header_raw['colors_used']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
208
+                $offset += 4;
209
+                $thisfile_bmp_header_raw['colors_important'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
210
+                $offset += 4;
211
+                $thisfile_bmp_header_raw['resolution_units'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
212
+                $offset += 2;
213
+                $thisfile_bmp_header_raw['reserved1']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
214
+                $offset += 2;
215
+                $thisfile_bmp_header_raw['recording']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
216
+                $offset += 2;
217
+                $thisfile_bmp_header_raw['rendering']        = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
218
+                $offset += 2;
219
+                $thisfile_bmp_header_raw['size1']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
220
+                $offset += 4;
221
+                $thisfile_bmp_header_raw['size2']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
222
+                $offset += 4;
223
+                $thisfile_bmp_header_raw['color_encoding']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
224
+                $offset += 4;
225
+                $thisfile_bmp_header_raw['identifier']       = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
226
+                $offset += 4;
227
+
228
+                $thisfile_bmp_header['compression']          = $this->BMPcompressionOS2Lookup($thisfile_bmp_header_raw['compression']);
229
+
230
+                $ThisFileInfo['video']['codec'] = $thisfile_bmp_header['compression'].' '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
231
+            }
232
+
233
+        } elseif ($thisfile_bmp['type_os'] == 'Windows') {
234
+
235
+            // Windows-format BMP
236
+
237
+            // BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
238
+            // all versions
239
+            // DWORD  biSize;
240
+            // LONG   biWidth;
241
+            // LONG   biHeight;
242
+            // WORD   biPlanes;
243
+            // WORD   biBitCount;
244
+            // DWORD  biCompression;
245
+            // DWORD  biSizeImage;
246
+            // LONG   biXPelsPerMeter;
247
+            // LONG   biYPelsPerMeter;
248
+            // DWORD  biClrUsed;
249
+            // DWORD  biClrImportant;
250
+
251
+            $thisfile_bmp_header_raw['width']            = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
252
+            $offset += 4;
253
+            $thisfile_bmp_header_raw['height']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
254
+            $offset += 4;
255
+            $thisfile_bmp_header_raw['planes']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
256
+            $offset += 2;
257
+            $thisfile_bmp_header_raw['bits_per_pixel']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 2));
258
+            $offset += 2;
259
+            $thisfile_bmp_header_raw['compression']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
260
+            $offset += 4;
261
+            $thisfile_bmp_header_raw['bmp_data_size']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
262
+            $offset += 4;
263
+            $thisfile_bmp_header_raw['resolution_h']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
264
+            $offset += 4;
265
+            $thisfile_bmp_header_raw['resolution_v']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
266
+            $offset += 4;
267
+            $thisfile_bmp_header_raw['colors_used']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
268
+            $offset += 4;
269
+            $thisfile_bmp_header_raw['colors_important'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
270
+            $offset += 4;
271
+
272
+            $thisfile_bmp_header['compression'] = $this->BMPcompressionWindowsLookup($thisfile_bmp_header_raw['compression']);
273
+            $ThisFileInfo['video']['resolution_x']    = $thisfile_bmp_header_raw['width'];
274
+            $ThisFileInfo['video']['resolution_y']    = $thisfile_bmp_header_raw['height'];
275
+            $ThisFileInfo['video']['codec']           = $thisfile_bmp_header['compression'].' '.$thisfile_bmp_header_raw['bits_per_pixel'].'-bit';
276
+            $ThisFileInfo['video']['bits_per_sample'] = $thisfile_bmp_header_raw['bits_per_pixel'];
277
+
278
+            if (($thisfile_bmp['type_version'] >= 4) || ($thisfile_bmp_header_raw['compression'] == 3)) {
279
+                // should only be v4+, but BMPs with type_version==1 and BI_BITFIELDS compression have been seen
280
+                $BMPheader .= substr($BMPdata, $overalloffset, 44);
281
+                $overalloffset += 44;
282
+
283
+                // BITMAPV4HEADER - [44 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_2k1e.asp
284
+                // Win95+, WinNT4.0+
285
+                // DWORD        bV4RedMask;
286
+                // DWORD        bV4GreenMask;
287
+                // DWORD        bV4BlueMask;
288
+                // DWORD        bV4AlphaMask;
289
+                // DWORD        bV4CSType;
290
+                // CIEXYZTRIPLE bV4Endpoints;
291
+                // DWORD        bV4GammaRed;
292
+                // DWORD        bV4GammaGreen;
293
+                // DWORD        bV4GammaBlue;
294
+                $thisfile_bmp_header_raw['red_mask']     = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
295
+                $offset += 4;
296
+                $thisfile_bmp_header_raw['green_mask']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
297
+                $offset += 4;
298
+                $thisfile_bmp_header_raw['blue_mask']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
299
+                $offset += 4;
300
+                $thisfile_bmp_header_raw['alpha_mask']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
301
+                $offset += 4;
302
+                $thisfile_bmp_header_raw['cs_type']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
303
+                $offset += 4;
304
+                $thisfile_bmp_header_raw['ciexyz_red']   =                         substr($BMPheader, $offset, 4);
305
+                $offset += 4;
306
+                $thisfile_bmp_header_raw['ciexyz_green'] =                         substr($BMPheader, $offset, 4);
307
+                $offset += 4;
308
+                $thisfile_bmp_header_raw['ciexyz_blue']  =                         substr($BMPheader, $offset, 4);
309
+                $offset += 4;
310
+                $thisfile_bmp_header_raw['gamma_red']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
311
+                $offset += 4;
312
+                $thisfile_bmp_header_raw['gamma_green']  = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
313
+                $offset += 4;
314
+                $thisfile_bmp_header_raw['gamma_blue']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
315
+                $offset += 4;
316
+
317
+                $thisfile_bmp_header['ciexyz_red']   = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_red']));
318
+                $thisfile_bmp_header['ciexyz_green'] = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_green']));
319
+                $thisfile_bmp_header['ciexyz_blue']  = $this->FixedPoint2_30(strrev($thisfile_bmp_header_raw['ciexyz_blue']));
320
+            }
321
+
322
+            if ($thisfile_bmp['type_version'] >= 5) {
323
+                $BMPheader .= substr($BMPdata, $overalloffset, 16);
324
+                $overalloffset += 16;
325
+
326
+                // BITMAPV5HEADER - [16 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_7c36.asp
327
+                // Win98+, Win2000+
328
+                // DWORD        bV5Intent;
329
+                // DWORD        bV5ProfileData;
330
+                // DWORD        bV5ProfileSize;
331
+                // DWORD        bV5Reserved;
332
+                $thisfile_bmp_header_raw['intent']              = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
333
+                $offset += 4;
334
+                $thisfile_bmp_header_raw['profile_data_offset'] = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
335
+                $offset += 4;
336
+                $thisfile_bmp_header_raw['profile_data_size']   = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
337
+                $offset += 4;
338
+                $thisfile_bmp_header_raw['reserved3']           = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
339
+                $offset += 4;
340
+            }
341
+
342
+        } else {
343
+
344
+            $ThisFileInfo['error'][] = 'Unknown BMP format in header.';
345
+            return false;
346
+
347
+        }
348
+
349
+        if ($ExtractPalette || $ExtractData) {
350
+            $PaletteEntries = 0;
351
+            if ($thisfile_bmp_header_raw['bits_per_pixel'] < 16) {
352
+                $PaletteEntries = pow(2, $thisfile_bmp_header_raw['bits_per_pixel']);
353
+            } elseif (isset($thisfile_bmp_header_raw['colors_used']) && ($thisfile_bmp_header_raw['colors_used'] > 0) && ($thisfile_bmp_header_raw['colors_used'] <= 256)) {
354
+                $PaletteEntries = $thisfile_bmp_header_raw['colors_used'];
355
+            }
356
+            if ($PaletteEntries > 0) {
357
+                $BMPpalette = substr($BMPdata, $overalloffset, 4 * $PaletteEntries);
358
+                $overalloffset += 4 * $PaletteEntries;
359
+
360
+                $paletteoffset = 0;
361
+                for ($i = 0; $i < $PaletteEntries; $i++) {
362
+                    // RGBQUAD          - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_5f8y.asp
363
+                    // BYTE    rgbBlue;
364
+                    // BYTE    rgbGreen;
365
+                    // BYTE    rgbRed;
366
+                    // BYTE    rgbReserved;
367
+                    $blue  = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
368
+                    $green = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
369
+                    $red   = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
370
+                    if (($thisfile_bmp['type_os'] == 'OS/2') && ($thisfile_bmp['type_version'] == 1)) {
371
+                        // no padding byte
372
+                    } else {
373
+                        $paletteoffset++; // padding byte
374
+                    }
375
+                    $thisfile_bmp['palette'][$i] = (($red << 16) | ($green << 8) | ($blue));
376
+                }
377
+            }
378
+        }
379
+
380
+        if ($ExtractData) {
381
+            $RowByteLength = ceil(($thisfile_bmp_header_raw['width'] * ($thisfile_bmp_header_raw['bits_per_pixel'] / 8)) / 4) * 4; // round up to nearest DWORD boundary
382
+
383
+            $BMPpixelData = substr($BMPdata, $thisfile_bmp_header_raw['data_offset'], $thisfile_bmp_header_raw['height'] * $RowByteLength);
384
+            $overalloffset = $thisfile_bmp_header_raw['data_offset'] + ($thisfile_bmp_header_raw['height'] * $RowByteLength);
385
+
386
+            $pixeldataoffset = 0;
387
+            switch (@$thisfile_bmp_header_raw['compression']) {
388
+
389
+                case 0: // BI_RGB
390
+                    switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
391
+                        case 1:
392
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
393
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col = $col) {
394
+                                    $paletteindexbyte = ord($BMPpixelData{$pixeldataoffset++});
395
+                                    for ($i = 7; $i >= 0; $i--) {
396
+                                        $paletteindex = ($paletteindexbyte & (0x01 << $i)) >> $i;
397
+                                        $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
398
+                                        $col++;
399
+                                    }
400
+                                }
401
+                                while (($pixeldataoffset % 4) != 0) {
402
+                                    // lines are padded to nearest DWORD
403
+                                    $pixeldataoffset++;
404
+                                }
405
+                            }
406
+                            break;
407
+
408
+                        case 4:
409
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
410
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col = $col) {
411
+                                    $paletteindexbyte = ord($BMPpixelData{$pixeldataoffset++});
412
+                                    for ($i = 1; $i >= 0; $i--) {
413
+                                        $paletteindex = ($paletteindexbyte & (0x0F << (4 * $i))) >> (4 * $i);
414
+                                        $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
415
+                                        $col++;
416
+                                    }
417
+                                }
418
+                                while (($pixeldataoffset % 4) != 0) {
419
+                                    // lines are padded to nearest DWORD
420
+                                    $pixeldataoffset++;
421
+                                }
422
+                            }
423
+                            break;
424
+
425
+                        case 8:
426
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
427
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
428
+                                    $paletteindex = ord($BMPpixelData{$pixeldataoffset++});
429
+                                    $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
430
+                                }
431
+                                while (($pixeldataoffset % 4) != 0) {
432
+                                    // lines are padded to nearest DWORD
433
+                                    $pixeldataoffset++;
434
+                                }
435
+                            }
436
+                            break;
437
+
438
+                        case 24:
439
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
440
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
441
+                                    $thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
442
+                                    $pixeldataoffset += 3;
443
+                                }
444
+                                while (($pixeldataoffset % 4) != 0) {
445
+                                    // lines are padded to nearest DWORD
446
+                                    $pixeldataoffset++;
447
+                                }
448
+                            }
449
+                            break;
450
+
451
+                        case 32:
452
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
453
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
454
+                                    $thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+3}) << 24) | (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
455
+                                    $pixeldataoffset += 4;
456
+                                }
457
+                                while (($pixeldataoffset % 4) != 0) {
458
+                                    // lines are padded to nearest DWORD
459
+                                    $pixeldataoffset++;
460
+                                }
461
+                            }
462
+                            break;
463
+
464
+                        case 16:
465
+                            // ?
466
+                            break;
467
+
468
+                        default:
469
+                            $ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
470
+                            break;
471
+                    }
472
+                    break;
473
+
474
+
475
+                case 1: // BI_RLE8 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
476
+                    switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
477
+                        case 8:
478
+                            $pixelcounter = 0;
479
+                            while ($pixeldataoffset < strlen($BMPpixelData)) {
480
+                                $firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
481
+                                $secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
482
+                                if ($firstbyte == 0) {
483
+
484
+                                    // escaped/absolute mode - the first byte of the pair can be set to zero to
485
+                                    // indicate an escape character that denotes the end of a line, the end of
486
+                                    // a bitmap, or a delta, depending on the value of the second byte.
487
+                                    switch ($secondbyte) {
488
+                                        case 0:
489
+                                            // end of line
490
+                                            // no need for special processing, just ignore
491
+                                            break;
492
+
493
+                                        case 1:
494
+                                            // end of bitmap
495
+                                            $pixeldataoffset = strlen($BMPpixelData); // force to exit loop just in case
496
+                                            break;
497
+
498
+                                        case 2:
499
+                                            // delta - The 2 bytes following the escape contain unsigned values
500
+                                            // indicating the horizontal and vertical offsets of the next pixel
501
+                                            // from the current position.
502
+                                            $colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
503
+                                            $rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
504
+                                            $col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
505
+                                            $row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
506
+                                            $pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
507
+                                            break;
508
+
509
+                                        default:
510
+                                            // In absolute mode, the first byte is zero and the second byte is a
511
+                                            // value in the range 03H through FFH. The second byte represents the
512
+                                            // number of bytes that follow, each of which contains the color index
513
+                                            // of a single pixel. Each run must be aligned on a word boundary.
514
+                                            for ($i = 0; $i < $secondbyte; $i++) {
515
+                                                $paletteindex = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
516
+                                                $col = $pixelcounter % $thisfile_bmp_header_raw['width'];
517
+                                                $row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
518
+                                                $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
519
+                                                $pixelcounter++;
520
+                                            }
521
+                                            while (($pixeldataoffset % 2) != 0) {
522
+                                                // Each run must be aligned on a word boundary.
523
+                                                $pixeldataoffset++;
524
+                                            }
525
+                                            break;
526
+                                    }
527
+
528
+                                } else {
529
+
530
+                                    // encoded mode - the first byte specifies the number of consecutive pixels
531
+                                    // to be drawn using the color index contained in the second byte.
532
+                                    for ($i = 0; $i < $firstbyte; $i++) {
533
+                                        $col = $pixelcounter % $thisfile_bmp_header_raw['width'];
534
+                                        $row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
535
+                                        $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$secondbyte];
536
+                                        $pixelcounter++;
537
+                                    }
538
+
539
+                                }
540
+                            }
541
+                            break;
542
+
543
+                        default:
544
+                            $ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
545
+                            break;
546
+                    }
547
+                    break;
548
+
549
+
550
+
551
+                case 2: // BI_RLE4 - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_6x0u.asp
552
+                    switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
553
+                        case 4:
554
+                            $pixelcounter = 0;
555
+                            while ($pixeldataoffset < strlen($BMPpixelData)) {
556
+                                $firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
557
+                                $secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
558
+                                if ($firstbyte == 0) {
559
+
560
+                                    // escaped/absolute mode - the first byte of the pair can be set to zero to
561
+                                    // indicate an escape character that denotes the end of a line, the end of
562
+                                    // a bitmap, or a delta, depending on the value of the second byte.
563
+                                    switch ($secondbyte) {
564
+                                        case 0:
565
+                                            // end of line
566
+                                            // no need for special processing, just ignore
567
+                                            break;
568
+
569
+                                        case 1:
570
+                                            // end of bitmap
571
+                                            $pixeldataoffset = strlen($BMPpixelData); // force to exit loop just in case
572
+                                            break;
573
+
574
+                                        case 2:
575
+                                            // delta - The 2 bytes following the escape contain unsigned values
576
+                                            // indicating the horizontal and vertical offsets of the next pixel
577
+                                            // from the current position.
578
+                                            $colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
579
+                                            $rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
580
+                                            $col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
581
+                                            $row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
582
+                                            $pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
583
+                                            break;
584
+
585
+                                        default:
586
+                                            // In absolute mode, the first byte is zero. The second byte contains the number
587
+                                            // of color indexes that follow. Subsequent bytes contain color indexes in their
588
+                                            // high- and low-order 4 bits, one color index for each pixel. In absolute mode,
589
+                                            // each run must be aligned on a word boundary.
590
+                                            $paletteindexes = array();
591
+                                            for ($i = 0, $iMax = ceil($secondbyte / 2); $i < $iMax; $i++) {
592
+                                                $paletteindexbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
593
+                                                $paletteindexes[] = ($paletteindexbyte & 0xF0) >> 4;
594
+                                                $paletteindexes[] = ($paletteindexbyte & 0x0F);
595
+                                            }
596
+                                            while (($pixeldataoffset % 2) != 0) {
597
+                                                // Each run must be aligned on a word boundary.
598
+                                                $pixeldataoffset++;
599
+                                            }
600
+
601
+                                            foreach ($paletteindexes as $dummy => $paletteindex) {
602
+                                                $col = $pixelcounter % $thisfile_bmp_header_raw['width'];
603
+                                                $row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
604
+                                                $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
605
+                                                $pixelcounter++;
606
+                                            }
607
+                                            break;
608
+                                    }
609
+
610
+                                } else {
611
+
612
+                                    // encoded mode - the first byte of the pair contains the number of pixels to be
613
+                                    // drawn using the color indexes in the second byte. The second byte contains two
614
+                                    // color indexes, one in its high-order 4 bits and one in its low-order 4 bits.
615
+                                    // The first of the pixels is drawn using the color specified by the high-order
616
+                                    // 4 bits, the second is drawn using the color in the low-order 4 bits, the third
617
+                                    // is drawn using the color in the high-order 4 bits, and so on, until all the
618
+                                    // pixels specified by the first byte have been drawn.
619
+                                    $paletteindexes[0] = ($secondbyte & 0xF0) >> 4;
620
+                                    $paletteindexes[1] = ($secondbyte & 0x0F);
621
+                                    for ($i = 0; $i < $firstbyte; $i++) {
622
+                                        $col = $pixelcounter % $thisfile_bmp_header_raw['width'];
623
+                                        $row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
624
+                                        $thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindexes[($i % 2)]];
625
+                                        $pixelcounter++;
626
+                                    }
627
+
628
+                                }
629
+                            }
630
+                            break;
631
+
632
+                        default:
633
+                            $ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
634
+                            break;
635
+                    }
636
+                    break;
637
+
638
+
639
+                case 3: // BI_BITFIELDS
640
+                    switch ($thisfile_bmp_header_raw['bits_per_pixel']) {
641
+                        case 16:
642
+                        case 32:
643
+                            $redshift   = 0;
644
+                            $greenshift = 0;
645
+                            $blueshift  = 0;
646
+                            if (!$thisfile_bmp_header_raw['red_mask'] || !$thisfile_bmp_header_raw['green_mask'] || !$thisfile_bmp_header_raw['blue_mask']) {
647
+                                $ThisFileInfo['error'][] = 'missing $thisfile_bmp_header_raw[(red|green|blue)_mask]';
648
+                                return false;
649
+                            }
650
+                            while ((($thisfile_bmp_header_raw['red_mask'] >> $redshift) & 0x01) == 0) {
651
+                                $redshift++;
652
+                            }
653
+                            while ((($thisfile_bmp_header_raw['green_mask'] >> $greenshift) & 0x01) == 0) {
654
+                                $greenshift++;
655
+                            }
656
+                            while ((($thisfile_bmp_header_raw['blue_mask'] >> $blueshift) & 0x01) == 0) {
657
+                                $blueshift++;
658
+                            }
659
+                            for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
660
+                                for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
661
+                                    $pixelvalue = $this->LittleEndian2Int(substr($BMPpixelData, $pixeldataoffset, $thisfile_bmp_header_raw['bits_per_pixel'] / 8));
662
+                                    $pixeldataoffset += $thisfile_bmp_header_raw['bits_per_pixel'] / 8;
663
+
664
+                                    $red   = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'red_mask'])   >> $redshift)   / ($thisfile_bmp_header_raw[ 'red_mask']   >> $redshift))   * 255);
665
+                                    $green = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'green_mask']) >> $greenshift) / ($thisfile_bmp_header_raw[ 'green_mask'] >> $greenshift)) * 255);
666
+                                    $blue  = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'blue_mask'])  >> $blueshift)  / ($thisfile_bmp_header_raw[ 'blue_mask']  >> $blueshift))  * 255);
667
+                                    $thisfile_bmp['data'][$row][$col] = (($red << 16) | ($green << 8) | ($blue));
668
+                                }
669
+                                while (($pixeldataoffset % 4) != 0) {
670
+                                    // lines are padded to nearest DWORD
671
+                                    $pixeldataoffset++;
672
+                                }
673
+                            }
674
+                            break;
675
+
676
+                        default:
677
+                            $ThisFileInfo['error'][] = 'Unknown bits-per-pixel value ('.$thisfile_bmp_header_raw['bits_per_pixel'].') - cannot read pixel data';
678
+                            break;
679
+                    }
680
+                    break;
681
+
682
+
683
+                default: // unhandled compression type
684
+                    $ThisFileInfo['error'][] = 'Unknown/unhandled compression type value ('.$thisfile_bmp_header_raw['compression'].') - cannot decompress pixel data';
685
+                    break;
686
+            }
687
+        }
688
+
689
+        return true;
690
+    }
691
+
692
+    public function IntColor2RGB($color) {
693
+        $red   = ($color & 0x00FF0000) >> 16;
694
+        $green = ($color & 0x0000FF00) >> 8;
695
+        $blue  = ($color & 0x000000FF);
696
+        return array($red, $green, $blue);
697
+    }
698
+
699
+    public function PlotPixelsGD(&$BMPdata, $truecolor=true) {
700
+        $imagewidth  = $BMPdata['header']['raw']['width'];
701
+        $imageheight = $BMPdata['header']['raw']['height'];
702
+
703
+        if ($truecolor) {
704
+
705
+            $gd = @imagecreatetruecolor($imagewidth, $imageheight);
706
+
707
+        } else {
708
+
709
+            $gd = @imagecreate($imagewidth, $imageheight);
710
+            if (!empty($BMPdata['palette'])) {
711
+                // create GD palette from BMP palette
712
+                foreach ($BMPdata['palette'] as $dummy => $color) {
713
+                    list($r, $g, $b) = $this->IntColor2RGB($color);
714
+                    imagecolorallocate($gd, $r, $g, $b);
715
+                }
716
+            } else {
717
+                // create 216-color websafe palette
718
+                for ($r = 0x00; $r <= 0xFF; $r += 0x33) {
719
+                    for ($g = 0x00; $g <= 0xFF; $g += 0x33) {
720
+                        for ($b = 0x00; $b <= 0xFF; $b += 0x33) {
721
+                            imagecolorallocate($gd, $r, $g, $b);
722
+                        }
723
+                    }
724
+                }
725
+            }
726
+
727
+        }
728
+        if (!is_resource($gd)) {
729
+            return false;
730
+        }
731
+
732
+        foreach ($BMPdata['data'] as $row => $colarray) {
733
+            if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
734
+                set_time_limit(30);
735
+            }
736
+            foreach ($colarray as $col => $color) {
737
+                list($red, $green, $blue) = $this->IntColor2RGB($color);
738
+                if ($truecolor) {
739
+                    $pixelcolor = imagecolorallocate($gd, $red, $green, $blue);
740
+                } else {
741
+                    $pixelcolor = imagecolorclosest($gd, $red, $green, $blue);
742
+                }
743
+                imagesetpixel($gd, $col, $row, $pixelcolor);
744
+            }
745
+        }
746
+        return $gd;
747
+    }
748
+
749
+    public function PlotBMP(&$BMPinfo) {
750
+        $starttime = time();
751
+        if (!isset($BMPinfo['bmp']['data']) || !is_array($BMPinfo['bmp']['data'])) {
752
+            echo 'ERROR: no pixel data<BR>';
753
+            return false;
754
+        }
755
+        if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
756
+            set_time_limit((int) round($BMPinfo[ 'resolution_x'] * $BMPinfo[ 'resolution_y'] / 10000));
757
+        }
758
+        $im = $this->PlotPixelsGD($BMPinfo['bmp']);
759
+        if (headers_sent()) {
760
+            echo 'plotted '.($BMPinfo['resolution_x'] * $BMPinfo['resolution_y']).' pixels in '.(time() - $starttime).' seconds<BR>';
761
+            imagedestroy($im);
762
+            exit;
763
+        }
764
+        header('Content-Type: image/png');
765
+        imagepng($im);
766
+        imagedestroy($im);
767
+        return true;
768
+    }
769
+
770
+    public function BMPcompressionWindowsLookup($compressionid) {
771
+        static $BMPcompressionWindowsLookup = array(
772
+            0 => 'BI_RGB',
773
+            1 => 'BI_RLE8',
774
+            2 => 'BI_RLE4',
775
+            3 => 'BI_BITFIELDS',
776
+            4 => 'BI_JPEG',
777
+            5 => 'BI_PNG'
778
+        );
779
+        return (isset($BMPcompressionWindowsLookup[$compressionid]) ? $BMPcompressionWindowsLookup[$compressionid] : 'invalid');
780
+    }
781
+
782
+    public function BMPcompressionOS2Lookup($compressionid) {
783
+        static $BMPcompressionOS2Lookup = array(
784
+            0 => 'BI_RGB',
785
+            1 => 'BI_RLE8',
786
+            2 => 'BI_RLE4',
787
+            3 => 'Huffman 1D',
788
+            4 => 'BI_RLE24',
789
+        );
790
+        return (isset($BMPcompressionOS2Lookup[$compressionid]) ? $BMPcompressionOS2Lookup[$compressionid] : 'invalid');
791
+    }
792
+
793
+
794
+    // from getid3.lib.php
795
+
796
+    public function trunc($floatnumber) {
797
+        // truncates a floating-point number at the decimal point
798
+        // returns int (if possible, otherwise float)
799
+        if ($floatnumber >= 1) {
800
+            $truncatednumber = floor($floatnumber);
801
+        } elseif ($floatnumber <= -1) {
802
+            $truncatednumber = ceil($floatnumber);
803
+        } else {
804
+            $truncatednumber = 0;
805
+        }
806
+        if ($truncatednumber <= 1073741824) { // 2^30
807
+            $truncatednumber = (int) $truncatednumber;
808
+        }
809
+        return $truncatednumber;
810
+    }
811
+
812
+    public function LittleEndian2Int($byteword) {
813
+        $intvalue = 0;
814
+        $byteword = strrev($byteword);
815
+        $bytewordlen = strlen($byteword);
816
+        for ($i = 0; $i < $bytewordlen; $i++) {
817
+            $intvalue += ord($byteword{$i}) * pow(256, ($bytewordlen - 1 - $i));
818
+        }
819
+        return $intvalue;
820
+    }
821
+
822
+    public function BigEndian2Int($byteword) {
823
+        return $this->LittleEndian2Int(strrev($byteword));
824
+    }
825
+
826
+    public function BigEndian2Bin($byteword) {
827
+        $binvalue = '';
828
+        $bytewordlen = strlen($byteword);
829
+        for ($i = 0; $i < $bytewordlen; $i++) {
830
+            $binvalue .= str_pad(decbin(ord($byteword{$i})), 8, '0', STR_PAD_LEFT);
831
+        }
832
+        return $binvalue;
833
+    }
834
+
835
+    public function FixedPoint2_30($rawdata) {
836
+        $binarystring = $this->BigEndian2Bin($rawdata);
837
+        return $this->Bin2Dec(substr($binarystring, 0, 2)) + (float) ($this->Bin2Dec(substr($binarystring, 2, 30)) / 1073741824);
838
+    }
839
+
840
+    public function Bin2Dec($binstring, $signed=false) {
841
+        $signmult = 1;
842
+        if ($signed) {
843
+            if ($binstring{0} == '1') {
844
+                $signmult = -1;
845
+            }
846
+            $binstring = substr($binstring, 1);
847
+        }
848
+        $decvalue = 0;
849
+        for ($i = 0, $iMax = strlen($binstring); $i < $iMax; $i++) {
850
+            $decvalue += ((int) $binstring[ strlen($binstring) - $i - 1 ]) * pow(2, $i);
851
+        }
852
+        return $this->CastAsInt($decvalue * $signmult);
853
+    }
854
+
855
+    public function CastAsInt($floatnum) {
856
+        // convert to float if not already
857
+        $floatnum = (float) $floatnum;
858
+
859
+        // convert a float to type int, only if possible
860
+        if ($this->trunc($floatnum) == $floatnum) {
861
+            // it's not floating point
862
+            if ($floatnum <= 1073741824) { // 2^30
863
+                // it's within int range
864
+                $floatnum = (int) $floatnum;
865
+            }
866
+        }
867
+        return $floatnum;
868
+    }
869 869
 
870 870
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 
21 21
 class phpthumb_bmp {
22 22
 
23
-	public function phpthumb_bmp2gd(&$BMPdata, $truecolor=true) {
23
+	public function phpthumb_bmp2gd(&$BMPdata, $truecolor = true) {
24 24
 		$ThisFileInfo = array();
25 25
 		if ($this->getid3_bmp($BMPdata, $ThisFileInfo, true, true)) {
26 26
 			$gd = $this->PlotPixelsGD($ThisFileInfo['bmp'], $truecolor);
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
 		return false;
30 30
 	}
31 31
 
32
-	public function phpthumb_bmpfile2gd($filename, $truecolor=true) {
32
+	public function phpthumb_bmpfile2gd($filename, $truecolor = true) {
33 33
 		if ($fp = @fopen($filename, 'rb')) {
34 34
 			$BMPdata = fread($fp, filesize($filename));
35 35
 			fclose($fp);
@@ -57,29 +57,29 @@  discard block
 block discarded – undo
57 57
 
58 58
 		$bmpSize = strlen($BMP) + 14 + 40;
59 59
 		// BITMAPFILEHEADER [14 bytes] - http://msdn.microsoft.com/library/en-us/gdi/bitmaps_62uq.asp
60
-		$BITMAPFILEHEADER  = 'BM';                                                           // WORD    bfType;
60
+		$BITMAPFILEHEADER  = 'BM'; // WORD    bfType;
61 61
 		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String($bmpSize, 4); // DWORD   bfSize;
62
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved1;
63
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(       0, 2); // WORD    bfReserved2;
64
-		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(      54, 4); // DWORD   bfOffBits;
62
+		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(0, 2); // WORD    bfReserved1;
63
+		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(0, 2); // WORD    bfReserved2;
64
+		$BITMAPFILEHEADER .= phpthumb_functions::LittleEndian2String(54, 4); // DWORD   bfOffBits;
65 65
 
66 66
 		// BITMAPINFOHEADER - [40 bytes] http://msdn.microsoft.com/library/en-us/gdi/bitmaps_1rw2.asp
67
-		$BITMAPINFOHEADER  = phpthumb_functions::LittleEndian2String(      40, 4); // DWORD  biSize;
68
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageX, 4); // LONG   biWidth;
69
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String( $imageY, 4); // LONG   biHeight;
70
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       1, 2); // WORD   biPlanes;
71
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(      24, 2); // WORD   biBitCount;
72
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biCompression;
73
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biSizeImage;
74
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biXPelsPerMeter;
75
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(    2835, 4); // LONG   biYPelsPerMeter;
76
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrUsed;
77
-		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(       0, 4); // DWORD  biClrImportant;
67
+		$BITMAPINFOHEADER  = phpthumb_functions::LittleEndian2String(40, 4); // DWORD  biSize;
68
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String($imageX, 4); // LONG   biWidth;
69
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String($imageY, 4); // LONG   biHeight;
70
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(1, 2); // WORD   biPlanes;
71
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(24, 2); // WORD   biBitCount;
72
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(0, 4); // DWORD  biCompression;
73
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(0, 4); // DWORD  biSizeImage;
74
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(2835, 4); // LONG   biXPelsPerMeter;
75
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(2835, 4); // LONG   biYPelsPerMeter;
76
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(0, 4); // DWORD  biClrUsed;
77
+		$BITMAPINFOHEADER .= phpthumb_functions::LittleEndian2String(0, 4); // DWORD  biClrImportant;
78 78
 
79 79
 		return $BITMAPFILEHEADER.$BITMAPINFOHEADER.$BMP;
80 80
 	}
81 81
 
82
-	public function getid3_bmp(&$BMPdata, &$ThisFileInfo, $ExtractPalette=false, $ExtractData=false) {
82
+	public function getid3_bmp(&$BMPdata, &$ThisFileInfo, $ExtractPalette = false, $ExtractData = false) {
83 83
 
84 84
 		// shortcuts
85 85
 		$ThisFileInfo['bmp']['header']['raw'] = array();
@@ -100,11 +100,11 @@  discard block
 block discarded – undo
100 100
 		$BMPheader = substr($BMPdata, $overalloffset, 14 + 40);
101 101
 		$overalloffset += (14 + 40);
102 102
 
103
-		$thisfile_bmp_header_raw['identifier']  = substr($BMPheader, $offset, 2);
103
+		$thisfile_bmp_header_raw['identifier'] = substr($BMPheader, $offset, 2);
104 104
 		$offset += 2;
105 105
 
106 106
 		if ($thisfile_bmp_header_raw['identifier'] != 'BM') {
107
-			$ThisFileInfo['error'][] = 'Expecting "BM" at offset '. (int) (@$ThisFileInfo[ 'avdataoffset']) .', found "'. $thisfile_bmp_header_raw[ 'identifier'].'"';
107
+			$ThisFileInfo['error'][] = 'Expecting "BM" at offset '.(int)(@$ThisFileInfo['avdataoffset']).', found "'.$thisfile_bmp_header_raw['identifier'].'"';
108 108
 			unset($ThisFileInfo['fileformat']);
109 109
 			unset($ThisFileInfo['bmp']);
110 110
 			return false;
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 		$ThisFileInfo['fileformat']                  = 'bmp';
154 154
 		$ThisFileInfo['video']['dataformat']         = 'bmp';
155 155
 		$ThisFileInfo['video']['lossless']           = true;
156
-		$ThisFileInfo['video']['pixel_aspect_ratio'] = (float) 1;
156
+		$ThisFileInfo['video']['pixel_aspect_ratio'] = (float)1;
157 157
 
158 158
 		if ($thisfile_bmp['type_os'] == 'OS/2') {
159 159
 
@@ -301,11 +301,11 @@  discard block
 block discarded – undo
301 301
 				$offset += 4;
302 302
 				$thisfile_bmp_header_raw['cs_type']      = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
303 303
 				$offset += 4;
304
-				$thisfile_bmp_header_raw['ciexyz_red']   =                         substr($BMPheader, $offset, 4);
304
+				$thisfile_bmp_header_raw['ciexyz_red']   = substr($BMPheader, $offset, 4);
305 305
 				$offset += 4;
306
-				$thisfile_bmp_header_raw['ciexyz_green'] =                         substr($BMPheader, $offset, 4);
306
+				$thisfile_bmp_header_raw['ciexyz_green'] = substr($BMPheader, $offset, 4);
307 307
 				$offset += 4;
308
-				$thisfile_bmp_header_raw['ciexyz_blue']  =                         substr($BMPheader, $offset, 4);
308
+				$thisfile_bmp_header_raw['ciexyz_blue']  = substr($BMPheader, $offset, 4);
309 309
 				$offset += 4;
310 310
 				$thisfile_bmp_header_raw['gamma_red']    = $this->LittleEndian2Int(substr($BMPheader, $offset, 4));
311 311
 				$offset += 4;
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
 					// BYTE    rgbGreen;
365 365
 					// BYTE    rgbRed;
366 366
 					// BYTE    rgbReserved;
367
-					$blue  = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
368
-					$green = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
369
-					$red   = $this->LittleEndian2Int($BMPpalette[ $paletteoffset++ ]);
367
+					$blue  = $this->LittleEndian2Int($BMPpalette[$paletteoffset++]);
368
+					$green = $this->LittleEndian2Int($BMPpalette[$paletteoffset++]);
369
+					$red   = $this->LittleEndian2Int($BMPpalette[$paletteoffset++]);
370 370
 					if (($thisfile_bmp['type_os'] == 'OS/2') && ($thisfile_bmp['type_version'] == 1)) {
371 371
 						// no padding byte
372 372
 					} else {
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 						case 24:
439 439
 							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
440 440
 								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
441
-									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
441
+									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset + 2}) << 16) | (ord($BMPpixelData{$pixeldataoffset + 1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
442 442
 									$pixeldataoffset += 3;
443 443
 								}
444 444
 								while (($pixeldataoffset % 4) != 0) {
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 						case 32:
452 452
 							for ($row = ($thisfile_bmp_header_raw['height'] - 1); $row >= 0; $row--) {
453 453
 								for ($col = 0; $col < $thisfile_bmp_header_raw['width']; $col++) {
454
-									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset+3}) << 24) | (ord($BMPpixelData{$pixeldataoffset+2}) << 16) | (ord($BMPpixelData{$pixeldataoffset+1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
454
+									$thisfile_bmp['data'][$row][$col] = (ord($BMPpixelData{$pixeldataoffset + 3}) << 24) | (ord($BMPpixelData{$pixeldataoffset + 2}) << 16) | (ord($BMPpixelData{$pixeldataoffset + 1}) << 8) | ord($BMPpixelData{$pixeldataoffset});
455 455
 									$pixeldataoffset += 4;
456 456
 								}
457 457
 								while (($pixeldataoffset % 4) != 0) {
@@ -477,8 +477,8 @@  discard block
 block discarded – undo
477 477
 						case 8:
478 478
 							$pixelcounter = 0;
479 479
 							while ($pixeldataoffset < strlen($BMPpixelData)) {
480
-								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
481
-								$secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
480
+								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
481
+								$secondbyte = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
482 482
 								if ($firstbyte == 0) {
483 483
 
484 484
 									// escaped/absolute mode - the first byte of the pair can be set to zero to
@@ -499,8 +499,8 @@  discard block
 block discarded – undo
499 499
 											// delta - The 2 bytes following the escape contain unsigned values
500 500
 											// indicating the horizontal and vertical offsets of the next pixel
501 501
 											// from the current position.
502
-											$colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
503
-											$rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
502
+											$colincrement = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
503
+											$rowincrement = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
504 504
 											$col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
505 505
 											$row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
506 506
 											$pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 											// number of bytes that follow, each of which contains the color index
513 513
 											// of a single pixel. Each run must be aligned on a word boundary.
514 514
 											for ($i = 0; $i < $secondbyte; $i++) {
515
-												$paletteindex = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
515
+												$paletteindex = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
516 516
 												$col = $pixelcounter % $thisfile_bmp_header_raw['width'];
517 517
 												$row = $thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width']);
518 518
 												$thisfile_bmp['data'][$row][$col] = $thisfile_bmp['palette'][$paletteindex];
@@ -553,8 +553,8 @@  discard block
 block discarded – undo
553 553
 						case 4:
554 554
 							$pixelcounter = 0;
555 555
 							while ($pixeldataoffset < strlen($BMPpixelData)) {
556
-								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
557
-								$secondbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
556
+								$firstbyte  = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
557
+								$secondbyte = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
558 558
 								if ($firstbyte == 0) {
559 559
 
560 560
 									// escaped/absolute mode - the first byte of the pair can be set to zero to
@@ -575,8 +575,8 @@  discard block
 block discarded – undo
575 575
 											// delta - The 2 bytes following the escape contain unsigned values
576 576
 											// indicating the horizontal and vertical offsets of the next pixel
577 577
 											// from the current position.
578
-											$colincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
579
-											$rowincrement = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
578
+											$colincrement = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
579
+											$rowincrement = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
580 580
 											$col = ($pixelcounter % $thisfile_bmp_header_raw['width']) + $colincrement;
581 581
 											$row = ($thisfile_bmp_header_raw['height'] - 1 - (($pixelcounter - $col) / $thisfile_bmp_header_raw['width'])) - $rowincrement;
582 582
 											$pixelcounter = ($row * $thisfile_bmp_header_raw['width']) + $col;
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 											// each run must be aligned on a word boundary.
590 590
 											$paletteindexes = array();
591 591
 											for ($i = 0, $iMax = ceil($secondbyte / 2); $i < $iMax; $i++) {
592
-												$paletteindexbyte = $this->LittleEndian2Int($BMPpixelData[ $pixeldataoffset++ ]);
592
+												$paletteindexbyte = $this->LittleEndian2Int($BMPpixelData[$pixeldataoffset++]);
593 593
 												$paletteindexes[] = ($paletteindexbyte & 0xF0) >> 4;
594 594
 												$paletteindexes[] = ($paletteindexbyte & 0x0F);
595 595
 											}
@@ -661,9 +661,9 @@  discard block
 block discarded – undo
661 661
 									$pixelvalue = $this->LittleEndian2Int(substr($BMPpixelData, $pixeldataoffset, $thisfile_bmp_header_raw['bits_per_pixel'] / 8));
662 662
 									$pixeldataoffset += $thisfile_bmp_header_raw['bits_per_pixel'] / 8;
663 663
 
664
-									$red   = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'red_mask'])   >> $redshift)   / ($thisfile_bmp_header_raw[ 'red_mask']   >> $redshift))   * 255);
665
-									$green = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'green_mask']) >> $greenshift) / ($thisfile_bmp_header_raw[ 'green_mask'] >> $greenshift)) * 255);
666
-									$blue  = (int) round(((($pixelvalue & $thisfile_bmp_header_raw[ 'blue_mask'])  >> $blueshift)  / ($thisfile_bmp_header_raw[ 'blue_mask']  >> $blueshift))  * 255);
664
+									$red   = (int)round(((($pixelvalue & $thisfile_bmp_header_raw['red_mask']) >> $redshift) / ($thisfile_bmp_header_raw['red_mask'] >> $redshift)) * 255);
665
+									$green = (int)round(((($pixelvalue & $thisfile_bmp_header_raw['green_mask']) >> $greenshift) / ($thisfile_bmp_header_raw['green_mask'] >> $greenshift)) * 255);
666
+									$blue  = (int)round(((($pixelvalue & $thisfile_bmp_header_raw['blue_mask']) >> $blueshift) / ($thisfile_bmp_header_raw['blue_mask'] >> $blueshift)) * 255);
667 667
 									$thisfile_bmp['data'][$row][$col] = (($red << 16) | ($green << 8) | ($blue));
668 668
 								}
669 669
 								while (($pixeldataoffset % 4) != 0) {
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 		return array($red, $green, $blue);
697 697
 	}
698 698
 
699
-	public function PlotPixelsGD(&$BMPdata, $truecolor=true) {
699
+	public function PlotPixelsGD(&$BMPdata, $truecolor = true) {
700 700
 		$imagewidth  = $BMPdata['header']['raw']['width'];
701 701
 		$imageheight = $BMPdata['header']['raw']['height'];
702 702
 
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 			return false;
754 754
 		}
755 755
 		if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
756
-			set_time_limit((int) round($BMPinfo[ 'resolution_x'] * $BMPinfo[ 'resolution_y'] / 10000));
756
+			set_time_limit((int)round($BMPinfo['resolution_x'] * $BMPinfo['resolution_y'] / 10000));
757 757
 		}
758 758
 		$im = $this->PlotPixelsGD($BMPinfo['bmp']);
759 759
 		if (headers_sent()) {
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
 			$truncatednumber = 0;
805 805
 		}
806 806
 		if ($truncatednumber <= 1073741824) { // 2^30
807
-			$truncatednumber = (int) $truncatednumber;
807
+			$truncatednumber = (int)$truncatednumber;
808 808
 		}
809 809
 		return $truncatednumber;
810 810
 	}
@@ -834,10 +834,10 @@  discard block
 block discarded – undo
834 834
 
835 835
 	public function FixedPoint2_30($rawdata) {
836 836
 		$binarystring = $this->BigEndian2Bin($rawdata);
837
-		return $this->Bin2Dec(substr($binarystring, 0, 2)) + (float) ($this->Bin2Dec(substr($binarystring, 2, 30)) / 1073741824);
837
+		return $this->Bin2Dec(substr($binarystring, 0, 2)) + (float)($this->Bin2Dec(substr($binarystring, 2, 30)) / 1073741824);
838 838
 	}
839 839
 
840
-	public function Bin2Dec($binstring, $signed=false) {
840
+	public function Bin2Dec($binstring, $signed = false) {
841 841
 		$signmult = 1;
842 842
 		if ($signed) {
843 843
 			if ($binstring{0} == '1') {
@@ -847,21 +847,21 @@  discard block
 block discarded – undo
847 847
 		}
848 848
 		$decvalue = 0;
849 849
 		for ($i = 0, $iMax = strlen($binstring); $i < $iMax; $i++) {
850
-			$decvalue += ((int) $binstring[ strlen($binstring) - $i - 1 ]) * pow(2, $i);
850
+			$decvalue += ((int)$binstring[strlen($binstring) - $i - 1]) * pow(2, $i);
851 851
 		}
852 852
 		return $this->CastAsInt($decvalue * $signmult);
853 853
 	}
854 854
 
855 855
 	public function CastAsInt($floatnum) {
856 856
 		// convert to float if not already
857
-		$floatnum = (float) $floatnum;
857
+		$floatnum = (float)$floatnum;
858 858
 
859 859
 		// convert a float to type int, only if possible
860 860
 		if ($this->trunc($floatnum) == $floatnum) {
861 861
 			// it's not floating point
862 862
 			if ($floatnum <= 1073741824) { // 2^30
863 863
 				// it's within int range
864
-				$floatnum = (int) $floatnum;
864
+				$floatnum = (int)$floatnum;
865 865
 			}
866 866
 		}
867 867
 		return $floatnum;
Please login to merge, or discard this patch.
htdocs/modules/system/class/thumbs/phpthumb.gif.php 4 patches
Indentation   +1075 added lines, -1075 removed lines patch added patch discarded remove patch
@@ -23,11 +23,11 @@  discard block
 block discarded – undo
23 23
 
24 24
 function gif_loadFile($lpszFileName, $iIndex = 0)
25 25
 {
26
-	$gif = new CGIF();
27
-	if ($gif->loadFile($lpszFileName, $iIndex)) {
28
-		return $gif;
29
-	}
30
-	return false;
26
+    $gif = new CGIF();
27
+    if ($gif->loadFile($lpszFileName, $iIndex)) {
28
+        return $gif;
29
+    }
30
+    return false;
31 31
 }
32 32
 
33 33
 ///////////////////////////////////////////////////////////////////////////////////////////////////
@@ -35,1141 +35,1141 @@  discard block
 block discarded – undo
35 35
 // Added by James Heinrich <[email protected]> - December 10, 2003
36 36
 function gif_loadFileToGDimageResource($gifFilename, $bgColor = -1)
37 37
 {
38
-	if ($gif = gif_loadFile($gifFilename)) {
39
-
40
-		if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
41
-			// shouldn't take nearly this long
42
-			set_time_limit(120);
43
-		}
44
-		// general strategy: convert raw data to PNG then convert PNG data to GD image resource
45
-		$PNGdata = $gif->getPng($bgColor);
46
-		if ($img = @imagecreatefromstring($PNGdata)) {
47
-
48
-			// excellent - PNG image data successfully converted to GD image
49
-			return $img;
50
-
51
-		} elseif ($img = $gif->getGD_PixelPlotterVersion()) {
52
-
53
-			// problem: imagecreatefromstring() didn't like the PNG image data.
54
-			//   This has been known to happen in PHP v4.0.6
55
-			// solution: take the raw image data and create a new GD image and plot
56
-			//   pixel-by-pixel on the GD image. This is extremely slow, but it does
57
-			//   work and a slow solution is better than no solution, right? :)
58
-			return $img;
59
-
60
-		}
61
-	}
62
-	return false;
38
+    if ($gif = gif_loadFile($gifFilename)) {
39
+
40
+        if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
41
+            // shouldn't take nearly this long
42
+            set_time_limit(120);
43
+        }
44
+        // general strategy: convert raw data to PNG then convert PNG data to GD image resource
45
+        $PNGdata = $gif->getPng($bgColor);
46
+        if ($img = @imagecreatefromstring($PNGdata)) {
47
+
48
+            // excellent - PNG image data successfully converted to GD image
49
+            return $img;
50
+
51
+        } elseif ($img = $gif->getGD_PixelPlotterVersion()) {
52
+
53
+            // problem: imagecreatefromstring() didn't like the PNG image data.
54
+            //   This has been known to happen in PHP v4.0.6
55
+            // solution: take the raw image data and create a new GD image and plot
56
+            //   pixel-by-pixel on the GD image. This is extremely slow, but it does
57
+            //   work and a slow solution is better than no solution, right? :)
58
+            return $img;
59
+
60
+        }
61
+    }
62
+    return false;
63 63
 }
64 64
 
65 65
 ///////////////////////////////////////////////////////////////////////////////////////////////////
66 66
 
67 67
 function gif_outputAsBmp($gif, $lpszFileName, $bgColor = -1)
68 68
 {
69
-	if (!isset($gif) || (@get_class($gif) <> 'cgif') || !$gif->loaded() || ($lpszFileName == '')) {
70
-		return false;
71
-	}
72
-
73
-	$fd = $gif->getBmp($bgColor);
74
-	if (strlen($fd) <= 0) {
75
-		return false;
76
-	}
77
-
78
-	if (!($fh = @fopen($lpszFileName, 'wb'))) {
79
-		return false;
80
-	}
81
-	@fwrite($fh, $fd, strlen($fd));
82
-	@fflush($fh);
83
-	@fclose($fh);
84
-	return true;
69
+    if (!isset($gif) || (@get_class($gif) <> 'cgif') || !$gif->loaded() || ($lpszFileName == '')) {
70
+        return false;
71
+    }
72
+
73
+    $fd = $gif->getBmp($bgColor);
74
+    if (strlen($fd) <= 0) {
75
+        return false;
76
+    }
77
+
78
+    if (!($fh = @fopen($lpszFileName, 'wb'))) {
79
+        return false;
80
+    }
81
+    @fwrite($fh, $fd, strlen($fd));
82
+    @fflush($fh);
83
+    @fclose($fh);
84
+    return true;
85 85
 }
86 86
 
87 87
 ///////////////////////////////////////////////////////////////////////////////////////////////////
88 88
 
89 89
 function gif_outputAsPng($gif, $lpszFileName, $bgColor = -1)
90 90
 {
91
-	if (!isSet($gif) || (@get_class($gif) <> 'cgif') || !$gif->loaded() || ($lpszFileName == '')) {
92
-		return false;
93
-	}
94
-
95
-	$fd = $gif->getPng($bgColor);
96
-	if (strlen($fd) <= 0) {
97
-		return false;
98
-	}
99
-
100
-	if (!($fh = @fopen($lpszFileName, 'wb'))) {
101
-		return false;
102
-	}
103
-	@fwrite($fh, $fd, strlen($fd));
104
-	@fflush($fh);
105
-	@fclose($fh);
106
-	return true;
91
+    if (!isSet($gif) || (@get_class($gif) <> 'cgif') || !$gif->loaded() || ($lpszFileName == '')) {
92
+        return false;
93
+    }
94
+
95
+    $fd = $gif->getPng($bgColor);
96
+    if (strlen($fd) <= 0) {
97
+        return false;
98
+    }
99
+
100
+    if (!($fh = @fopen($lpszFileName, 'wb'))) {
101
+        return false;
102
+    }
103
+    @fwrite($fh, $fd, strlen($fd));
104
+    @fflush($fh);
105
+    @fclose($fh);
106
+    return true;
107 107
 }
108 108
 
109 109
 ///////////////////////////////////////////////////////////////////////////////////////////////////
110 110
 
111 111
 function gif_outputAsJpeg($gif, $lpszFileName, $bgColor = -1)
112 112
 {
113
-	// JPEG output that does not require cjpeg added by James Heinrich <[email protected]> - December 10, 2003
114
-	if ((strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') && (file_exists('/usr/local/bin/cjpeg') || `which cjpeg`)) {
113
+    // JPEG output that does not require cjpeg added by James Heinrich <[email protected]> - December 10, 2003
114
+    if ((strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') && (file_exists('/usr/local/bin/cjpeg') || `which cjpeg`)) {
115 115
 
116
-		if (gif_outputAsBmp($gif, $lpszFileName.'.bmp', $bgColor)) {
117
-			exec('cjpeg '.$lpszFileName.'.bmp >'.$lpszFileName.' 2>/dev/null');
118
-			@unlink($lpszFileName.'.bmp');
116
+        if (gif_outputAsBmp($gif, $lpszFileName.'.bmp', $bgColor)) {
117
+            exec('cjpeg '.$lpszFileName.'.bmp >'.$lpszFileName.' 2>/dev/null');
118
+            @unlink($lpszFileName.'.bmp');
119 119
 
120
-			if (@file_exists($lpszFileName)) {
121
-				if (@filesize($lpszFileName) > 0) {
122
-					return true;
123
-				}
120
+            if (@file_exists($lpszFileName)) {
121
+                if (@filesize($lpszFileName) > 0) {
122
+                    return true;
123
+                }
124 124
 
125
-				@unlink($lpszFileName);
126
-			}
127
-		}
125
+                @unlink($lpszFileName);
126
+            }
127
+        }
128 128
 
129
-	} else {
129
+    } else {
130 130
 
131
-		// either Windows, or cjpeg not found in path
132
-		if ($img = @imagecreatefromstring($gif->getPng($bgColor))) {
133
-			if (@imagejpeg($img, $lpszFileName)) {
134
-				return true;
135
-			}
136
-		}
131
+        // either Windows, or cjpeg not found in path
132
+        if ($img = @imagecreatefromstring($gif->getPng($bgColor))) {
133
+            if (@imagejpeg($img, $lpszFileName)) {
134
+                return true;
135
+            }
136
+        }
137 137
 
138
-	}
138
+    }
139 139
 
140
-	return false;
140
+    return false;
141 141
 }
142 142
 
143 143
 ///////////////////////////////////////////////////////////////////////////////////////////////////
144 144
 
145 145
 function gif_getSize($gif, &$width, &$height)
146 146
 {
147
-	if (isSet($gif) && (@get_class($gif) == 'cgif') && $gif->loaded()) {
148
-		$width  = $gif->width();
149
-		$height = $gif->height();
150
-	} elseif (@file_exists($gif)) {
151
-		$myGIF = new CGIF();
152
-		if (!$myGIF->getSize($gif, $width, $height)) {
153
-			return false;
154
-		}
155
-	} else {
156
-		return false;
157
-	}
158
-
159
-	return true;
147
+    if (isSet($gif) && (@get_class($gif) == 'cgif') && $gif->loaded()) {
148
+        $width  = $gif->width();
149
+        $height = $gif->height();
150
+    } elseif (@file_exists($gif)) {
151
+        $myGIF = new CGIF();
152
+        if (!$myGIF->getSize($gif, $width, $height)) {
153
+            return false;
154
+        }
155
+    } else {
156
+        return false;
157
+    }
158
+
159
+    return true;
160 160
 }
161 161
 
162 162
 ///////////////////////////////////////////////////////////////////////////////////////////////////
163 163
 
164 164
 class CGIFLZW
165 165
 {
166
-	public $MAX_LZW_BITS;
167
-	public $Fresh, $CodeSize, $SetCodeSize, $MaxCode, $MaxCodeSize, $FirstCode, $OldCode;
168
-	public $ClearCode, $EndCode, $Next, $Vals, $Stack, $sp, $Buf, $CurBit, $LastBit, $Done, $LastByte;
169
-
170
-	///////////////////////////////////////////////////////////////////////////
171
-
172
-	// CONSTRUCTOR
173
-	public function __construct()
174
-	{
175
-		$this->MAX_LZW_BITS = 12;
176
-		unSet($this->Next);
177
-		unSet($this->Vals);
178
-		unSet($this->Stack);
179
-		unSet($this->Buf);
180
-
181
-		$this->Next  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
182
-		$this->Vals  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
183
-		$this->Stack = range(0, (1 << ($this->MAX_LZW_BITS + 1)) - 1);
184
-		$this->Buf   = range(0, 279);
185
-	}
186
-
187
-	///////////////////////////////////////////////////////////////////////////
188
-
189
-	public function deCompress($data, &$datLen)
190
-	{
191
-		$stLen  = strlen($data);
192
-		$datLen = 0;
193
-		$ret    = '';
194
-
195
-		// INITIALIZATION
196
-		$this->LZWCommand($data, true);
197
-
198
-		while (($iIndex = $this->LZWCommand($data, false)) >= 0) {
199
-			$ret .= chr($iIndex);
200
-		}
201
-
202
-		$datLen = $stLen - strlen($data);
203
-
204
-		if ($iIndex != -2) {
205
-			return false;
206
-		}
207
-
208
-		return $ret;
209
-	}
210
-
211
-	///////////////////////////////////////////////////////////////////////////
212
-
213
-	public function LZWCommand(&$data, $bInit)
214
-	{
215
-		if ($bInit) {
216
-			$this->SetCodeSize = ord($data{0});
217
-			$data = substr($data, 1);
218
-
219
-			$this->CodeSize    = $this->SetCodeSize + 1;
220
-			$this->ClearCode   = 1 << $this->SetCodeSize;
221
-			$this->EndCode     = $this->ClearCode + 1;
222
-			$this->MaxCode     = $this->ClearCode + 2;
223
-			$this->MaxCodeSize = $this->ClearCode << 1;
224
-
225
-			$this->GetCode($data, $bInit);
226
-
227
-			$this->Fresh = 1;
228
-			for ($i = 0; $i < $this->ClearCode; $i++) {
229
-				$this->Next[$i] = 0;
230
-				$this->Vals[$i] = $i;
231
-			}
232
-
233
-			for (; $i < (1 << $this->MAX_LZW_BITS); $i++) {
234
-				$this->Next[$i] = 0;
235
-				$this->Vals[$i] = 0;
236
-			}
237
-
238
-			$this->sp = 0;
239
-			return 1;
240
-		}
241
-
242
-		if ($this->Fresh) {
243
-			$this->Fresh = 0;
244
-			do {
245
-				$this->FirstCode = $this->GetCode($data, $bInit);
246
-				$this->OldCode   = $this->FirstCode;
247
-			}
248
-			while ($this->FirstCode == $this->ClearCode);
249
-
250
-			return $this->FirstCode;
251
-		}
252
-
253
-		if ($this->sp > 0) {
254
-			$this->sp--;
255
-			return $this->Stack[$this->sp];
256
-		}
257
-
258
-		while (($Code = $this->GetCode($data, $bInit)) >= 0) {
259
-			if ($Code == $this->ClearCode) {
260
-				for ($i = 0; $i < $this->ClearCode; $i++) {
261
-					$this->Next[$i] = 0;
262
-					$this->Vals[$i] = $i;
263
-				}
264
-
265
-				for (; $i < (1 << $this->MAX_LZW_BITS); $i++) {
266
-					$this->Next[$i] = 0;
267
-					$this->Vals[$i] = 0;
268
-				}
269
-
270
-				$this->CodeSize    = $this->SetCodeSize + 1;
271
-				$this->MaxCodeSize = $this->ClearCode << 1;
272
-				$this->MaxCode     = $this->ClearCode + 2;
273
-				$this->sp          = 0;
274
-				$this->FirstCode   = $this->GetCode($data, $bInit);
275
-				$this->OldCode     = $this->FirstCode;
276
-
277
-				return $this->FirstCode;
278
-			}
279
-
280
-			if ($Code == $this->EndCode) {
281
-				return -2;
282
-			}
283
-
284
-			$InCode = $Code;
285
-			if ($Code >= $this->MaxCode) {
286
-				$this->Stack[$this->sp] = $this->FirstCode;
287
-				$this->sp++;
288
-				$Code = $this->OldCode;
289
-			}
290
-
291
-			while ($Code >= $this->ClearCode) {
292
-				$this->Stack[$this->sp] = $this->Vals[$Code];
293
-				$this->sp++;
294
-
295
-				if ($Code == $this->Next[$Code]) // Circular table entry, big GIF Error!
296
-					return -1;
297
-
298
-				$Code = $this->Next[$Code];
299
-			}
300
-
301
-			$this->FirstCode = $this->Vals[$Code];
302
-			$this->Stack[$this->sp] = $this->FirstCode;
303
-			$this->sp++;
304
-
305
-			if (($Code = $this->MaxCode) < (1 << $this->MAX_LZW_BITS)) {
306
-				$this->Next[$Code] = $this->OldCode;
307
-				$this->Vals[$Code] = $this->FirstCode;
308
-				$this->MaxCode++;
309
-
310
-				if (($this->MaxCode >= $this->MaxCodeSize) && ($this->MaxCodeSize < (1 << $this->MAX_LZW_BITS))) {
311
-					$this->MaxCodeSize *= 2;
312
-					$this->CodeSize++;
313
-				}
314
-			}
315
-
316
-			$this->OldCode = $InCode;
317
-			if ($this->sp > 0) {
318
-				$this->sp--;
319
-				return $this->Stack[$this->sp];
320
-			}
321
-		}
322
-
323
-		return $Code;
324
-	}
325
-
326
-	///////////////////////////////////////////////////////////////////////////
327
-
328
-	public function GetCode(&$data, $bInit)
329
-	{
330
-		if ($bInit) {
331
-			$this->CurBit   = 0;
332
-			$this->LastBit  = 0;
333
-			$this->Done     = 0;
334
-			$this->LastByte = 2;
335
-			return 1;
336
-		}
337
-
338
-		if (($this->CurBit + $this->CodeSize) >= $this->LastBit) {
339
-			if ($this->Done) {
340
-				if ($this->CurBit >= $this->LastBit) {
341
-					// Ran off the end of my bits
342
-					return 0;
343
-				}
344
-				return -1;
345
-			}
346
-
347
-			$this->Buf[0] = $this->Buf[$this->LastByte - 2];
348
-			$this->Buf[1] = $this->Buf[$this->LastByte - 1];
349
-
350
-			$Count = ord($data{0});
351
-			$data  = substr($data, 1);
352
-
353
-			if ($Count) {
354
-				for ($i = 0; $i < $Count; $i++) {
355
-					$this->Buf[2 + $i] = ord($data{$i});
356
-				}
357
-				$data = substr($data, $Count);
358
-			} else {
359
-				$this->Done = 1;
360
-			}
361
-
362
-			$this->LastByte = 2 + $Count;
363
-			$this->CurBit   = ($this->CurBit - $this->LastBit) + 16;
364
-			$this->LastBit  = (2 + $Count) << 3;
365
-		}
366
-
367
-		$iRet = 0;
368
-		for ($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) {
369
-			$iRet |= (($this->Buf[ (int) ($i / 8) ] & (1 << ($i % 8))) != 0) << $j;
370
-		}
371
-
372
-		$this->CurBit += $this->CodeSize;
373
-		return $iRet;
374
-	}
166
+    public $MAX_LZW_BITS;
167
+    public $Fresh, $CodeSize, $SetCodeSize, $MaxCode, $MaxCodeSize, $FirstCode, $OldCode;
168
+    public $ClearCode, $EndCode, $Next, $Vals, $Stack, $sp, $Buf, $CurBit, $LastBit, $Done, $LastByte;
169
+
170
+    ///////////////////////////////////////////////////////////////////////////
171
+
172
+    // CONSTRUCTOR
173
+    public function __construct()
174
+    {
175
+        $this->MAX_LZW_BITS = 12;
176
+        unSet($this->Next);
177
+        unSet($this->Vals);
178
+        unSet($this->Stack);
179
+        unSet($this->Buf);
180
+
181
+        $this->Next  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
182
+        $this->Vals  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
183
+        $this->Stack = range(0, (1 << ($this->MAX_LZW_BITS + 1)) - 1);
184
+        $this->Buf   = range(0, 279);
185
+    }
186
+
187
+    ///////////////////////////////////////////////////////////////////////////
188
+
189
+    public function deCompress($data, &$datLen)
190
+    {
191
+        $stLen  = strlen($data);
192
+        $datLen = 0;
193
+        $ret    = '';
194
+
195
+        // INITIALIZATION
196
+        $this->LZWCommand($data, true);
197
+
198
+        while (($iIndex = $this->LZWCommand($data, false)) >= 0) {
199
+            $ret .= chr($iIndex);
200
+        }
201
+
202
+        $datLen = $stLen - strlen($data);
203
+
204
+        if ($iIndex != -2) {
205
+            return false;
206
+        }
207
+
208
+        return $ret;
209
+    }
210
+
211
+    ///////////////////////////////////////////////////////////////////////////
212
+
213
+    public function LZWCommand(&$data, $bInit)
214
+    {
215
+        if ($bInit) {
216
+            $this->SetCodeSize = ord($data{0});
217
+            $data = substr($data, 1);
218
+
219
+            $this->CodeSize    = $this->SetCodeSize + 1;
220
+            $this->ClearCode   = 1 << $this->SetCodeSize;
221
+            $this->EndCode     = $this->ClearCode + 1;
222
+            $this->MaxCode     = $this->ClearCode + 2;
223
+            $this->MaxCodeSize = $this->ClearCode << 1;
224
+
225
+            $this->GetCode($data, $bInit);
226
+
227
+            $this->Fresh = 1;
228
+            for ($i = 0; $i < $this->ClearCode; $i++) {
229
+                $this->Next[$i] = 0;
230
+                $this->Vals[$i] = $i;
231
+            }
232
+
233
+            for (; $i < (1 << $this->MAX_LZW_BITS); $i++) {
234
+                $this->Next[$i] = 0;
235
+                $this->Vals[$i] = 0;
236
+            }
237
+
238
+            $this->sp = 0;
239
+            return 1;
240
+        }
241
+
242
+        if ($this->Fresh) {
243
+            $this->Fresh = 0;
244
+            do {
245
+                $this->FirstCode = $this->GetCode($data, $bInit);
246
+                $this->OldCode   = $this->FirstCode;
247
+            }
248
+            while ($this->FirstCode == $this->ClearCode);
249
+
250
+            return $this->FirstCode;
251
+        }
252
+
253
+        if ($this->sp > 0) {
254
+            $this->sp--;
255
+            return $this->Stack[$this->sp];
256
+        }
257
+
258
+        while (($Code = $this->GetCode($data, $bInit)) >= 0) {
259
+            if ($Code == $this->ClearCode) {
260
+                for ($i = 0; $i < $this->ClearCode; $i++) {
261
+                    $this->Next[$i] = 0;
262
+                    $this->Vals[$i] = $i;
263
+                }
264
+
265
+                for (; $i < (1 << $this->MAX_LZW_BITS); $i++) {
266
+                    $this->Next[$i] = 0;
267
+                    $this->Vals[$i] = 0;
268
+                }
269
+
270
+                $this->CodeSize    = $this->SetCodeSize + 1;
271
+                $this->MaxCodeSize = $this->ClearCode << 1;
272
+                $this->MaxCode     = $this->ClearCode + 2;
273
+                $this->sp          = 0;
274
+                $this->FirstCode   = $this->GetCode($data, $bInit);
275
+                $this->OldCode     = $this->FirstCode;
276
+
277
+                return $this->FirstCode;
278
+            }
279
+
280
+            if ($Code == $this->EndCode) {
281
+                return -2;
282
+            }
283
+
284
+            $InCode = $Code;
285
+            if ($Code >= $this->MaxCode) {
286
+                $this->Stack[$this->sp] = $this->FirstCode;
287
+                $this->sp++;
288
+                $Code = $this->OldCode;
289
+            }
290
+
291
+            while ($Code >= $this->ClearCode) {
292
+                $this->Stack[$this->sp] = $this->Vals[$Code];
293
+                $this->sp++;
294
+
295
+                if ($Code == $this->Next[$Code]) // Circular table entry, big GIF Error!
296
+                    return -1;
297
+
298
+                $Code = $this->Next[$Code];
299
+            }
300
+
301
+            $this->FirstCode = $this->Vals[$Code];
302
+            $this->Stack[$this->sp] = $this->FirstCode;
303
+            $this->sp++;
304
+
305
+            if (($Code = $this->MaxCode) < (1 << $this->MAX_LZW_BITS)) {
306
+                $this->Next[$Code] = $this->OldCode;
307
+                $this->Vals[$Code] = $this->FirstCode;
308
+                $this->MaxCode++;
309
+
310
+                if (($this->MaxCode >= $this->MaxCodeSize) && ($this->MaxCodeSize < (1 << $this->MAX_LZW_BITS))) {
311
+                    $this->MaxCodeSize *= 2;
312
+                    $this->CodeSize++;
313
+                }
314
+            }
315
+
316
+            $this->OldCode = $InCode;
317
+            if ($this->sp > 0) {
318
+                $this->sp--;
319
+                return $this->Stack[$this->sp];
320
+            }
321
+        }
322
+
323
+        return $Code;
324
+    }
325
+
326
+    ///////////////////////////////////////////////////////////////////////////
327
+
328
+    public function GetCode(&$data, $bInit)
329
+    {
330
+        if ($bInit) {
331
+            $this->CurBit   = 0;
332
+            $this->LastBit  = 0;
333
+            $this->Done     = 0;
334
+            $this->LastByte = 2;
335
+            return 1;
336
+        }
337
+
338
+        if (($this->CurBit + $this->CodeSize) >= $this->LastBit) {
339
+            if ($this->Done) {
340
+                if ($this->CurBit >= $this->LastBit) {
341
+                    // Ran off the end of my bits
342
+                    return 0;
343
+                }
344
+                return -1;
345
+            }
346
+
347
+            $this->Buf[0] = $this->Buf[$this->LastByte - 2];
348
+            $this->Buf[1] = $this->Buf[$this->LastByte - 1];
349
+
350
+            $Count = ord($data{0});
351
+            $data  = substr($data, 1);
352
+
353
+            if ($Count) {
354
+                for ($i = 0; $i < $Count; $i++) {
355
+                    $this->Buf[2 + $i] = ord($data{$i});
356
+                }
357
+                $data = substr($data, $Count);
358
+            } else {
359
+                $this->Done = 1;
360
+            }
361
+
362
+            $this->LastByte = 2 + $Count;
363
+            $this->CurBit   = ($this->CurBit - $this->LastBit) + 16;
364
+            $this->LastBit  = (2 + $Count) << 3;
365
+        }
366
+
367
+        $iRet = 0;
368
+        for ($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) {
369
+            $iRet |= (($this->Buf[ (int) ($i / 8) ] & (1 << ($i % 8))) != 0) << $j;
370
+        }
371
+
372
+        $this->CurBit += $this->CodeSize;
373
+        return $iRet;
374
+    }
375 375
 }
376 376
 
377 377
 ///////////////////////////////////////////////////////////////////////////////////////////////////
378 378
 
379 379
 class CGIFCOLORTABLE
380 380
 {
381
-	public $m_nColors;
382
-	public $m_arColors;
383
-
384
-	///////////////////////////////////////////////////////////////////////////
385
-
386
-	// CONSTRUCTOR
387
-	public function __construct()
388
-	{
389
-		unSet($this->m_nColors);
390
-		unSet($this->m_arColors);
391
-	}
392
-
393
-	///////////////////////////////////////////////////////////////////////////
394
-
395
-	public function load($lpData, $num)
396
-	{
397
-		$this->m_nColors  = 0;
398
-		$this->m_arColors = array();
399
-
400
-		for ($i = 0; $i < $num; $i++) {
401
-			$rgb = substr($lpData, $i * 3, 3);
402
-			if (strlen($rgb) < 3) {
403
-				return false;
404
-			}
405
-
406
-			$this->m_arColors[] = (ord($rgb{2}) << 16) + (ord($rgb{1}) << 8) + ord($rgb{0});
407
-			$this->m_nColors++;
408
-		}
409
-
410
-		return true;
411
-	}
412
-
413
-	///////////////////////////////////////////////////////////////////////////
414
-
415
-	public function toString()
416
-	{
417
-		$ret = '';
418
-
419
-		for ($i = 0; $i < $this->m_nColors; $i++) {
420
-			$ret .=
421
-				chr(($this->m_arColors[$i] & 0x000000FF))       . // R
422
-				chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
423
-				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16);  // B
424
-		}
425
-
426
-		return $ret;
427
-	}
428
-
429
-	///////////////////////////////////////////////////////////////////////////
430
-
431
-	public function toRGBQuad()
432
-	{
433
-		$ret = '';
434
-
435
-		for ($i = 0; $i < $this->m_nColors; $i++) {
436
-			$ret .=
437
-				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16) . // B
438
-				chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
439
-				chr(($this->m_arColors[$i] & 0x000000FF))       . // R
440
-				"\x00";
441
-		}
442
-
443
-		return $ret;
444
-	}
445
-
446
-	///////////////////////////////////////////////////////////////////////////
447
-
448
-	public function colorIndex($rgb)
449
-	{
450
-		$rgb = (int) $rgb & 0xFFFFFF;
451
-		$r1  = ($rgb & 0x0000FF);
452
-		$g1  = ($rgb & 0x00FF00) >>  8;
453
-		$b1  = ($rgb & 0xFF0000) >> 16;
454
-		$idx = -1;
455
-		$dif = 0;
456
-
457
-		for ($i = 0; $i < $this->m_nColors; $i++) {
458
-			$r2 = ($this->m_arColors[$i] & 0x000000FF);
459
-			$g2 = ($this->m_arColors[$i] & 0x0000FF00) >>  8;
460
-			$b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16;
461
-			$d  = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1);
462
-
463
-			if (($idx == -1) || ($d < $dif)) {
464
-				$idx = $i;
465
-				$dif = $d;
466
-			}
467
-		}
468
-
469
-		return $idx;
470
-	}
381
+    public $m_nColors;
382
+    public $m_arColors;
383
+
384
+    ///////////////////////////////////////////////////////////////////////////
385
+
386
+    // CONSTRUCTOR
387
+    public function __construct()
388
+    {
389
+        unSet($this->m_nColors);
390
+        unSet($this->m_arColors);
391
+    }
392
+
393
+    ///////////////////////////////////////////////////////////////////////////
394
+
395
+    public function load($lpData, $num)
396
+    {
397
+        $this->m_nColors  = 0;
398
+        $this->m_arColors = array();
399
+
400
+        for ($i = 0; $i < $num; $i++) {
401
+            $rgb = substr($lpData, $i * 3, 3);
402
+            if (strlen($rgb) < 3) {
403
+                return false;
404
+            }
405
+
406
+            $this->m_arColors[] = (ord($rgb{2}) << 16) + (ord($rgb{1}) << 8) + ord($rgb{0});
407
+            $this->m_nColors++;
408
+        }
409
+
410
+        return true;
411
+    }
412
+
413
+    ///////////////////////////////////////////////////////////////////////////
414
+
415
+    public function toString()
416
+    {
417
+        $ret = '';
418
+
419
+        for ($i = 0; $i < $this->m_nColors; $i++) {
420
+            $ret .=
421
+                chr(($this->m_arColors[$i] & 0x000000FF))       . // R
422
+                chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
423
+                chr(($this->m_arColors[$i] & 0x00FF0000) >> 16);  // B
424
+        }
425
+
426
+        return $ret;
427
+    }
428
+
429
+    ///////////////////////////////////////////////////////////////////////////
430
+
431
+    public function toRGBQuad()
432
+    {
433
+        $ret = '';
434
+
435
+        for ($i = 0; $i < $this->m_nColors; $i++) {
436
+            $ret .=
437
+                chr(($this->m_arColors[$i] & 0x00FF0000) >> 16) . // B
438
+                chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
439
+                chr(($this->m_arColors[$i] & 0x000000FF))       . // R
440
+                "\x00";
441
+        }
442
+
443
+        return $ret;
444
+    }
445
+
446
+    ///////////////////////////////////////////////////////////////////////////
447
+
448
+    public function colorIndex($rgb)
449
+    {
450
+        $rgb = (int) $rgb & 0xFFFFFF;
451
+        $r1  = ($rgb & 0x0000FF);
452
+        $g1  = ($rgb & 0x00FF00) >>  8;
453
+        $b1  = ($rgb & 0xFF0000) >> 16;
454
+        $idx = -1;
455
+        $dif = 0;
456
+
457
+        for ($i = 0; $i < $this->m_nColors; $i++) {
458
+            $r2 = ($this->m_arColors[$i] & 0x000000FF);
459
+            $g2 = ($this->m_arColors[$i] & 0x0000FF00) >>  8;
460
+            $b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16;
461
+            $d  = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1);
462
+
463
+            if (($idx == -1) || ($d < $dif)) {
464
+                $idx = $i;
465
+                $dif = $d;
466
+            }
467
+        }
468
+
469
+        return $idx;
470
+    }
471 471
 }
472 472
 
473 473
 ///////////////////////////////////////////////////////////////////////////////////////////////////
474 474
 
475 475
 class CGIFFILEHEADER
476 476
 {
477
-	public $m_lpVer;
478
-	public $m_nWidth;
479
-	public $m_nHeight;
480
-	public $m_bGlobalClr;
481
-	public $m_nColorRes;
482
-	public $m_bSorted;
483
-	public $m_nTableSize;
484
-	public $m_nBgColor;
485
-	public $m_nPixelRatio;
486
-	public $m_colorTable;
487
-
488
-	///////////////////////////////////////////////////////////////////////////
489
-
490
-	// CONSTRUCTOR
491
-	public function __construct()
492
-	{
493
-		unSet($this->m_lpVer);
494
-		unSet($this->m_nWidth);
495
-		unSet($this->m_nHeight);
496
-		unSet($this->m_bGlobalClr);
497
-		unSet($this->m_nColorRes);
498
-		unSet($this->m_bSorted);
499
-		unSet($this->m_nTableSize);
500
-		unSet($this->m_nBgColor);
501
-		unSet($this->m_nPixelRatio);
502
-		unSet($this->m_colorTable);
503
-	}
504
-
505
-	///////////////////////////////////////////////////////////////////////////
506
-
507
-	public function load($lpData, &$hdrLen)
508
-	{
509
-		$hdrLen = 0;
510
-
511
-		$this->m_lpVer = substr($lpData, 0, 6);
512
-		if (($this->m_lpVer <> 'GIF87a') && ($this->m_lpVer <> 'GIF89a')) {
513
-			return false;
514
-		}
515
-
516
-		$this->m_nWidth  = $this->w2i(substr($lpData, 6, 2));
517
-		$this->m_nHeight = $this->w2i(substr($lpData, 8, 2));
518
-		if (!$this->m_nWidth || !$this->m_nHeight) {
519
-			return false;
520
-		}
521
-
522
-		$b = ord($lpData[ 10 ]);
523
-		$this->m_bGlobalClr  = ($b & 0x80) ? true : false;
524
-		$this->m_nColorRes   = ($b & 0x70) >> 4;
525
-		$this->m_bSorted     = ($b & 0x08) ? true : false;
526
-		$this->m_nTableSize  = 2 << ($b & 0x07);
527
-		$this->m_nBgColor    = ord($lpData[ 11 ]);
528
-		$this->m_nPixelRatio = ord($lpData[ 12 ]);
529
-		$hdrLen = 13;
530
-
531
-		if ($this->m_bGlobalClr) {
532
-			$this->m_colorTable = new CGIFCOLORTABLE();
533
-			if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) {
534
-				return false;
535
-			}
536
-			$hdrLen += 3 * $this->m_nTableSize;
537
-		}
538
-
539
-		return true;
540
-	}
541
-
542
-	///////////////////////////////////////////////////////////////////////////
543
-
544
-	public function w2i($str)
545
-	{
546
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
547
-	}
477
+    public $m_lpVer;
478
+    public $m_nWidth;
479
+    public $m_nHeight;
480
+    public $m_bGlobalClr;
481
+    public $m_nColorRes;
482
+    public $m_bSorted;
483
+    public $m_nTableSize;
484
+    public $m_nBgColor;
485
+    public $m_nPixelRatio;
486
+    public $m_colorTable;
487
+
488
+    ///////////////////////////////////////////////////////////////////////////
489
+
490
+    // CONSTRUCTOR
491
+    public function __construct()
492
+    {
493
+        unSet($this->m_lpVer);
494
+        unSet($this->m_nWidth);
495
+        unSet($this->m_nHeight);
496
+        unSet($this->m_bGlobalClr);
497
+        unSet($this->m_nColorRes);
498
+        unSet($this->m_bSorted);
499
+        unSet($this->m_nTableSize);
500
+        unSet($this->m_nBgColor);
501
+        unSet($this->m_nPixelRatio);
502
+        unSet($this->m_colorTable);
503
+    }
504
+
505
+    ///////////////////////////////////////////////////////////////////////////
506
+
507
+    public function load($lpData, &$hdrLen)
508
+    {
509
+        $hdrLen = 0;
510
+
511
+        $this->m_lpVer = substr($lpData, 0, 6);
512
+        if (($this->m_lpVer <> 'GIF87a') && ($this->m_lpVer <> 'GIF89a')) {
513
+            return false;
514
+        }
515
+
516
+        $this->m_nWidth  = $this->w2i(substr($lpData, 6, 2));
517
+        $this->m_nHeight = $this->w2i(substr($lpData, 8, 2));
518
+        if (!$this->m_nWidth || !$this->m_nHeight) {
519
+            return false;
520
+        }
521
+
522
+        $b = ord($lpData[ 10 ]);
523
+        $this->m_bGlobalClr  = ($b & 0x80) ? true : false;
524
+        $this->m_nColorRes   = ($b & 0x70) >> 4;
525
+        $this->m_bSorted     = ($b & 0x08) ? true : false;
526
+        $this->m_nTableSize  = 2 << ($b & 0x07);
527
+        $this->m_nBgColor    = ord($lpData[ 11 ]);
528
+        $this->m_nPixelRatio = ord($lpData[ 12 ]);
529
+        $hdrLen = 13;
530
+
531
+        if ($this->m_bGlobalClr) {
532
+            $this->m_colorTable = new CGIFCOLORTABLE();
533
+            if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) {
534
+                return false;
535
+            }
536
+            $hdrLen += 3 * $this->m_nTableSize;
537
+        }
538
+
539
+        return true;
540
+    }
541
+
542
+    ///////////////////////////////////////////////////////////////////////////
543
+
544
+    public function w2i($str)
545
+    {
546
+        return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
547
+    }
548 548
 }
549 549
 
550 550
 ///////////////////////////////////////////////////////////////////////////////////////////////////
551 551
 
552 552
 class CGIFIMAGEHEADER
553 553
 {
554
-	public $m_nLeft;
555
-	public $m_nTop;
556
-	public $m_nWidth;
557
-	public $m_nHeight;
558
-	public $m_bLocalClr;
559
-	public $m_bInterlace;
560
-	public $m_bSorted;
561
-	public $m_nTableSize;
562
-	public $m_colorTable;
563
-
564
-	///////////////////////////////////////////////////////////////////////////
565
-
566
-	// CONSTRUCTOR
567
-	public function __construct()
568
-	{
569
-		unSet($this->m_nLeft);
570
-		unSet($this->m_nTop);
571
-		unSet($this->m_nWidth);
572
-		unSet($this->m_nHeight);
573
-		unSet($this->m_bLocalClr);
574
-		unSet($this->m_bInterlace);
575
-		unSet($this->m_bSorted);
576
-		unSet($this->m_nTableSize);
577
-		unSet($this->m_colorTable);
578
-	}
579
-
580
-	///////////////////////////////////////////////////////////////////////////
581
-
582
-	public function load($lpData, &$hdrLen)
583
-	{
584
-		$hdrLen = 0;
585
-
586
-		$this->m_nLeft   = $this->w2i(substr($lpData, 0, 2));
587
-		$this->m_nTop    = $this->w2i(substr($lpData, 2, 2));
588
-		$this->m_nWidth  = $this->w2i(substr($lpData, 4, 2));
589
-		$this->m_nHeight = $this->w2i(substr($lpData, 6, 2));
590
-
591
-		if (!$this->m_nWidth || !$this->m_nHeight) {
592
-			return false;
593
-		}
594
-
595
-		$b = ord($lpData{8});
596
-		$this->m_bLocalClr  = ($b & 0x80) ? true : false;
597
-		$this->m_bInterlace = ($b & 0x40) ? true : false;
598
-		$this->m_bSorted    = ($b & 0x20) ? true : false;
599
-		$this->m_nTableSize = 2 << ($b & 0x07);
600
-		$hdrLen = 9;
601
-
602
-		if ($this->m_bLocalClr) {
603
-			$this->m_colorTable = new CGIFCOLORTABLE();
604
-			if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) {
605
-				return false;
606
-			}
607
-			$hdrLen += 3 * $this->m_nTableSize;
608
-		}
609
-
610
-		return true;
611
-	}
612
-
613
-	///////////////////////////////////////////////////////////////////////////
614
-
615
-	public function w2i($str)
616
-	{
617
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
618
-	}
554
+    public $m_nLeft;
555
+    public $m_nTop;
556
+    public $m_nWidth;
557
+    public $m_nHeight;
558
+    public $m_bLocalClr;
559
+    public $m_bInterlace;
560
+    public $m_bSorted;
561
+    public $m_nTableSize;
562
+    public $m_colorTable;
563
+
564
+    ///////////////////////////////////////////////////////////////////////////
565
+
566
+    // CONSTRUCTOR
567
+    public function __construct()
568
+    {
569
+        unSet($this->m_nLeft);
570
+        unSet($this->m_nTop);
571
+        unSet($this->m_nWidth);
572
+        unSet($this->m_nHeight);
573
+        unSet($this->m_bLocalClr);
574
+        unSet($this->m_bInterlace);
575
+        unSet($this->m_bSorted);
576
+        unSet($this->m_nTableSize);
577
+        unSet($this->m_colorTable);
578
+    }
579
+
580
+    ///////////////////////////////////////////////////////////////////////////
581
+
582
+    public function load($lpData, &$hdrLen)
583
+    {
584
+        $hdrLen = 0;
585
+
586
+        $this->m_nLeft   = $this->w2i(substr($lpData, 0, 2));
587
+        $this->m_nTop    = $this->w2i(substr($lpData, 2, 2));
588
+        $this->m_nWidth  = $this->w2i(substr($lpData, 4, 2));
589
+        $this->m_nHeight = $this->w2i(substr($lpData, 6, 2));
590
+
591
+        if (!$this->m_nWidth || !$this->m_nHeight) {
592
+            return false;
593
+        }
594
+
595
+        $b = ord($lpData{8});
596
+        $this->m_bLocalClr  = ($b & 0x80) ? true : false;
597
+        $this->m_bInterlace = ($b & 0x40) ? true : false;
598
+        $this->m_bSorted    = ($b & 0x20) ? true : false;
599
+        $this->m_nTableSize = 2 << ($b & 0x07);
600
+        $hdrLen = 9;
601
+
602
+        if ($this->m_bLocalClr) {
603
+            $this->m_colorTable = new CGIFCOLORTABLE();
604
+            if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) {
605
+                return false;
606
+            }
607
+            $hdrLen += 3 * $this->m_nTableSize;
608
+        }
609
+
610
+        return true;
611
+    }
612
+
613
+    ///////////////////////////////////////////////////////////////////////////
614
+
615
+    public function w2i($str)
616
+    {
617
+        return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
618
+    }
619 619
 }
620 620
 
621 621
 ///////////////////////////////////////////////////////////////////////////////////////////////////
622 622
 
623 623
 class CGIFIMAGE
624 624
 {
625
-	public $m_disp;
626
-	public $m_bUser;
627
-	public $m_bTrans;
628
-	public $m_nDelay;
629
-	public $m_nTrans;
630
-	public $m_lpComm;
631
-	public $m_gih;
632
-	public $m_data;
633
-	public $m_lzw;
634
-
635
-	///////////////////////////////////////////////////////////////////////////
636
-
637
-	public function __construct()
638
-	{
639
-		unSet($this->m_disp);
640
-		unSet($this->m_bUser);
641
-		unSet($this->m_bTrans);
642
-		unSet($this->m_nDelay);
643
-		unSet($this->m_nTrans);
644
-		unSet($this->m_lpComm);
645
-		unSet($this->m_data);
646
-		$this->m_gih = new CGIFIMAGEHEADER();
647
-		$this->m_lzw = new CGIFLZW();
648
-	}
649
-
650
-	///////////////////////////////////////////////////////////////////////////
651
-
652
-	public function load($data, &$datLen)
653
-	{
654
-		$datLen = 0;
655
-
656
-		while (true) {
657
-			$b = ord($data{0});
658
-			$data = substr($data, 1);
659
-			$datLen++;
660
-
661
-			switch($b) {
662
-			case 0x21: // Extension
663
-				if (!$this->skipExt($data, $len = 0)) {
664
-					return false;
665
-				}
666
-				$datLen += $len;
667
-				break;
668
-
669
-			case 0x2C: // Image
670
-				// LOAD HEADER & COLOR TABLE
671
-				if (!$this->m_gih->load($data, $len = 0)) {
672
-					return false;
673
-				}
674
-				$data = substr($data, $len);
675
-				$datLen += $len;
676
-
677
-				// ALLOC BUFFER
678
-				if (!($this->m_data = $this->m_lzw->deCompress($data, $len = 0))) {
679
-					return false;
680
-				}
681
-				$data = substr($data, $len);
682
-				$datLen += $len;
683
-
684
-				if ($this->m_gih->m_bInterlace) {
685
-					$this->deInterlace();
686
-				}
687
-				return true;
688
-
689
-			case 0x3B: // EOF
690
-			default:
691
-				return false;
692
-			}
693
-		}
694
-		return false;
695
-	}
696
-
697
-	///////////////////////////////////////////////////////////////////////////
698
-
699
-	public function skipExt(&$data, &$extLen)
700
-	{
701
-		$extLen = 0;
702
-
703
-		$b = ord($data{0});
704
-		$data = substr($data, 1);
705
-		$extLen++;
706
-
707
-		switch($b) {
708
-		case 0xF9: // Graphic Control
709
-			$b = ord($data{1});
710
-			$this->m_disp   = ($b & 0x1C) >> 2;
711
-			$this->m_bUser  = ($b & 0x02) ? true : false;
712
-			$this->m_bTrans = ($b & 0x01) ? true : false;
713
-			$this->m_nDelay = $this->w2i(substr($data, 2, 2));
714
-			$this->m_nTrans = ord($data{4});
715
-			break;
716
-
717
-		case 0xFE: // Comment
718
-			$this->m_lpComm = substr($data, 1, ord($data{0}));
719
-			break;
720
-
721
-		case 0x01: // Plain text
722
-			break;
723
-
724
-		case 0xFF: // Application
725
-			break;
726
-		}
727
-
728
-		// SKIP DEFAULT AS DEFS MAY CHANGE
729
-		$b = ord($data{0});
730
-		$data = substr($data, 1);
731
-		$extLen++;
732
-		while ($b > 0) {
733
-			$data = substr($data, $b);
734
-			$extLen += $b;
735
-			$b    = ord($data{0});
736
-			$data = substr($data, 1);
737
-			$extLen++;
738
-		}
739
-		return true;
740
-	}
741
-
742
-	///////////////////////////////////////////////////////////////////////////
743
-
744
-	public function w2i($str)
745
-	{
746
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
747
-	}
748
-
749
-	///////////////////////////////////////////////////////////////////////////
750
-
751
-	public function deInterlace()
752
-	{
753
-		$data = $this->m_data;
754
-		$s = 0;
755
-		$y = 0;
756
-
757
-		for ($i = 0; $i < 4; $i++) {
758
-			switch($i) {
759
-			case 0:
760
-				$s = 8;
761
-				$y = 0;
762
-				break;
763
-
764
-			case 1:
765
-				$s = 8;
766
-				$y = 4;
767
-				break;
768
-
769
-			case 2:
770
-				$s = 4;
771
-				$y = 2;
772
-				break;
773
-
774
-			case 3:
775
-				$s = 2;
776
-				$y = 1;
777
-				break;
778
-			}
779
-
780
-			for (; $y < $this->m_gih->m_nHeight; $y += $s) {
781
-				$lne = substr($this->m_data, 0, $this->m_gih->m_nWidth);
782
-				$this->m_data = substr($this->m_data, $this->m_gih->m_nWidth);
783
-
784
-				$data =
785
-					substr($data, 0, $y * $this->m_gih->m_nWidth) .
786
-					$lne .
787
-					substr($data, ($y + 1) * $this->m_gih->m_nWidth);
788
-			}
789
-		}
790
-
791
-		$this->m_data = $data;
792
-	}
625
+    public $m_disp;
626
+    public $m_bUser;
627
+    public $m_bTrans;
628
+    public $m_nDelay;
629
+    public $m_nTrans;
630
+    public $m_lpComm;
631
+    public $m_gih;
632
+    public $m_data;
633
+    public $m_lzw;
634
+
635
+    ///////////////////////////////////////////////////////////////////////////
636
+
637
+    public function __construct()
638
+    {
639
+        unSet($this->m_disp);
640
+        unSet($this->m_bUser);
641
+        unSet($this->m_bTrans);
642
+        unSet($this->m_nDelay);
643
+        unSet($this->m_nTrans);
644
+        unSet($this->m_lpComm);
645
+        unSet($this->m_data);
646
+        $this->m_gih = new CGIFIMAGEHEADER();
647
+        $this->m_lzw = new CGIFLZW();
648
+    }
649
+
650
+    ///////////////////////////////////////////////////////////////////////////
651
+
652
+    public function load($data, &$datLen)
653
+    {
654
+        $datLen = 0;
655
+
656
+        while (true) {
657
+            $b = ord($data{0});
658
+            $data = substr($data, 1);
659
+            $datLen++;
660
+
661
+            switch($b) {
662
+            case 0x21: // Extension
663
+                if (!$this->skipExt($data, $len = 0)) {
664
+                    return false;
665
+                }
666
+                $datLen += $len;
667
+                break;
668
+
669
+            case 0x2C: // Image
670
+                // LOAD HEADER & COLOR TABLE
671
+                if (!$this->m_gih->load($data, $len = 0)) {
672
+                    return false;
673
+                }
674
+                $data = substr($data, $len);
675
+                $datLen += $len;
676
+
677
+                // ALLOC BUFFER
678
+                if (!($this->m_data = $this->m_lzw->deCompress($data, $len = 0))) {
679
+                    return false;
680
+                }
681
+                $data = substr($data, $len);
682
+                $datLen += $len;
683
+
684
+                if ($this->m_gih->m_bInterlace) {
685
+                    $this->deInterlace();
686
+                }
687
+                return true;
688
+
689
+            case 0x3B: // EOF
690
+            default:
691
+                return false;
692
+            }
693
+        }
694
+        return false;
695
+    }
696
+
697
+    ///////////////////////////////////////////////////////////////////////////
698
+
699
+    public function skipExt(&$data, &$extLen)
700
+    {
701
+        $extLen = 0;
702
+
703
+        $b = ord($data{0});
704
+        $data = substr($data, 1);
705
+        $extLen++;
706
+
707
+        switch($b) {
708
+        case 0xF9: // Graphic Control
709
+            $b = ord($data{1});
710
+            $this->m_disp   = ($b & 0x1C) >> 2;
711
+            $this->m_bUser  = ($b & 0x02) ? true : false;
712
+            $this->m_bTrans = ($b & 0x01) ? true : false;
713
+            $this->m_nDelay = $this->w2i(substr($data, 2, 2));
714
+            $this->m_nTrans = ord($data{4});
715
+            break;
716
+
717
+        case 0xFE: // Comment
718
+            $this->m_lpComm = substr($data, 1, ord($data{0}));
719
+            break;
720
+
721
+        case 0x01: // Plain text
722
+            break;
723
+
724
+        case 0xFF: // Application
725
+            break;
726
+        }
727
+
728
+        // SKIP DEFAULT AS DEFS MAY CHANGE
729
+        $b = ord($data{0});
730
+        $data = substr($data, 1);
731
+        $extLen++;
732
+        while ($b > 0) {
733
+            $data = substr($data, $b);
734
+            $extLen += $b;
735
+            $b    = ord($data{0});
736
+            $data = substr($data, 1);
737
+            $extLen++;
738
+        }
739
+        return true;
740
+    }
741
+
742
+    ///////////////////////////////////////////////////////////////////////////
743
+
744
+    public function w2i($str)
745
+    {
746
+        return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
747
+    }
748
+
749
+    ///////////////////////////////////////////////////////////////////////////
750
+
751
+    public function deInterlace()
752
+    {
753
+        $data = $this->m_data;
754
+        $s = 0;
755
+        $y = 0;
756
+
757
+        for ($i = 0; $i < 4; $i++) {
758
+            switch($i) {
759
+            case 0:
760
+                $s = 8;
761
+                $y = 0;
762
+                break;
763
+
764
+            case 1:
765
+                $s = 8;
766
+                $y = 4;
767
+                break;
768
+
769
+            case 2:
770
+                $s = 4;
771
+                $y = 2;
772
+                break;
773
+
774
+            case 3:
775
+                $s = 2;
776
+                $y = 1;
777
+                break;
778
+            }
779
+
780
+            for (; $y < $this->m_gih->m_nHeight; $y += $s) {
781
+                $lne = substr($this->m_data, 0, $this->m_gih->m_nWidth);
782
+                $this->m_data = substr($this->m_data, $this->m_gih->m_nWidth);
783
+
784
+                $data =
785
+                    substr($data, 0, $y * $this->m_gih->m_nWidth) .
786
+                    $lne .
787
+                    substr($data, ($y + 1) * $this->m_gih->m_nWidth);
788
+            }
789
+        }
790
+
791
+        $this->m_data = $data;
792
+    }
793 793
 }
794 794
 
795 795
 ///////////////////////////////////////////////////////////////////////////////////////////////////
796 796
 
797 797
 class CGIF
798 798
 {
799
-	public $m_gfh;
800
-	public $m_lpData;
801
-	public $m_img;
802
-	public $m_bLoaded;
803
-
804
-	///////////////////////////////////////////////////////////////////////////
805
-
806
-	// CONSTRUCTOR
807
-	public function __construct()
808
-	{
809
-		$this->m_gfh     = new CGIFFILEHEADER();
810
-		$this->m_img     = new CGIFIMAGE();
811
-		$this->m_lpData  = '';
812
-		$this->m_bLoaded = false;
813
-	}
814
-
815
-	///////////////////////////////////////////////////////////////////////////
816
-
817
-	public function loadFile($lpszFileName, $iIndex)
818
-	{
819
-		if ($iIndex < 0) {
820
-			return false;
821
-		}
822
-
823
-		// READ FILE
824
-		if (!($fh = @fopen($lpszFileName, 'rb'))) {
825
-			return false;
826
-		}
827
-		$this->m_lpData = @fread($fh, @filesize($lpszFileName));
828
-		fclose($fh);
829
-
830
-		// GET FILE HEADER
831
-		if (!$this->m_gfh->load($this->m_lpData, $len = 0)) {
832
-			return false;
833
-		}
834
-		$this->m_lpData = substr($this->m_lpData, $len);
835
-
836
-		do {
837
-			if (!$this->m_img->load($this->m_lpData, $imgLen = 0)) {
838
-				return false;
839
-			}
840
-			$this->m_lpData = substr($this->m_lpData, $imgLen);
841
-		}
842
-		while ($iIndex-- > 0);
843
-
844
-		$this->m_bLoaded = true;
845
-		return true;
846
-	}
847
-
848
-	///////////////////////////////////////////////////////////////////////////
849
-
850
-	public function getSize($lpszFileName, &$width, &$height)
851
-	{
852
-		if (!($fh = @fopen($lpszFileName, 'rb'))) {
853
-			return false;
854
-		}
855
-		$data = @fread($fh, @filesize($lpszFileName));
856
-		@fclose($fh);
857
-
858
-		$gfh = new CGIFFILEHEADER();
859
-		if (!$gfh->load($data, $len = 0)) {
860
-			return false;
861
-		}
862
-
863
-		$width  = $gfh->m_nWidth;
864
-		$height = $gfh->m_nHeight;
865
-		return true;
866
-	}
867
-
868
-	///////////////////////////////////////////////////////////////////////////
869
-
870
-	public function getBmp($bgColor)
871
-	{
872
-		$out = '';
873
-
874
-		if (!$this->m_bLoaded) {
875
-			return false;
876
-		}
877
-
878
-		// PREPARE COLOR TABLE (RGBQUADs)
879
-		if ($this->m_img->m_gih->m_bLocalClr) {
880
-			$nColors = $this->m_img->m_gih->m_nTableSize;
881
-			$rgbq    = $this->m_img->m_gih->m_colorTable->toRGBQuad();
882
-			if ($bgColor != -1) {
883
-				$bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor);
884
-			}
885
-		} elseif ($this->m_gfh->m_bGlobalClr) {
886
-			$nColors = $this->m_gfh->m_nTableSize;
887
-			$rgbq    = $this->m_gfh->m_colorTable->toRGBQuad();
888
-			if ($bgColor != -1) {
889
-				$bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
890
-			}
891
-		} else {
892
-			$nColors =  0;
893
-			$rgbq    = '';
894
-			$bgColor = -1;
895
-		}
896
-
897
-		// PREPARE BITMAP BITS
898
-		$data = $this->m_img->m_data;
899
-		$nPxl = ($this->m_gfh->m_nHeight - 1) * $this->m_gfh->m_nWidth;
900
-		$bmp  = '';
901
-		$nPad = ($this->m_gfh->m_nWidth % 4) ? 4 - ($this->m_gfh->m_nWidth % 4) : 0;
902
-		for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
903
-			for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
904
-				if (
905
-					($x >= $this->m_img->m_gih->m_nLeft) &&
906
-					($y >= $this->m_img->m_gih->m_nTop) &&
907
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
908
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
909
-					// PART OF IMAGE
910
-					if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
911
-						// TRANSPARENT -> BACKGROUND
912
-						if ($bgColor == -1) {
913
-							$bmp .= chr($this->m_gfh->m_nBgColor);
914
-						} else {
915
-							$bmp .= chr($bgColor);
916
-						}
917
-					} else {
918
-						$bmp .= $data{$nPxl};
919
-					}
920
-				} else {
921
-					// BACKGROUND
922
-					if ($bgColor == -1) {
923
-						$bmp .= chr($this->m_gfh->m_nBgColor);
924
-					} else {
925
-						$bmp .= chr($bgColor);
926
-					}
927
-				}
928
-			}
929
-			$nPxl -= $this->m_gfh->m_nWidth << 1;
930
-
931
-			// ADD PADDING
932
-			for ($x = 0; $x < $nPad; $x++) {
933
-				$bmp .= "\x00";
934
-			}
935
-		}
936
-
937
-		// BITMAPFILEHEADER
938
-		$out .= 'BM';
939
-		$out .= $this->dword(14 + 40 + ($nColors << 2) + strlen($bmp));
940
-		$out .= "\x00\x00";
941
-		$out .= "\x00\x00";
942
-		$out .= $this->dword(14 + 40 + ($nColors << 2));
943
-
944
-		// BITMAPINFOHEADER
945
-		$out .= $this->dword(40);
946
-		$out .= $this->dword($this->m_gfh->m_nWidth);
947
-		$out .= $this->dword($this->m_gfh->m_nHeight);
948
-		$out .= "\x01\x00";
949
-		$out .= "\x08\x00";
950
-		$out .= "\x00\x00\x00\x00";
951
-		$out .= "\x00\x00\x00\x00";
952
-		$out .= "\x12\x0B\x00\x00";
953
-		$out .= "\x12\x0B\x00\x00";
954
-		$out .= $this->dword($nColors % 256);
955
-		$out .= "\x00\x00\x00\x00";
956
-
957
-		// COLOR TABLE
958
-		if ($nColors > 0) {
959
-			$out .= $rgbq;
960
-		}
961
-
962
-		// DATA
963
-		$out .= $bmp;
964
-
965
-		return $out;
966
-	}
967
-
968
-	///////////////////////////////////////////////////////////////////////////
969
-
970
-	public function getPng($bgColor)
971
-	{
972
-		$out = '';
973
-
974
-		if (!$this->m_bLoaded) {
975
-			return false;
976
-		}
977
-
978
-		// PREPARE COLOR TABLE (RGBQUADs)
979
-		if ($this->m_img->m_gih->m_bLocalClr) {
980
-			$nColors = $this->m_img->m_gih->m_nTableSize;
981
-			$pal     = $this->m_img->m_gih->m_colorTable->toString();
982
-			if ($bgColor != -1) {
983
-				$bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor);
984
-			}
985
-		} elseif ($this->m_gfh->m_bGlobalClr) {
986
-			$nColors = $this->m_gfh->m_nTableSize;
987
-			$pal     = $this->m_gfh->m_colorTable->toString();
988
-			if ($bgColor != -1) {
989
-				$bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
990
-			}
991
-		} else {
992
-			$nColors =  0;
993
-			$pal     = '';
994
-			$bgColor = -1;
995
-		}
996
-
997
-		// PREPARE BITMAP BITS
998
-		$data = $this->m_img->m_data;
999
-		$nPxl = 0;
1000
-		$bmp  = '';
1001
-		for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
1002
-			$bmp .= "\x00";
1003
-			for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
1004
-				if (
1005
-					($x >= $this->m_img->m_gih->m_nLeft) &&
1006
-					($y >= $this->m_img->m_gih->m_nTop) &&
1007
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1008
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1009
-					// PART OF IMAGE
1010
-					$bmp .= $data{$nPxl};
1011
-				} else {
1012
-					// BACKGROUND
1013
-					if ($bgColor == -1) {
1014
-						$bmp .= chr($this->m_gfh->m_nBgColor);
1015
-					} else {
1016
-						$bmp .= chr($bgColor);
1017
-					}
1018
-				}
1019
-			}
1020
-		}
1021
-		$bmp = gzcompress($bmp, 9);
1022
-
1023
-		///////////////////////////////////////////////////////////////////////
1024
-		// SIGNATURE
1025
-		$out .= "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
1026
-		///////////////////////////////////////////////////////////////////////
1027
-		// HEADER
1028
-		$out .= "\x00\x00\x00\x0D";
1029
-		$tmp  = 'IHDR';
1030
-		$tmp .= $this->ndword($this->m_gfh->m_nWidth);
1031
-		$tmp .= $this->ndword($this->m_gfh->m_nHeight);
1032
-		$tmp .= "\x08\x03\x00\x00\x00";
1033
-		$out .= $tmp;
1034
-		$out .= $this->ndword(crc32($tmp));
1035
-		///////////////////////////////////////////////////////////////////////
1036
-		// PALETTE
1037
-		if ($nColors > 0) {
1038
-			$out .= $this->ndword($nColors * 3);
1039
-			$tmp  = 'PLTE';
1040
-			$tmp .= $pal;
1041
-			$out .= $tmp;
1042
-			$out .= $this->ndword(crc32($tmp));
1043
-		}
1044
-		///////////////////////////////////////////////////////////////////////
1045
-		// TRANSPARENCY
1046
-		if (@$this->m_img->m_bTrans && ($nColors > 0)) {
1047
-			$out .= $this->ndword($nColors);
1048
-			$tmp  = 'tRNS';
1049
-			for ($i = 0; $i < $nColors; $i++) {
1050
-				$tmp .= ($i == $this->m_img->m_nTrans) ? "\x00" : "\xFF";
1051
-			}
1052
-			$out .= $tmp;
1053
-			$out .= $this->ndword(crc32($tmp));
1054
-		}
1055
-		///////////////////////////////////////////////////////////////////////
1056
-		// DATA BITS
1057
-		$out .= $this->ndword(strlen($bmp));
1058
-		$tmp  = 'IDAT';
1059
-		$tmp .= $bmp;
1060
-		$out .= $tmp;
1061
-		$out .= $this->ndword(crc32($tmp));
1062
-		///////////////////////////////////////////////////////////////////////
1063
-		// END OF FILE
1064
-		$out .= "\x00\x00\x00\x00IEND\xAE\x42\x60\x82";
1065
-
1066
-		return $out;
1067
-	}
1068
-
1069
-	///////////////////////////////////////////////////////////////////////////
1070
-
1071
-	// Added by James Heinrich <[email protected]> - January 5, 2003
1072
-
1073
-	// Takes raw image data and plots it pixel-by-pixel on a new GD image and returns that
1074
-	// It's extremely slow, but the only solution when imagecreatefromstring() fails
1075
-	public function getGD_PixelPlotterVersion()
1076
-	{
1077
-		if (!$this->m_bLoaded) {
1078
-			return false;
1079
-		}
1080
-
1081
-		// PREPARE COLOR TABLE (RGBQUADs)
1082
-		if ($this->m_img->m_gih->m_bLocalClr) {
1083
-			$pal = $this->m_img->m_gih->m_colorTable->toString();
1084
-		} elseif ($this->m_gfh->m_bGlobalClr) {
1085
-			$pal = $this->m_gfh->m_colorTable->toString();
1086
-		} else {
1087
-			die('No color table available in getGD_PixelPlotterVersion()');
1088
-		}
1089
-
1090
-		$PlottingIMG = imagecreate($this->m_gfh->m_nWidth, $this->m_gfh->m_nHeight);
1091
-		$NumColorsInPal = floor(strlen($pal) / 3);
1092
-		$ThisImageColor = array();
1093
-		for ($i = 0; $i < $NumColorsInPal; $i++) {
1094
-			$ThisImageColor[$i] = imagecolorallocate(
1095
-									$PlottingIMG,
1096
-									ord($pal{(($i * 3) + 0)}),
1097
-									ord($pal{(($i * 3) + 1)}),
1098
-									ord($pal{(($i * 3) + 2)}));
1099
-		}
1100
-
1101
-		// PREPARE BITMAP BITS
1102
-		$data = $this->m_img->m_data;
1103
-		$nPxl = ($this->m_gfh->m_nHeight - 1) * $this->m_gfh->m_nWidth;
1104
-		for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
1105
-			if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
1106
-				set_time_limit(30);
1107
-			}
1108
-			for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
1109
-				if (
1110
-					($x >= $this->m_img->m_gih->m_nLeft) &&
1111
-					($y >= $this->m_img->m_gih->m_nTop) &&
1112
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1113
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1114
-					// PART OF IMAGE
1115
-					if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
1116
-						imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[$this->m_gfh->m_nBgColor]);
1117
-					} else {
1118
-						imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[ord($data{$nPxl})]);
1119
-					}
1120
-				} else {
1121
-					// BACKGROUND
1122
-					imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[$this->m_gfh->m_nBgColor]);
1123
-				}
1124
-			}
1125
-			$nPxl -= $this->m_gfh->m_nWidth << 1;
1126
-
1127
-		}
1128
-
1129
-		return $PlottingIMG;
1130
-	}
1131
-
1132
-	///////////////////////////////////////////////////////////////////////////
1133
-
1134
-	public function dword($val)
1135
-	{
1136
-		$val = (int) $val;
1137
-		return chr($val & 0xFF).chr(($val & 0xFF00) >> 8).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF000000) >> 24);
1138
-	}
1139
-
1140
-	///////////////////////////////////////////////////////////////////////////
1141
-
1142
-	public function ndword($val)
1143
-	{
1144
-		$val = (int) $val;
1145
-		return chr(($val & 0xFF000000) >> 24).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF00) >> 8).chr($val & 0xFF);
1146
-	}
1147
-
1148
-	///////////////////////////////////////////////////////////////////////////
1149
-
1150
-	public function width()
1151
-	{
1152
-		return $this->m_gfh->m_nWidth;
1153
-	}
1154
-
1155
-	///////////////////////////////////////////////////////////////////////////
1156
-
1157
-	public function height()
1158
-	{
1159
-		return $this->m_gfh->m_nHeight;
1160
-	}
1161
-
1162
-	///////////////////////////////////////////////////////////////////////////
1163
-
1164
-	public function comment()
1165
-	{
1166
-		return $this->m_img->m_lpComm;
1167
-	}
1168
-
1169
-	///////////////////////////////////////////////////////////////////////////
1170
-
1171
-	public function loaded()
1172
-	{
1173
-		return $this->m_bLoaded;
1174
-	}
799
+    public $m_gfh;
800
+    public $m_lpData;
801
+    public $m_img;
802
+    public $m_bLoaded;
803
+
804
+    ///////////////////////////////////////////////////////////////////////////
805
+
806
+    // CONSTRUCTOR
807
+    public function __construct()
808
+    {
809
+        $this->m_gfh     = new CGIFFILEHEADER();
810
+        $this->m_img     = new CGIFIMAGE();
811
+        $this->m_lpData  = '';
812
+        $this->m_bLoaded = false;
813
+    }
814
+
815
+    ///////////////////////////////////////////////////////////////////////////
816
+
817
+    public function loadFile($lpszFileName, $iIndex)
818
+    {
819
+        if ($iIndex < 0) {
820
+            return false;
821
+        }
822
+
823
+        // READ FILE
824
+        if (!($fh = @fopen($lpszFileName, 'rb'))) {
825
+            return false;
826
+        }
827
+        $this->m_lpData = @fread($fh, @filesize($lpszFileName));
828
+        fclose($fh);
829
+
830
+        // GET FILE HEADER
831
+        if (!$this->m_gfh->load($this->m_lpData, $len = 0)) {
832
+            return false;
833
+        }
834
+        $this->m_lpData = substr($this->m_lpData, $len);
835
+
836
+        do {
837
+            if (!$this->m_img->load($this->m_lpData, $imgLen = 0)) {
838
+                return false;
839
+            }
840
+            $this->m_lpData = substr($this->m_lpData, $imgLen);
841
+        }
842
+        while ($iIndex-- > 0);
843
+
844
+        $this->m_bLoaded = true;
845
+        return true;
846
+    }
847
+
848
+    ///////////////////////////////////////////////////////////////////////////
849
+
850
+    public function getSize($lpszFileName, &$width, &$height)
851
+    {
852
+        if (!($fh = @fopen($lpszFileName, 'rb'))) {
853
+            return false;
854
+        }
855
+        $data = @fread($fh, @filesize($lpszFileName));
856
+        @fclose($fh);
857
+
858
+        $gfh = new CGIFFILEHEADER();
859
+        if (!$gfh->load($data, $len = 0)) {
860
+            return false;
861
+        }
862
+
863
+        $width  = $gfh->m_nWidth;
864
+        $height = $gfh->m_nHeight;
865
+        return true;
866
+    }
867
+
868
+    ///////////////////////////////////////////////////////////////////////////
869
+
870
+    public function getBmp($bgColor)
871
+    {
872
+        $out = '';
873
+
874
+        if (!$this->m_bLoaded) {
875
+            return false;
876
+        }
877
+
878
+        // PREPARE COLOR TABLE (RGBQUADs)
879
+        if ($this->m_img->m_gih->m_bLocalClr) {
880
+            $nColors = $this->m_img->m_gih->m_nTableSize;
881
+            $rgbq    = $this->m_img->m_gih->m_colorTable->toRGBQuad();
882
+            if ($bgColor != -1) {
883
+                $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor);
884
+            }
885
+        } elseif ($this->m_gfh->m_bGlobalClr) {
886
+            $nColors = $this->m_gfh->m_nTableSize;
887
+            $rgbq    = $this->m_gfh->m_colorTable->toRGBQuad();
888
+            if ($bgColor != -1) {
889
+                $bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
890
+            }
891
+        } else {
892
+            $nColors =  0;
893
+            $rgbq    = '';
894
+            $bgColor = -1;
895
+        }
896
+
897
+        // PREPARE BITMAP BITS
898
+        $data = $this->m_img->m_data;
899
+        $nPxl = ($this->m_gfh->m_nHeight - 1) * $this->m_gfh->m_nWidth;
900
+        $bmp  = '';
901
+        $nPad = ($this->m_gfh->m_nWidth % 4) ? 4 - ($this->m_gfh->m_nWidth % 4) : 0;
902
+        for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
903
+            for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
904
+                if (
905
+                    ($x >= $this->m_img->m_gih->m_nLeft) &&
906
+                    ($y >= $this->m_img->m_gih->m_nTop) &&
907
+                    ($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
908
+                    ($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
909
+                    // PART OF IMAGE
910
+                    if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
911
+                        // TRANSPARENT -> BACKGROUND
912
+                        if ($bgColor == -1) {
913
+                            $bmp .= chr($this->m_gfh->m_nBgColor);
914
+                        } else {
915
+                            $bmp .= chr($bgColor);
916
+                        }
917
+                    } else {
918
+                        $bmp .= $data{$nPxl};
919
+                    }
920
+                } else {
921
+                    // BACKGROUND
922
+                    if ($bgColor == -1) {
923
+                        $bmp .= chr($this->m_gfh->m_nBgColor);
924
+                    } else {
925
+                        $bmp .= chr($bgColor);
926
+                    }
927
+                }
928
+            }
929
+            $nPxl -= $this->m_gfh->m_nWidth << 1;
930
+
931
+            // ADD PADDING
932
+            for ($x = 0; $x < $nPad; $x++) {
933
+                $bmp .= "\x00";
934
+            }
935
+        }
936
+
937
+        // BITMAPFILEHEADER
938
+        $out .= 'BM';
939
+        $out .= $this->dword(14 + 40 + ($nColors << 2) + strlen($bmp));
940
+        $out .= "\x00\x00";
941
+        $out .= "\x00\x00";
942
+        $out .= $this->dword(14 + 40 + ($nColors << 2));
943
+
944
+        // BITMAPINFOHEADER
945
+        $out .= $this->dword(40);
946
+        $out .= $this->dword($this->m_gfh->m_nWidth);
947
+        $out .= $this->dword($this->m_gfh->m_nHeight);
948
+        $out .= "\x01\x00";
949
+        $out .= "\x08\x00";
950
+        $out .= "\x00\x00\x00\x00";
951
+        $out .= "\x00\x00\x00\x00";
952
+        $out .= "\x12\x0B\x00\x00";
953
+        $out .= "\x12\x0B\x00\x00";
954
+        $out .= $this->dword($nColors % 256);
955
+        $out .= "\x00\x00\x00\x00";
956
+
957
+        // COLOR TABLE
958
+        if ($nColors > 0) {
959
+            $out .= $rgbq;
960
+        }
961
+
962
+        // DATA
963
+        $out .= $bmp;
964
+
965
+        return $out;
966
+    }
967
+
968
+    ///////////////////////////////////////////////////////////////////////////
969
+
970
+    public function getPng($bgColor)
971
+    {
972
+        $out = '';
973
+
974
+        if (!$this->m_bLoaded) {
975
+            return false;
976
+        }
977
+
978
+        // PREPARE COLOR TABLE (RGBQUADs)
979
+        if ($this->m_img->m_gih->m_bLocalClr) {
980
+            $nColors = $this->m_img->m_gih->m_nTableSize;
981
+            $pal     = $this->m_img->m_gih->m_colorTable->toString();
982
+            if ($bgColor != -1) {
983
+                $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor);
984
+            }
985
+        } elseif ($this->m_gfh->m_bGlobalClr) {
986
+            $nColors = $this->m_gfh->m_nTableSize;
987
+            $pal     = $this->m_gfh->m_colorTable->toString();
988
+            if ($bgColor != -1) {
989
+                $bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
990
+            }
991
+        } else {
992
+            $nColors =  0;
993
+            $pal     = '';
994
+            $bgColor = -1;
995
+        }
996
+
997
+        // PREPARE BITMAP BITS
998
+        $data = $this->m_img->m_data;
999
+        $nPxl = 0;
1000
+        $bmp  = '';
1001
+        for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
1002
+            $bmp .= "\x00";
1003
+            for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
1004
+                if (
1005
+                    ($x >= $this->m_img->m_gih->m_nLeft) &&
1006
+                    ($y >= $this->m_img->m_gih->m_nTop) &&
1007
+                    ($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1008
+                    ($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1009
+                    // PART OF IMAGE
1010
+                    $bmp .= $data{$nPxl};
1011
+                } else {
1012
+                    // BACKGROUND
1013
+                    if ($bgColor == -1) {
1014
+                        $bmp .= chr($this->m_gfh->m_nBgColor);
1015
+                    } else {
1016
+                        $bmp .= chr($bgColor);
1017
+                    }
1018
+                }
1019
+            }
1020
+        }
1021
+        $bmp = gzcompress($bmp, 9);
1022
+
1023
+        ///////////////////////////////////////////////////////////////////////
1024
+        // SIGNATURE
1025
+        $out .= "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
1026
+        ///////////////////////////////////////////////////////////////////////
1027
+        // HEADER
1028
+        $out .= "\x00\x00\x00\x0D";
1029
+        $tmp  = 'IHDR';
1030
+        $tmp .= $this->ndword($this->m_gfh->m_nWidth);
1031
+        $tmp .= $this->ndword($this->m_gfh->m_nHeight);
1032
+        $tmp .= "\x08\x03\x00\x00\x00";
1033
+        $out .= $tmp;
1034
+        $out .= $this->ndword(crc32($tmp));
1035
+        ///////////////////////////////////////////////////////////////////////
1036
+        // PALETTE
1037
+        if ($nColors > 0) {
1038
+            $out .= $this->ndword($nColors * 3);
1039
+            $tmp  = 'PLTE';
1040
+            $tmp .= $pal;
1041
+            $out .= $tmp;
1042
+            $out .= $this->ndword(crc32($tmp));
1043
+        }
1044
+        ///////////////////////////////////////////////////////////////////////
1045
+        // TRANSPARENCY
1046
+        if (@$this->m_img->m_bTrans && ($nColors > 0)) {
1047
+            $out .= $this->ndword($nColors);
1048
+            $tmp  = 'tRNS';
1049
+            for ($i = 0; $i < $nColors; $i++) {
1050
+                $tmp .= ($i == $this->m_img->m_nTrans) ? "\x00" : "\xFF";
1051
+            }
1052
+            $out .= $tmp;
1053
+            $out .= $this->ndword(crc32($tmp));
1054
+        }
1055
+        ///////////////////////////////////////////////////////////////////////
1056
+        // DATA BITS
1057
+        $out .= $this->ndword(strlen($bmp));
1058
+        $tmp  = 'IDAT';
1059
+        $tmp .= $bmp;
1060
+        $out .= $tmp;
1061
+        $out .= $this->ndword(crc32($tmp));
1062
+        ///////////////////////////////////////////////////////////////////////
1063
+        // END OF FILE
1064
+        $out .= "\x00\x00\x00\x00IEND\xAE\x42\x60\x82";
1065
+
1066
+        return $out;
1067
+    }
1068
+
1069
+    ///////////////////////////////////////////////////////////////////////////
1070
+
1071
+    // Added by James Heinrich <[email protected]> - January 5, 2003
1072
+
1073
+    // Takes raw image data and plots it pixel-by-pixel on a new GD image and returns that
1074
+    // It's extremely slow, but the only solution when imagecreatefromstring() fails
1075
+    public function getGD_PixelPlotterVersion()
1076
+    {
1077
+        if (!$this->m_bLoaded) {
1078
+            return false;
1079
+        }
1080
+
1081
+        // PREPARE COLOR TABLE (RGBQUADs)
1082
+        if ($this->m_img->m_gih->m_bLocalClr) {
1083
+            $pal = $this->m_img->m_gih->m_colorTable->toString();
1084
+        } elseif ($this->m_gfh->m_bGlobalClr) {
1085
+            $pal = $this->m_gfh->m_colorTable->toString();
1086
+        } else {
1087
+            die('No color table available in getGD_PixelPlotterVersion()');
1088
+        }
1089
+
1090
+        $PlottingIMG = imagecreate($this->m_gfh->m_nWidth, $this->m_gfh->m_nHeight);
1091
+        $NumColorsInPal = floor(strlen($pal) / 3);
1092
+        $ThisImageColor = array();
1093
+        for ($i = 0; $i < $NumColorsInPal; $i++) {
1094
+            $ThisImageColor[$i] = imagecolorallocate(
1095
+                                    $PlottingIMG,
1096
+                                    ord($pal{(($i * 3) + 0)}),
1097
+                                    ord($pal{(($i * 3) + 1)}),
1098
+                                    ord($pal{(($i * 3) + 2)}));
1099
+        }
1100
+
1101
+        // PREPARE BITMAP BITS
1102
+        $data = $this->m_img->m_data;
1103
+        $nPxl = ($this->m_gfh->m_nHeight - 1) * $this->m_gfh->m_nWidth;
1104
+        for ($y = 0; $y < $this->m_gfh->m_nHeight; $y++) {
1105
+            if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
1106
+                set_time_limit(30);
1107
+            }
1108
+            for ($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) {
1109
+                if (
1110
+                    ($x >= $this->m_img->m_gih->m_nLeft) &&
1111
+                    ($y >= $this->m_img->m_gih->m_nTop) &&
1112
+                    ($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1113
+                    ($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1114
+                    // PART OF IMAGE
1115
+                    if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
1116
+                        imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[$this->m_gfh->m_nBgColor]);
1117
+                    } else {
1118
+                        imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[ord($data{$nPxl})]);
1119
+                    }
1120
+                } else {
1121
+                    // BACKGROUND
1122
+                    imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[$this->m_gfh->m_nBgColor]);
1123
+                }
1124
+            }
1125
+            $nPxl -= $this->m_gfh->m_nWidth << 1;
1126
+
1127
+        }
1128
+
1129
+        return $PlottingIMG;
1130
+    }
1131
+
1132
+    ///////////////////////////////////////////////////////////////////////////
1133
+
1134
+    public function dword($val)
1135
+    {
1136
+        $val = (int) $val;
1137
+        return chr($val & 0xFF).chr(($val & 0xFF00) >> 8).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF000000) >> 24);
1138
+    }
1139
+
1140
+    ///////////////////////////////////////////////////////////////////////////
1141
+
1142
+    public function ndword($val)
1143
+    {
1144
+        $val = (int) $val;
1145
+        return chr(($val & 0xFF000000) >> 24).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF00) >> 8).chr($val & 0xFF);
1146
+    }
1147
+
1148
+    ///////////////////////////////////////////////////////////////////////////
1149
+
1150
+    public function width()
1151
+    {
1152
+        return $this->m_gfh->m_nWidth;
1153
+    }
1154
+
1155
+    ///////////////////////////////////////////////////////////////////////////
1156
+
1157
+    public function height()
1158
+    {
1159
+        return $this->m_gfh->m_nHeight;
1160
+    }
1161
+
1162
+    ///////////////////////////////////////////////////////////////////////////
1163
+
1164
+    public function comment()
1165
+    {
1166
+        return $this->m_img->m_lpComm;
1167
+    }
1168
+
1169
+    ///////////////////////////////////////////////////////////////////////////
1170
+
1171
+    public function loaded()
1172
+    {
1173
+        return $this->m_bLoaded;
1174
+    }
1175 1175
 }
Please login to merge, or discard this patch.
Switch Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -659,36 +659,36 @@  discard block
 block discarded – undo
659 659
 			$datLen++;
660 660
 
661 661
 			switch($b) {
662
-			case 0x21: // Extension
663
-				if (!$this->skipExt($data, $len = 0)) {
664
-					return false;
665
-				}
666
-				$datLen += $len;
667
-				break;
668
-
669
-			case 0x2C: // Image
670
-				// LOAD HEADER & COLOR TABLE
671
-				if (!$this->m_gih->load($data, $len = 0)) {
672
-					return false;
673
-				}
674
-				$data = substr($data, $len);
675
-				$datLen += $len;
676
-
677
-				// ALLOC BUFFER
678
-				if (!($this->m_data = $this->m_lzw->deCompress($data, $len = 0))) {
679
-					return false;
680
-				}
681
-				$data = substr($data, $len);
682
-				$datLen += $len;
683
-
684
-				if ($this->m_gih->m_bInterlace) {
685
-					$this->deInterlace();
686
-				}
687
-				return true;
688
-
689
-			case 0x3B: // EOF
690
-			default:
691
-				return false;
662
+			    case 0x21: // Extension
663
+				    if (!$this->skipExt($data, $len = 0)) {
664
+					    return false;
665
+				    }
666
+				    $datLen += $len;
667
+				    break;
668
+
669
+			    case 0x2C: // Image
670
+				    // LOAD HEADER & COLOR TABLE
671
+				    if (!$this->m_gih->load($data, $len = 0)) {
672
+					    return false;
673
+				    }
674
+				    $data = substr($data, $len);
675
+				    $datLen += $len;
676
+
677
+				    // ALLOC BUFFER
678
+				    if (!($this->m_data = $this->m_lzw->deCompress($data, $len = 0))) {
679
+					    return false;
680
+				    }
681
+				    $data = substr($data, $len);
682
+				    $datLen += $len;
683
+
684
+				    if ($this->m_gih->m_bInterlace) {
685
+					    $this->deInterlace();
686
+				    }
687
+				    return true;
688
+
689
+			    case 0x3B: // EOF
690
+			    default:
691
+				    return false;
692 692
 			}
693 693
 		}
694 694
 		return false;
@@ -705,24 +705,24 @@  discard block
 block discarded – undo
705 705
 		$extLen++;
706 706
 
707 707
 		switch($b) {
708
-		case 0xF9: // Graphic Control
709
-			$b = ord($data{1});
710
-			$this->m_disp   = ($b & 0x1C) >> 2;
711
-			$this->m_bUser  = ($b & 0x02) ? true : false;
712
-			$this->m_bTrans = ($b & 0x01) ? true : false;
713
-			$this->m_nDelay = $this->w2i(substr($data, 2, 2));
714
-			$this->m_nTrans = ord($data{4});
715
-			break;
716
-
717
-		case 0xFE: // Comment
718
-			$this->m_lpComm = substr($data, 1, ord($data{0}));
719
-			break;
720
-
721
-		case 0x01: // Plain text
722
-			break;
723
-
724
-		case 0xFF: // Application
725
-			break;
708
+		    case 0xF9: // Graphic Control
709
+			    $b = ord($data{1});
710
+			    $this->m_disp   = ($b & 0x1C) >> 2;
711
+			    $this->m_bUser  = ($b & 0x02) ? true : false;
712
+			    $this->m_bTrans = ($b & 0x01) ? true : false;
713
+			    $this->m_nDelay = $this->w2i(substr($data, 2, 2));
714
+			    $this->m_nTrans = ord($data{4});
715
+			    break;
716
+
717
+		    case 0xFE: // Comment
718
+			    $this->m_lpComm = substr($data, 1, ord($data{0}));
719
+			    break;
720
+
721
+		    case 0x01: // Plain text
722
+			    break;
723
+
724
+		    case 0xFF: // Application
725
+			    break;
726 726
 		}
727 727
 
728 728
 		// SKIP DEFAULT AS DEFS MAY CHANGE
@@ -756,25 +756,25 @@  discard block
 block discarded – undo
756 756
 
757 757
 		for ($i = 0; $i < 4; $i++) {
758 758
 			switch($i) {
759
-			case 0:
760
-				$s = 8;
761
-				$y = 0;
762
-				break;
763
-
764
-			case 1:
765
-				$s = 8;
766
-				$y = 4;
767
-				break;
768
-
769
-			case 2:
770
-				$s = 4;
771
-				$y = 2;
772
-				break;
773
-
774
-			case 3:
775
-				$s = 2;
776
-				$y = 1;
777
-				break;
759
+			    case 0:
760
+				    $s = 8;
761
+				    $y = 0;
762
+				    break;
763
+
764
+			    case 1:
765
+				    $s = 8;
766
+				    $y = 4;
767
+				    break;
768
+
769
+			    case 2:
770
+				    $s = 4;
771
+				    $y = 2;
772
+				    break;
773
+
774
+			    case 3:
775
+				    $s = 2;
776
+				    $y = 1;
777
+				    break;
778 778
 			}
779 779
 
780 780
 			for (; $y < $this->m_gih->m_nHeight; $y += $s) {
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -178,8 +178,8 @@  discard block
 block discarded – undo
178 178
 		unSet($this->Stack);
179 179
 		unSet($this->Buf);
180 180
 
181
-		$this->Next  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
182
-		$this->Vals  = range(0, (1 << $this->MAX_LZW_BITS)       - 1);
181
+		$this->Next  = range(0, (1 << $this->MAX_LZW_BITS) - 1);
182
+		$this->Vals  = range(0, (1 << $this->MAX_LZW_BITS) - 1);
183 183
 		$this->Stack = range(0, (1 << ($this->MAX_LZW_BITS + 1)) - 1);
184 184
 		$this->Buf   = range(0, 279);
185 185
 	}
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 
367 367
 		$iRet = 0;
368 368
 		for ($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) {
369
-			$iRet |= (($this->Buf[ (int) ($i / 8) ] & (1 << ($i % 8))) != 0) << $j;
369
+			$iRet |= (($this->Buf[(int)($i / 8)] & (1 << ($i % 8))) != 0) << $j;
370 370
 		}
371 371
 
372 372
 		$this->CurBit += $this->CodeSize;
@@ -418,9 +418,9 @@  discard block
 block discarded – undo
418 418
 
419 419
 		for ($i = 0; $i < $this->m_nColors; $i++) {
420 420
 			$ret .=
421
-				chr(($this->m_arColors[$i] & 0x000000FF))       . // R
422
-				chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
423
-				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16);  // B
421
+				chr(($this->m_arColors[$i] & 0x000000FF)).// R
422
+				chr(($this->m_arColors[$i] & 0x0000FF00) >> 8).// G
423
+				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16); // B
424 424
 		}
425 425
 
426 426
 		return $ret;
@@ -434,9 +434,9 @@  discard block
 block discarded – undo
434 434
 
435 435
 		for ($i = 0; $i < $this->m_nColors; $i++) {
436 436
 			$ret .=
437
-				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16) . // B
438
-				chr(($this->m_arColors[$i] & 0x0000FF00) >>  8) . // G
439
-				chr(($this->m_arColors[$i] & 0x000000FF))       . // R
437
+				chr(($this->m_arColors[$i] & 0x00FF0000) >> 16).// B
438
+				chr(($this->m_arColors[$i] & 0x0000FF00) >> 8).// G
439
+				chr(($this->m_arColors[$i] & 0x000000FF)).// R
440 440
 				"\x00";
441 441
 		}
442 442
 
@@ -447,16 +447,16 @@  discard block
 block discarded – undo
447 447
 
448 448
 	public function colorIndex($rgb)
449 449
 	{
450
-		$rgb = (int) $rgb & 0xFFFFFF;
450
+		$rgb = (int)$rgb & 0xFFFFFF;
451 451
 		$r1  = ($rgb & 0x0000FF);
452
-		$g1  = ($rgb & 0x00FF00) >>  8;
452
+		$g1  = ($rgb & 0x00FF00) >> 8;
453 453
 		$b1  = ($rgb & 0xFF0000) >> 16;
454 454
 		$idx = -1;
455 455
 		$dif = 0;
456 456
 
457 457
 		for ($i = 0; $i < $this->m_nColors; $i++) {
458 458
 			$r2 = ($this->m_arColors[$i] & 0x000000FF);
459
-			$g2 = ($this->m_arColors[$i] & 0x0000FF00) >>  8;
459
+			$g2 = ($this->m_arColors[$i] & 0x0000FF00) >> 8;
460 460
 			$b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16;
461 461
 			$d  = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1);
462 462
 
@@ -519,13 +519,13 @@  discard block
 block discarded – undo
519 519
 			return false;
520 520
 		}
521 521
 
522
-		$b = ord($lpData[ 10 ]);
522
+		$b = ord($lpData[10]);
523 523
 		$this->m_bGlobalClr  = ($b & 0x80) ? true : false;
524 524
 		$this->m_nColorRes   = ($b & 0x70) >> 4;
525 525
 		$this->m_bSorted     = ($b & 0x08) ? true : false;
526 526
 		$this->m_nTableSize  = 2 << ($b & 0x07);
527
-		$this->m_nBgColor    = ord($lpData[ 11 ]);
528
-		$this->m_nPixelRatio = ord($lpData[ 12 ]);
527
+		$this->m_nBgColor    = ord($lpData[11]);
528
+		$this->m_nPixelRatio = ord($lpData[12]);
529 529
 		$hdrLen = 13;
530 530
 
531 531
 		if ($this->m_bGlobalClr) {
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 
544 544
 	public function w2i($str)
545 545
 	{
546
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
546
+		return ord($str[0]) + (ord($str[1]) << 8);
547 547
 	}
548 548
 }
549 549
 
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 
615 615
 	public function w2i($str)
616 616
 	{
617
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
617
+		return ord($str[0]) + (ord($str[1]) << 8);
618 618
 	}
619 619
 }
620 620
 
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 			$data = substr($data, 1);
659 659
 			$datLen++;
660 660
 
661
-			switch($b) {
661
+			switch ($b) {
662 662
 			case 0x21: // Extension
663 663
 				if (!$this->skipExt($data, $len = 0)) {
664 664
 					return false;
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
 		$data = substr($data, 1);
705 705
 		$extLen++;
706 706
 
707
-		switch($b) {
707
+		switch ($b) {
708 708
 		case 0xF9: // Graphic Control
709 709
 			$b = ord($data{1});
710 710
 			$this->m_disp   = ($b & 0x1C) >> 2;
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
 
744 744
 	public function w2i($str)
745 745
 	{
746
-		return ord($str[ 0 ]) + (ord($str[ 1 ]) << 8);
746
+		return ord($str[0]) + (ord($str[1]) << 8);
747 747
 	}
748 748
 
749 749
 	///////////////////////////////////////////////////////////////////////////
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 		$y = 0;
756 756
 
757 757
 		for ($i = 0; $i < 4; $i++) {
758
-			switch($i) {
758
+			switch ($i) {
759 759
 			case 0:
760 760
 				$s = 8;
761 761
 				$y = 0;
@@ -782,8 +782,8 @@  discard block
 block discarded – undo
782 782
 				$this->m_data = substr($this->m_data, $this->m_gih->m_nWidth);
783 783
 
784 784
 				$data =
785
-					substr($data, 0, $y * $this->m_gih->m_nWidth) .
786
-					$lne .
785
+					substr($data, 0, $y * $this->m_gih->m_nWidth).
786
+					$lne.
787 787
 					substr($data, ($y + 1) * $this->m_gih->m_nWidth);
788 788
 			}
789 789
 		}
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
890 890
 			}
891 891
 		} else {
892
-			$nColors =  0;
892
+			$nColors = 0;
893 893
 			$rgbq    = '';
894 894
 			$bgColor = -1;
895 895
 		}
@@ -904,8 +904,8 @@  discard block
 block discarded – undo
904 904
 				if (
905 905
 					($x >= $this->m_img->m_gih->m_nLeft) &&
906 906
 					($y >= $this->m_img->m_gih->m_nTop) &&
907
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
908
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
907
+					($x < ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
908
+					($y < ($this->m_img->m_gih->m_nTop + $this->m_img->m_gih->m_nHeight))) {
909 909
 					// PART OF IMAGE
910 910
 					if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
911 911
 						// TRANSPARENT -> BACKGROUND
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
 				$bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor);
990 990
 			}
991 991
 		} else {
992
-			$nColors =  0;
992
+			$nColors = 0;
993 993
 			$pal     = '';
994 994
 			$bgColor = -1;
995 995
 		}
@@ -1004,8 +1004,8 @@  discard block
 block discarded – undo
1004 1004
 				if (
1005 1005
 					($x >= $this->m_img->m_gih->m_nLeft) &&
1006 1006
 					($y >= $this->m_img->m_gih->m_nTop) &&
1007
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1008
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1007
+					($x < ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1008
+					($y < ($this->m_img->m_gih->m_nTop + $this->m_img->m_gih->m_nHeight))) {
1009 1009
 					// PART OF IMAGE
1010 1010
 					$bmp .= $data{$nPxl};
1011 1011
 				} else {
@@ -1109,8 +1109,8 @@  discard block
 block discarded – undo
1109 1109
 				if (
1110 1110
 					($x >= $this->m_img->m_gih->m_nLeft) &&
1111 1111
 					($y >= $this->m_img->m_gih->m_nTop) &&
1112
-					($x <  ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1113
-					($y <  ($this->m_img->m_gih->m_nTop  + $this->m_img->m_gih->m_nHeight))) {
1112
+					($x < ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) &&
1113
+					($y < ($this->m_img->m_gih->m_nTop + $this->m_img->m_gih->m_nHeight))) {
1114 1114
 					// PART OF IMAGE
1115 1115
 					if (@$this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) {
1116 1116
 						imagesetpixel($PlottingIMG, $x, $this->m_gfh->m_nHeight - $y - 1, $ThisImageColor[$this->m_gfh->m_nBgColor]);
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 
1134 1134
 	public function dword($val)
1135 1135
 	{
1136
-		$val = (int) $val;
1136
+		$val = (int)$val;
1137 1137
 		return chr($val & 0xFF).chr(($val & 0xFF00) >> 8).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF000000) >> 24);
1138 1138
 	}
1139 1139
 
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
 
1142 1142
 	public function ndword($val)
1143 1143
 	{
1144
-		$val = (int) $val;
1144
+		$val = (int)$val;
1145 1145
 		return chr(($val & 0xFF000000) >> 24).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF00) >> 8).chr($val & 0xFF);
1146 1146
 	}
1147 1147
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -292,8 +292,10 @@
 block discarded – undo
292 292
 				$this->Stack[$this->sp] = $this->Vals[$Code];
293 293
 				$this->sp++;
294 294
 
295
-				if ($Code == $this->Next[$Code]) // Circular table entry, big GIF Error!
295
+				if ($Code == $this->Next[$Code]) {
296
+				    // Circular table entry, big GIF Error!
296 297
 					return -1;
298
+				}
297 299
 
298 300
 				$Code = $this->Next[$Code];
299 301
 			}
Please login to merge, or discard this patch.
htdocs/modules/system/class/thumbs/phpThumb.php 2 patches
Indentation   +457 added lines, -457 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@  discard block
 block discarded – undo
14 14
 ini_set('display_errors', '1');
15 15
 ini_set('magic_quotes_runtime', '0');
16 16
 if (ini_get('magic_quotes_runtime')) {
17
-	die('"magic_quotes_runtime" is set in php.ini, cannot run phpThumb with this enabled');
17
+    die('"magic_quotes_runtime" is set in php.ini, cannot run phpThumb with this enabled');
18 18
 }
19 19
 // Set a default timezone if web server has not done already in php.ini
20 20
 if (!ini_get('date.timezone') && function_exists('date_default_timezone_set')) { // PHP >= 5.1.0
@@ -24,84 +24,84 @@  discard block
 block discarded – undo
24 24
 
25 25
 // this script relies on the superglobal arrays, fake it here for old PHP versions
26 26
 if (PHP_VERSION < '4.1.0') {
27
-	$_SERVER = $HTTP_SERVER_VARS;
28
-	$_GET    = $HTTP_GET_VARS;
27
+    $_SERVER = $HTTP_SERVER_VARS;
28
+    $_GET    = $HTTP_GET_VARS;
29 29
 }
30 30
 
31 31
 function SendSaveAsFileHeaderIfNeeded() {
32
-	if (headers_sent()) {
33
-		return false;
34
-	}
35
-	global $phpThumb;
36
-	$downloadfilename = phpthumb_functions::SanitizeFilename(!empty($_GET['sia']) ? $_GET['sia'] : (!empty($_GET['down']) ? $_GET['down'] : 'phpThumb_generated_thumbnail.'.(!empty($_GET['f']) ? $_GET['f'] : 'jpg')));
37
-	if (!empty($downloadfilename)) {
38
-		$phpThumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"', __FILE__, __LINE__);
39
-		header('Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
40
-	}
41
-	return true;
32
+    if (headers_sent()) {
33
+        return false;
34
+    }
35
+    global $phpThumb;
36
+    $downloadfilename = phpthumb_functions::SanitizeFilename(!empty($_GET['sia']) ? $_GET['sia'] : (!empty($_GET['down']) ? $_GET['down'] : 'phpThumb_generated_thumbnail.'.(!empty($_GET['f']) ? $_GET['f'] : 'jpg')));
37
+    if (!empty($downloadfilename)) {
38
+        $phpThumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"', __FILE__, __LINE__);
39
+        header('Content-Disposition: '.(!empty($_GET['down']) ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
40
+    }
41
+    return true;
42 42
 }
43 43
 
44 44
 function RedirectToCachedFile() {
45
-	global $phpThumb;
46
-
47
-	$nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $phpThumb->cache_filename);
48
-	$nice_docroot   = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($phpThumb->config_document_root, '/\\'));
49
-
50
-	$parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
51
-
52
-	$nModified  = filemtime($phpThumb->cache_filename);
53
-
54
-	if ($phpThumb->config_nooffsitelink_enabled && !empty($_SERVER['HTTP_REFERER']) && !in_array(@$parsed_url['host'], $phpThumb->config_nooffsitelink_valid_domains)) {
55
-
56
-		$phpThumb->DebugMessage('Would have used cached (image/'.$phpThumb->thumbnailFormat.') file "'.$phpThumb->cache_filename.'" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $phpThumb->config_nooffsitelink_valid_domains ('.implode(';', $phpThumb->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
57
-
58
-	} elseif ($phpThumb->phpThumbDebug) {
59
-
60
-		$phpThumb->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);
61
-		$phpThumb->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);
62
-		$phpThumb->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);
63
-		if ($getimagesize = @getimagesize($phpThumb->cache_filename)) {
64
-			$phpThumb->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
65
-		}
66
-		if (preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
67
-			$phpThumb->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);
68
-		} else {
69
-			$phpThumb->DebugMessage('* Would have sent data: readfile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
70
-		}
71
-
72
-	} else {
73
-
74
-		if (headers_sent()) {
75
-			$phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
76
-			exit;
77
-		}
78
-		SendSaveAsFileHeaderIfNeeded();
79
-
80
-		header('Pragma: private');
81
-		header('Cache-Control: max-age='.$phpThumb->getParameter('config_cache_maxage'));
82
-		header('Expires: '.date(DATE_RFC1123,  time() + $phpThumb->getParameter('config_cache_maxage')));
83
-		if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && !empty($_SERVER['SERVER_PROTOCOL'])) {
84
-			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
85
-			header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
86
-			exit;
87
-		}
88
-		header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
89
-		header('ETag: "'.md5_file($phpThumb->cache_filename).'"');
90
-		if ($getimagesize = @getimagesize($phpThumb->cache_filename)) {
91
-			header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
92
-		} elseif (preg_match('#\\.ico$#i', $phpThumb->cache_filename)) {
93
-			header('Content-Type: image/x-icon');
94
-		}
95
-		header('Content-Length: '.filesize($phpThumb->cache_filename));
96
-		if (empty($phpThumb->config_cache_force_passthru) && preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
97
-			header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));
98
-		} else {
99
-			@readfile($phpThumb->cache_filename);
100
-		}
101
-		exit;
102
-
103
-	}
104
-	return true;
45
+    global $phpThumb;
46
+
47
+    $nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $phpThumb->cache_filename);
48
+    $nice_docroot   = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($phpThumb->config_document_root, '/\\'));
49
+
50
+    $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
51
+
52
+    $nModified  = filemtime($phpThumb->cache_filename);
53
+
54
+    if ($phpThumb->config_nooffsitelink_enabled && !empty($_SERVER['HTTP_REFERER']) && !in_array(@$parsed_url['host'], $phpThumb->config_nooffsitelink_valid_domains)) {
55
+
56
+        $phpThumb->DebugMessage('Would have used cached (image/'.$phpThumb->thumbnailFormat.') file "'.$phpThumb->cache_filename.'" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $phpThumb->config_nooffsitelink_valid_domains ('.implode(';', $phpThumb->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
57
+
58
+    } elseif ($phpThumb->phpThumbDebug) {
59
+
60
+        $phpThumb->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);
61
+        $phpThumb->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);
62
+        $phpThumb->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);
63
+        if ($getimagesize = @getimagesize($phpThumb->cache_filename)) {
64
+            $phpThumb->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
65
+        }
66
+        if (preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
67
+            $phpThumb->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);
68
+        } else {
69
+            $phpThumb->DebugMessage('* Would have sent data: readfile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
70
+        }
71
+
72
+    } else {
73
+
74
+        if (headers_sent()) {
75
+            $phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
76
+            exit;
77
+        }
78
+        SendSaveAsFileHeaderIfNeeded();
79
+
80
+        header('Pragma: private');
81
+        header('Cache-Control: max-age='.$phpThumb->getParameter('config_cache_maxage'));
82
+        header('Expires: '.date(DATE_RFC1123,  time() + $phpThumb->getParameter('config_cache_maxage')));
83
+        if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && !empty($_SERVER['SERVER_PROTOCOL'])) {
84
+            header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
85
+            header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
86
+            exit;
87
+        }
88
+        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
89
+        header('ETag: "'.md5_file($phpThumb->cache_filename).'"');
90
+        if ($getimagesize = @getimagesize($phpThumb->cache_filename)) {
91
+            header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
92
+        } elseif (preg_match('#\\.ico$#i', $phpThumb->cache_filename)) {
93
+            header('Content-Type: image/x-icon');
94
+        }
95
+        header('Content-Length: '.filesize($phpThumb->cache_filename));
96
+        if (empty($phpThumb->config_cache_force_passthru) && preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
97
+            header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));
98
+        } else {
99
+            @readfile($phpThumb->cache_filename);
100
+        }
101
+        exit;
102
+
103
+    }
104
+    return true;
105 105
 }
106 106
 
107 107
 
@@ -109,8 +109,8 @@  discard block
 block discarded – undo
109 109
 // instantiate a new phpThumb() object
110 110
 ob_start();
111 111
 if (!include_once( __DIR__ .'/phpthumb.class.php')) {
112
-	ob_end_flush();
113
-	die('failed to include_once("'.realpath( __DIR__ .'/phpthumb.class.php').'")');
112
+    ob_end_flush();
113
+    die('failed to include_once("'.realpath( __DIR__ .'/phpthumb.class.php').'")');
114 114
 }
115 115
 ob_end_clean();
116 116
 $phpThumb = new phpThumb();
@@ -118,256 +118,256 @@  discard block
 block discarded – undo
118 118
 $phpThumb->setParameter('config_error_die_on_error', true);
119 119
 
120 120
 if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
121
-	set_time_limit(60);  // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
121
+    set_time_limit(60);  // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
122 122
 }
123 123
 
124 124
 // phpThumbDebug[0] used to be here, but may reveal too much
125 125
 // info when high_security_mode should be enabled (not set yet)
126 126
 
127 127
 if (file_exists( __DIR__ .'/phpThumb.config.php')) {
128
-	ob_start();
129
-	if (include_once( __DIR__ .'/phpThumb.config.php')) {
130
-		// great
131
-	} else {
132
-		ob_end_flush();
133
-		$phpThumb->config_disable_debug = false; // otherwise error message won't print
134
-		$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
135
-	}
136
-	ob_end_clean();
128
+    ob_start();
129
+    if (include_once( __DIR__ .'/phpThumb.config.php')) {
130
+        // great
131
+    } else {
132
+        ob_end_flush();
133
+        $phpThumb->config_disable_debug = false; // otherwise error message won't print
134
+        $phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
135
+    }
136
+    ob_end_clean();
137 137
 } elseif (file_exists( __DIR__ .'/phpThumb.config.php.default')) {
138
-	$phpThumb->config_disable_debug = false; // otherwise error message won't print
139
-	$phpThumb->ErrorImage('Please rename "phpThumb.config.php.default" to "phpThumb.config.php"');
138
+    $phpThumb->config_disable_debug = false; // otherwise error message won't print
139
+    $phpThumb->ErrorImage('Please rename "phpThumb.config.php.default" to "phpThumb.config.php"');
140 140
 } else {
141
-	$phpThumb->config_disable_debug = false; // otherwise error message won't print
142
-	$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
141
+    $phpThumb->config_disable_debug = false; // otherwise error message won't print
142
+    $phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
143 143
 }
144 144
 
145 145
 if (!empty($PHPTHUMB_CONFIG)) {
146
-	foreach ($PHPTHUMB_CONFIG as $key => $value) {
147
-		$keyname = 'config_'.$key;
148
-		$phpThumb->setParameter($keyname, $value);
149
-		if (!preg_match('#(password|mysql)#i', $key)) {
150
-			$phpThumb->DebugMessage('setParameter('.$keyname.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
151
-		}
152
-	}
153
-	if (!$phpThumb->config_disable_debug) {
154
-		// if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
155
-		$_GET['phpThumbDebug'] = (!empty($_GET['phpThumbDebug']) ? max(1, (int) $_GET[ 'phpThumbDebug']) : 9);
156
-		$phpThumb->setParameter('phpThumbDebug', $_GET['phpThumbDebug']);
157
-	}
146
+    foreach ($PHPTHUMB_CONFIG as $key => $value) {
147
+        $keyname = 'config_'.$key;
148
+        $phpThumb->setParameter($keyname, $value);
149
+        if (!preg_match('#(password|mysql)#i', $key)) {
150
+            $phpThumb->DebugMessage('setParameter('.$keyname.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
151
+        }
152
+    }
153
+    if (!$phpThumb->config_disable_debug) {
154
+        // if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
155
+        $_GET['phpThumbDebug'] = (!empty($_GET['phpThumbDebug']) ? max(1, (int) $_GET[ 'phpThumbDebug']) : 9);
156
+        $phpThumb->setParameter('phpThumbDebug', $_GET['phpThumbDebug']);
157
+    }
158 158
 } else {
159
-	$phpThumb->DebugMessage('$PHPTHUMB_CONFIG is empty', __FILE__, __LINE__);
159
+    $phpThumb->DebugMessage('$PHPTHUMB_CONFIG is empty', __FILE__, __LINE__);
160 160
 }
161 161
 
162 162
 if (empty($phpThumb->config_disable_pathinfo_parsing) && (empty($_GET) || isset($_GET['phpThumbDebug'])) && !empty($_SERVER['PATH_INFO'])) {
163
-	$_SERVER['PHP_SELF'] = str_replace($_SERVER['PATH_INFO'], '', @$_SERVER['PHP_SELF']);
164
-
165
-	$args = explode(';', substr($_SERVER['PATH_INFO'], 1));
166
-	$phpThumb->DebugMessage('PATH_INFO.$args set to ('.implode(')(', $args).')', __FILE__, __LINE__);
167
-	if (!empty($args)) {
168
-		$_GET['src'] = @$args[count($args) - 1];
169
-		$phpThumb->DebugMessage('PATH_INFO."src" = "'.$_GET['src'].'"', __FILE__, __LINE__);
170
-		if (preg_match('#^new\=([a-z0-9]+)#i', $_GET['src'], $matches)) {
171
-			unset($_GET['src']);
172
-			$_GET['new'] = $matches[1];
173
-		}
174
-	}
175
-	if (preg_match('#^([0-9]*)x?([0-9]*)$#i', @$args[count($args) - 2], $matches)) {
176
-		$_GET['w'] = $matches[1];
177
-		$_GET['h'] = $matches[2];
178
-		$phpThumb->DebugMessage('PATH_INFO."w"x"h" set to "'.$_GET['w'].'"x"'.$_GET['h'].'"', __FILE__, __LINE__);
179
-	}
180
-	for ($i = 0; $i < count($args) - 2; $i++) {
181
-		@list($key, $value) = explode('=', @$args[$i]);
182
-		if (substr($key, -2) == '[]') {
183
-			$array_key_name = substr($key, 0, -2);
184
-			$_GET[$array_key_name][] = $value;
185
-			$phpThumb->DebugMessage('PATH_INFO."'.$array_key_name.'[]" = "'.$value.'"', __FILE__, __LINE__);
186
-		} else {
187
-			$_GET[$key] = $value;
188
-			$phpThumb->DebugMessage('PATH_INFO."'.$key.'" = "'.$value.'"', __FILE__, __LINE__);
189
-		}
190
-	}
163
+    $_SERVER['PHP_SELF'] = str_replace($_SERVER['PATH_INFO'], '', @$_SERVER['PHP_SELF']);
164
+
165
+    $args = explode(';', substr($_SERVER['PATH_INFO'], 1));
166
+    $phpThumb->DebugMessage('PATH_INFO.$args set to ('.implode(')(', $args).')', __FILE__, __LINE__);
167
+    if (!empty($args)) {
168
+        $_GET['src'] = @$args[count($args) - 1];
169
+        $phpThumb->DebugMessage('PATH_INFO."src" = "'.$_GET['src'].'"', __FILE__, __LINE__);
170
+        if (preg_match('#^new\=([a-z0-9]+)#i', $_GET['src'], $matches)) {
171
+            unset($_GET['src']);
172
+            $_GET['new'] = $matches[1];
173
+        }
174
+    }
175
+    if (preg_match('#^([0-9]*)x?([0-9]*)$#i', @$args[count($args) - 2], $matches)) {
176
+        $_GET['w'] = $matches[1];
177
+        $_GET['h'] = $matches[2];
178
+        $phpThumb->DebugMessage('PATH_INFO."w"x"h" set to "'.$_GET['w'].'"x"'.$_GET['h'].'"', __FILE__, __LINE__);
179
+    }
180
+    for ($i = 0; $i < count($args) - 2; $i++) {
181
+        @list($key, $value) = explode('=', @$args[$i]);
182
+        if (substr($key, -2) == '[]') {
183
+            $array_key_name = substr($key, 0, -2);
184
+            $_GET[$array_key_name][] = $value;
185
+            $phpThumb->DebugMessage('PATH_INFO."'.$array_key_name.'[]" = "'.$value.'"', __FILE__, __LINE__);
186
+        } else {
187
+            $_GET[$key] = $value;
188
+            $phpThumb->DebugMessage('PATH_INFO."'.$key.'" = "'.$value.'"', __FILE__, __LINE__);
189
+        }
190
+    }
191 191
 }
192 192
 
193 193
 if (!empty($phpThumb->config_high_security_enabled)) {
194
-	if (empty($_GET['hash'])) {
195
-		$phpThumb->config_disable_debug = false; // otherwise error message won't print
196
-		$phpThumb->ErrorImage('ERROR: missing hash');
197
-	} elseif (phpthumb_functions::PasswordStrength($phpThumb->config_high_security_password) < 20) {
198
-		$phpThumb->config_disable_debug = false; // otherwise error message won't print
199
-		$phpThumb->ErrorImage('ERROR: $PHPTHUMB_CONFIG[high_security_password] is not complex enough');
200
-	} elseif ($_GET['hash'] != md5(str_replace($phpThumb->config_high_security_url_separator.'hash='.$_GET['hash'], '', $_SERVER['QUERY_STRING']).$phpThumb->config_high_security_password)) {
201
-		header('HTTP/1.0 403 Forbidden');
202
-		sleep(10); // deliberate delay to discourage password-guessing
203
-		$phpThumb->ErrorImage('ERROR: invalid hash');
204
-	}
194
+    if (empty($_GET['hash'])) {
195
+        $phpThumb->config_disable_debug = false; // otherwise error message won't print
196
+        $phpThumb->ErrorImage('ERROR: missing hash');
197
+    } elseif (phpthumb_functions::PasswordStrength($phpThumb->config_high_security_password) < 20) {
198
+        $phpThumb->config_disable_debug = false; // otherwise error message won't print
199
+        $phpThumb->ErrorImage('ERROR: $PHPTHUMB_CONFIG[high_security_password] is not complex enough');
200
+    } elseif ($_GET['hash'] != md5(str_replace($phpThumb->config_high_security_url_separator.'hash='.$_GET['hash'], '', $_SERVER['QUERY_STRING']).$phpThumb->config_high_security_password)) {
201
+        header('HTTP/1.0 403 Forbidden');
202
+        sleep(10); // deliberate delay to discourage password-guessing
203
+        $phpThumb->ErrorImage('ERROR: invalid hash');
204
+    }
205 205
 }
206 206
 
207 207
 ////////////////////////////////////////////////////////////////
208 208
 // Debug output, to try and help me diagnose problems
209 209
 $phpThumb->DebugTimingMessage('phpThumbDebug[0]', __FILE__, __LINE__);
210 210
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '0')) {
211
-	$phpThumb->phpThumbDebug();
211
+    $phpThumb->phpThumbDebug();
212 212
 }
213 213
 ////////////////////////////////////////////////////////////////
214 214
 
215 215
 // returned the fixed string if the evil "magic_quotes_gpc" setting is on
216 216
 if (get_magic_quotes_gpc()) {
217
-	// deprecated: 'err', 'file', 'goto',
218
-	$RequestVarsToStripSlashes = array('src', 'wmf', 'down');
219
-	foreach ($RequestVarsToStripSlashes as $key) {
220
-		if (isset($_GET[$key])) {
221
-			if (is_string($_GET[$key])) {
222
-				$_GET[$key] = stripslashes($_GET[$key]);
223
-			} else {
224
-				unset($_GET[$key]);
225
-			}
226
-		}
227
-	}
217
+    // deprecated: 'err', 'file', 'goto',
218
+    $RequestVarsToStripSlashes = array('src', 'wmf', 'down');
219
+    foreach ($RequestVarsToStripSlashes as $key) {
220
+        if (isset($_GET[$key])) {
221
+            if (is_string($_GET[$key])) {
222
+                $_GET[$key] = stripslashes($_GET[$key]);
223
+            } else {
224
+                unset($_GET[$key]);
225
+            }
226
+        }
227
+    }
228 228
 }
229 229
 
230 230
 if (empty($_SERVER['PATH_INFO']) && empty($_SERVER['QUERY_STRING'])) {
231
-	$phpThumb->config_disable_debug = false; // otherwise error message won't print
232
-	$phpThumb->ErrorImage('ERROR: no parameters specified');
231
+    $phpThumb->config_disable_debug = false; // otherwise error message won't print
232
+    $phpThumb->ErrorImage('ERROR: no parameters specified');
233 233
 }
234 234
 
235 235
 if (!empty($_GET['src']) && isset($_GET['md5s']) && empty($_GET['md5s'])) {
236
-	$md5s = '';
237
-	if (preg_match('#^([a-z0-9]+)://#i', $_GET['src'], $protocol_matches)) {
238
-		if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
239
-			if ($rawImageData = phpthumb_functions::SafeURLread($_GET['src'], $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
240
-				$md5s = md5($rawImageData);
241
-			}
242
-		} else {
243
-			$phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
244
-		}
245
-	} else {
246
-		$SourceFilename = $phpThumb->ResolveFilenameToAbsolute($_GET['src']);
247
-		if (is_readable($SourceFilename)) {
248
-			$md5s = phpthumb_functions::md5_file_safe($SourceFilename);
249
-		} else {
250
-			$phpThumb->ErrorImage('ERROR: "'.$SourceFilename.'" cannot be read');
251
-		}
252
-	}
253
-	if (!empty($_SERVER['HTTP_REFERER'])) {
254
-		$phpThumb->ErrorImage('&md5s='.$md5s);
255
-	} else {
256
-		die('&md5s='.$md5s);
257
-	}
236
+    $md5s = '';
237
+    if (preg_match('#^([a-z0-9]+)://#i', $_GET['src'], $protocol_matches)) {
238
+        if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
239
+            if ($rawImageData = phpthumb_functions::SafeURLread($_GET['src'], $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
240
+                $md5s = md5($rawImageData);
241
+            }
242
+        } else {
243
+            $phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
244
+        }
245
+    } else {
246
+        $SourceFilename = $phpThumb->ResolveFilenameToAbsolute($_GET['src']);
247
+        if (is_readable($SourceFilename)) {
248
+            $md5s = phpthumb_functions::md5_file_safe($SourceFilename);
249
+        } else {
250
+            $phpThumb->ErrorImage('ERROR: "'.$SourceFilename.'" cannot be read');
251
+        }
252
+    }
253
+    if (!empty($_SERVER['HTTP_REFERER'])) {
254
+        $phpThumb->ErrorImage('&md5s='.$md5s);
255
+    } else {
256
+        die('&md5s='.$md5s);
257
+    }
258 258
 }
259 259
 
260 260
 if (!empty($_GET['src']) && empty($phpThumb->config_allow_local_http_src) && preg_match('#^http://'.@$_SERVER['HTTP_HOST'].'(.+)#i', $_GET['src'], $matches)) {
261
-	$phpThumb->ErrorImage('It is MUCH better to specify the "src" parameter as "'.$matches[1].'" instead of "'.$matches[0].'".'."\n\n".'If you really must do it this way, enable "allow_local_http_src" in phpThumb.config.php');
261
+    $phpThumb->ErrorImage('It is MUCH better to specify the "src" parameter as "'.$matches[1].'" instead of "'.$matches[0].'".'."\n\n".'If you really must do it this way, enable "allow_local_http_src" in phpThumb.config.php');
262 262
 }
263 263
 
264 264
 ////////////////////////////////////////////////////////////////
265 265
 // Debug output, to try and help me diagnose problems
266 266
 $phpThumb->DebugTimingMessage('phpThumbDebug[1]', __FILE__, __LINE__);
267 267
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '1')) {
268
-	$phpThumb->phpThumbDebug();
268
+    $phpThumb->phpThumbDebug();
269 269
 }
270 270
 ////////////////////////////////////////////////////////////////
271 271
 
272 272
 $parsed_url_referer = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
273 273
 if ($phpThumb->config_nooffsitelink_require_refer && !in_array(@$parsed_url_referer['host'], $phpThumb->config_nohotlink_valid_domains)) {
274
-	$phpThumb->ErrorImage('config_nooffsitelink_require_refer enabled and '.(@$parsed_url_referer['host'] ? '"'.$parsed_url_referer['host'].'" is not an allowed referer' : 'no HTTP_REFERER exists'));
274
+    $phpThumb->ErrorImage('config_nooffsitelink_require_refer enabled and '.(@$parsed_url_referer['host'] ? '"'.$parsed_url_referer['host'].'" is not an allowed referer' : 'no HTTP_REFERER exists'));
275 275
 }
276 276
 $parsed_url_src = phpthumb_functions::ParseURLbetter(@$_GET['src']);
277 277
 if ($phpThumb->config_nohotlink_enabled && $phpThumb->config_nohotlink_erase_image && preg_match('#^(f|ht)tps?://#i', @$_GET['src']) && !in_array(@$parsed_url_src['host'], $phpThumb->config_nohotlink_valid_domains)) {
278
-	$phpThumb->ErrorImage($phpThumb->config_nohotlink_text_message);
278
+    $phpThumb->ErrorImage($phpThumb->config_nohotlink_text_message);
279 279
 }
280 280
 
281 281
 if ($phpThumb->config_mysql_query) {
282
-	if ($phpThumb->config_mysql_extension == 'mysqli') {
283
-
284
-		$found_missing_function = false;
285
-		foreach (array('mysqli_connect') as $required_mysqli_function) {
286
-			if (!function_exists($required_mysqli_function)) {
287
-				$found_missing_function = $required_mysqli_function;
288
-				break;
289
-			}
290
-		}
291
-		if ($found_missing_function) {
292
-			$phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
293
-		} else {
294
-			$mysqli = new mysqli($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password, $phpThumb->config_mysql_database);
295
-			if ($mysqli->connect_error) {
296
-				$phpThumb->ErrorImage('MySQLi connect error ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
297
-			} else {
298
-				if ($result = $mysqli->query($phpThumb->config_mysql_query)) {
299
-					if ($row = $result->fetch_array()) {
300
-
301
-						$result->free();
302
-						$mysqli->close();
303
-						$phpThumb->setSourceData($row[0]);
304
-						unset($row);
305
-
306
-					} else {
307
-						$result->free();
308
-						$mysqli->close();
309
-						$phpThumb->ErrorImage('no matching data in database.');
310
-					}
311
-				} else {
312
-					$mysqli->close();
313
-					$phpThumb->ErrorImage('Error in MySQL query: "'.$mysqli->error.'"');
314
-				}
315
-			}
316
-			unset($_GET['id']);
317
-		}
318
-
319
-	} elseif ($phpThumb->config_mysql_extension == 'mysql') {
320
-
321
-		$found_missing_function = false;
322
-		//foreach (array('mysql_connect', 'mysql_select_db', 'mysql_query', 'mysql_fetch_array', 'mysql_free_result', 'mysql_close', 'mysql_error') as $required_mysql_function) {
323
-		foreach (array('mysql_connect') as $required_mysql_function) {
324
-			if (!function_exists($required_mysql_function)) {
325
-				$found_missing_function = $required_mysql_function;
326
-				break;
327
-			}
328
-		}
329
-		if ($found_missing_function) {
330
-			$phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
331
-		} else {
332
-			if ($cid = @mysql_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {
333
-				if (@mysql_select_db($phpThumb->config_mysql_database, $cid)) {
334
-					if ($result = @mysql_query($phpThumb->config_mysql_query, $cid)) {
335
-						if ($row = @mysql_fetch_array($result)) {
336
-
337
-							mysql_free_result($result);
338
-							mysql_close($cid);
339
-							$phpThumb->setSourceData($row[0]);
340
-							unset($row);
341
-
342
-						} else {
343
-							mysql_free_result($result);
344
-							mysql_close($cid);
345
-							$phpThumb->ErrorImage('no matching data in database.');
346
-						}
347
-					} else {
348
-						mysql_close($cid);
349
-						$phpThumb->ErrorImage('Error in MySQL query: "'.mysql_error($cid).'"');
350
-					}
351
-				} else {
352
-					mysql_close($cid);
353
-					$phpThumb->ErrorImage('cannot select MySQL database: "'.mysql_error($cid).'"');
354
-				}
355
-			} else {
356
-				$phpThumb->ErrorImage('cannot connect to MySQL server');
357
-			}
358
-			unset($_GET['id']);
359
-		}
360
-
361
-	} else {
362
-		$phpThumb->ErrorImage('config_mysql_extension not supported');
363
-	}
282
+    if ($phpThumb->config_mysql_extension == 'mysqli') {
283
+
284
+        $found_missing_function = false;
285
+        foreach (array('mysqli_connect') as $required_mysqli_function) {
286
+            if (!function_exists($required_mysqli_function)) {
287
+                $found_missing_function = $required_mysqli_function;
288
+                break;
289
+            }
290
+        }
291
+        if ($found_missing_function) {
292
+            $phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
293
+        } else {
294
+            $mysqli = new mysqli($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password, $phpThumb->config_mysql_database);
295
+            if ($mysqli->connect_error) {
296
+                $phpThumb->ErrorImage('MySQLi connect error ('.$mysqli->connect_errno.') '.$mysqli->connect_error);
297
+            } else {
298
+                if ($result = $mysqli->query($phpThumb->config_mysql_query)) {
299
+                    if ($row = $result->fetch_array()) {
300
+
301
+                        $result->free();
302
+                        $mysqli->close();
303
+                        $phpThumb->setSourceData($row[0]);
304
+                        unset($row);
305
+
306
+                    } else {
307
+                        $result->free();
308
+                        $mysqli->close();
309
+                        $phpThumb->ErrorImage('no matching data in database.');
310
+                    }
311
+                } else {
312
+                    $mysqli->close();
313
+                    $phpThumb->ErrorImage('Error in MySQL query: "'.$mysqli->error.'"');
314
+                }
315
+            }
316
+            unset($_GET['id']);
317
+        }
318
+
319
+    } elseif ($phpThumb->config_mysql_extension == 'mysql') {
320
+
321
+        $found_missing_function = false;
322
+        //foreach (array('mysql_connect', 'mysql_select_db', 'mysql_query', 'mysql_fetch_array', 'mysql_free_result', 'mysql_close', 'mysql_error') as $required_mysql_function) {
323
+        foreach (array('mysql_connect') as $required_mysql_function) {
324
+            if (!function_exists($required_mysql_function)) {
325
+                $found_missing_function = $required_mysql_function;
326
+                break;
327
+            }
328
+        }
329
+        if ($found_missing_function) {
330
+            $phpThumb->ErrorImage('SQL function unavailable: '.$found_missing_function);
331
+        } else {
332
+            if ($cid = @mysql_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {
333
+                if (@mysql_select_db($phpThumb->config_mysql_database, $cid)) {
334
+                    if ($result = @mysql_query($phpThumb->config_mysql_query, $cid)) {
335
+                        if ($row = @mysql_fetch_array($result)) {
336
+
337
+                            mysql_free_result($result);
338
+                            mysql_close($cid);
339
+                            $phpThumb->setSourceData($row[0]);
340
+                            unset($row);
341
+
342
+                        } else {
343
+                            mysql_free_result($result);
344
+                            mysql_close($cid);
345
+                            $phpThumb->ErrorImage('no matching data in database.');
346
+                        }
347
+                    } else {
348
+                        mysql_close($cid);
349
+                        $phpThumb->ErrorImage('Error in MySQL query: "'.mysql_error($cid).'"');
350
+                    }
351
+                } else {
352
+                    mysql_close($cid);
353
+                    $phpThumb->ErrorImage('cannot select MySQL database: "'.mysql_error($cid).'"');
354
+                }
355
+            } else {
356
+                $phpThumb->ErrorImage('cannot connect to MySQL server');
357
+            }
358
+            unset($_GET['id']);
359
+        }
360
+
361
+    } else {
362
+        $phpThumb->ErrorImage('config_mysql_extension not supported');
363
+    }
364 364
 }
365 365
 
366 366
 ////////////////////////////////////////////////////////////////
367 367
 // Debug output, to try and help me diagnose problems
368 368
 $phpThumb->DebugTimingMessage('phpThumbDebug[2]', __FILE__, __LINE__);
369 369
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '2')) {
370
-	$phpThumb->phpThumbDebug();
370
+    $phpThumb->phpThumbDebug();
371 371
 }
372 372
 ////////////////////////////////////////////////////////////////
373 373
 
@@ -376,34 +376,34 @@  discard block
 block discarded – undo
376 376
 // deprecated: 'err', 'file', 'goto',
377 377
 $allowedGETparameters = array('src', 'new', 'w', 'h', 'wp', 'hp', 'wl', 'hl', 'ws', 'hs', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bc', 'bg', 'bgt', 'fltr', 'xto', 'ra', 'ar', 'aoe', 'far', 'iar', 'maxb', 'down', 'phpThumbDebug', 'hash', 'md5s', 'sfn', 'dpi', 'sia', 'nocache');
378 378
 foreach ($_GET as $key => $value) {
379
-	if (!empty($PHPTHUMB_DEFAULTS_DISABLEGETPARAMS) && ($key != 'src')) {
380
-		// disabled, do not set parameter
381
-		$phpThumb->DebugMessage('ignoring $_GET['.$key.'] because of $PHPTHUMB_DEFAULTS_DISABLEGETPARAMS', __FILE__, __LINE__);
382
-	} elseif (in_array($key, $allowedGETparameters)) {
383
-		$phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
384
-		$phpThumb->setParameter($key, $value);
385
-	} else {
386
-		$phpThumb->ErrorImage('Forbidden parameter: '.$key);
387
-	}
379
+    if (!empty($PHPTHUMB_DEFAULTS_DISABLEGETPARAMS) && ($key != 'src')) {
380
+        // disabled, do not set parameter
381
+        $phpThumb->DebugMessage('ignoring $_GET['.$key.'] because of $PHPTHUMB_DEFAULTS_DISABLEGETPARAMS', __FILE__, __LINE__);
382
+    } elseif (in_array($key, $allowedGETparameters)) {
383
+        $phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
384
+        $phpThumb->setParameter($key, $value);
385
+    } else {
386
+        $phpThumb->ErrorImage('Forbidden parameter: '.$key);
387
+    }
388 388
 }
389 389
 
390 390
 if (!empty($PHPTHUMB_DEFAULTS) && is_array($PHPTHUMB_DEFAULTS)) {
391
-	$phpThumb->DebugMessage('setting $PHPTHUMB_DEFAULTS['.implode(';', array_keys($PHPTHUMB_DEFAULTS)).']', __FILE__, __LINE__);
392
-	foreach ($PHPTHUMB_DEFAULTS as $key => $value) {
393
-		if (!$PHPTHUMB_DEFAULTS_GETSTRINGOVERRIDE || !isset($_GET[$key])) { // set parameter to default value if config is set to allow _GET to override default, OR if no value is passed via _GET for this parameter
394
-			//$_GET[$key] = $value;
395
-			//$phpThumb->DebugMessage('PHPTHUMB_DEFAULTS assigning ('.(is_array($value) ? print_r($value, true) : $value).') to $_GET['.$key.']', __FILE__, __LINE__);
396
-			$phpThumb->setParameter($key, $value);
397
-			$phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).') from $PHPTHUMB_DEFAULTS', __FILE__, __LINE__);
398
-		}
399
-	}
391
+    $phpThumb->DebugMessage('setting $PHPTHUMB_DEFAULTS['.implode(';', array_keys($PHPTHUMB_DEFAULTS)).']', __FILE__, __LINE__);
392
+    foreach ($PHPTHUMB_DEFAULTS as $key => $value) {
393
+        if (!$PHPTHUMB_DEFAULTS_GETSTRINGOVERRIDE || !isset($_GET[$key])) { // set parameter to default value if config is set to allow _GET to override default, OR if no value is passed via _GET for this parameter
394
+            //$_GET[$key] = $value;
395
+            //$phpThumb->DebugMessage('PHPTHUMB_DEFAULTS assigning ('.(is_array($value) ? print_r($value, true) : $value).') to $_GET['.$key.']', __FILE__, __LINE__);
396
+            $phpThumb->setParameter($key, $value);
397
+            $phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).') from $PHPTHUMB_DEFAULTS', __FILE__, __LINE__);
398
+        }
399
+    }
400 400
 }
401 401
 
402 402
 ////////////////////////////////////////////////////////////////
403 403
 // Debug output, to try and help me diagnose problems
404 404
 $phpThumb->DebugTimingMessage('phpThumbDebug[3]', __FILE__, __LINE__);
405 405
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '3')) {
406
-	$phpThumb->phpThumbDebug();
406
+    $phpThumb->phpThumbDebug();
407 407
 }
408 408
 ////////////////////////////////////////////////////////////////
409 409
 
@@ -422,214 +422,214 @@  discard block
 block discarded – undo
422 422
 // check to see if file can be output from source with no processing or caching
423 423
 $CanPassThroughDirectly = true;
424 424
 if ($phpThumb->rawImageData) {
425
-	// data from SQL, should be fine
425
+    // data from SQL, should be fine
426 426
 } elseif (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
427
-	// assume is ok to passthru if no other parameters specified
427
+    // assume is ok to passthru if no other parameters specified
428 428
 } elseif (preg_match('#^(f|ht)tp\://#i', $phpThumb->src)) {
429
-	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because preg_match("#^(f|ht)tp\://#i", '.$phpThumb->src.')', __FILE__, __LINE__);
430
-	$CanPassThroughDirectly = false;
429
+    $phpThumb->DebugMessage('$CanPassThroughDirectly=false because preg_match("#^(f|ht)tp\://#i", '.$phpThumb->src.')', __FILE__, __LINE__);
430
+    $CanPassThroughDirectly = false;
431 431
 } elseif (!@is_readable($phpThumb->sourceFilename)) {
432
-	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_readable('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
433
-	$CanPassThroughDirectly = false;
432
+    $phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_readable('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
433
+    $CanPassThroughDirectly = false;
434 434
 } elseif (!@is_file($phpThumb->sourceFilename)) {
435
-	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_file('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
436
-	$CanPassThroughDirectly = false;
435
+    $phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_file('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
436
+    $CanPassThroughDirectly = false;
437 437
 }
438 438
 foreach ($_GET as $key => $value) {
439
-	switch ($key) {
440
-		case 'src':
441
-			// allowed
442
-			break;
443
-
444
-		case 'w':
445
-		case 'h':
446
-			// might be OK if exactly matches original
447
-			if (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
448
-				// assume it is not ok for direct-passthru of remote image
449
-				$CanPassThroughDirectly = false;
450
-			}
451
-			break;
452
-
453
-		case 'phpThumbDebug':
454
-			// handled in direct-passthru code
455
-			break;
456
-
457
-		default:
458
-			// all other parameters will cause some processing,
459
-			// therefore cannot pass through original image unmodified
460
-			$CanPassThroughDirectly = false;
461
-			$UnAllowedGET[] = $key;
462
-			break;
463
-	}
439
+    switch ($key) {
440
+        case 'src':
441
+            // allowed
442
+            break;
443
+
444
+        case 'w':
445
+        case 'h':
446
+            // might be OK if exactly matches original
447
+            if (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
448
+                // assume it is not ok for direct-passthru of remote image
449
+                $CanPassThroughDirectly = false;
450
+            }
451
+            break;
452
+
453
+        case 'phpThumbDebug':
454
+            // handled in direct-passthru code
455
+            break;
456
+
457
+        default:
458
+            // all other parameters will cause some processing,
459
+            // therefore cannot pass through original image unmodified
460
+            $CanPassThroughDirectly = false;
461
+            $UnAllowedGET[] = $key;
462
+            break;
463
+    }
464 464
 }
465 465
 if (!empty($UnAllowedGET)) {
466
-	$phpThumb->DebugMessage('$CanPassThroughDirectly=false because $_GET['.implode(';', array_unique($UnAllowedGET)).'] are set', __FILE__, __LINE__);
466
+    $phpThumb->DebugMessage('$CanPassThroughDirectly=false because $_GET['.implode(';', array_unique($UnAllowedGET)).'] are set', __FILE__, __LINE__);
467 467
 }
468 468
 
469 469
 ////////////////////////////////////////////////////////////////
470 470
 // Debug output, to try and help me diagnose problems
471 471
 $phpThumb->DebugTimingMessage('phpThumbDebug[4]', __FILE__, __LINE__);
472 472
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '4')) {
473
-	$phpThumb->phpThumbDebug();
473
+    $phpThumb->phpThumbDebug();
474 474
 }
475 475
 ////////////////////////////////////////////////////////////////
476 476
 
477 477
 $phpThumb->DebugMessage('$CanPassThroughDirectly="'. (int) $CanPassThroughDirectly .'" && $phpThumb->src="'.$phpThumb->src.'"', __FILE__, __LINE__);
478 478
 while ($CanPassThroughDirectly && $phpThumb->src) {
479
-	// no parameters set, passthru
480
-
481
-	if (preg_match('#^http\://[^\\?&]+\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
482
-		$phpThumb->DebugMessage('Passing HTTP source through directly as Location: redirect ('.$phpThumb->src.')', __FILE__, __LINE__);
483
-		header('Location: '.$phpThumb->src);
484
-		exit;
485
-	}
486
-
487
-	$SourceFilename = $phpThumb->ResolveFilenameToAbsolute($phpThumb->src);
488
-
489
-	// security and size checks
490
-	if ($phpThumb->getimagesizeinfo = @getimagesize($SourceFilename)) {
491
-		$phpThumb->DebugMessage('Direct passthru getimagesize() returned [w='.$phpThumb->getimagesizeinfo[0].';h='.$phpThumb->getimagesizeinfo[1].';t='.$phpThumb->getimagesizeinfo[2].']', __FILE__, __LINE__);
492
-
493
-		if (!@$_GET['w'] && !@$_GET['wp'] && !@$_GET['wl'] && !@$_GET['ws'] && !@$_GET['h'] && !@$_GET['hp'] && !@$_GET['hl'] && !@$_GET['hs']) {
494
-			// no resizing needed
495
-			$phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'")', __FILE__, __LINE__);
496
-		} elseif (($phpThumb->getimagesizeinfo[0] <= @$_GET['w']) && ($phpThumb->getimagesizeinfo[1] <= @$_GET['h']) && ((@$_GET['w'] == $phpThumb->getimagesizeinfo[0]) || (@$_GET['h'] == $phpThumb->getimagesizeinfo[1]))) {
497
-			// image fits into 'w'x'h' box, and at least one dimension matches exactly, therefore no resizing needed
498
-			$phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" fits inside "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
499
-		} else {
500
-			$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because resizing required (from "'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" to "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
501
-			break;
502
-		}
503
-		switch ($phpThumb->getimagesizeinfo[2]) {
504
-			case 1: // GIF
505
-			case 2: // JPG
506
-			case 3: // PNG
507
-				// great, let it through
508
-				break;
509
-			default:
510
-				// browser probably can't handle format, remangle it to JPEG/PNG/GIF
511
-				$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because $phpThumb->getimagesizeinfo[2] = "'.$phpThumb->getimagesizeinfo[2].'"', __FILE__, __LINE__);
512
-				break 2;
513
-		}
514
-
515
-		$ImageCreateFunctions = array(1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng');
516
-		$theImageCreateFunction = @$ImageCreateFunctions[$phpThumb->getimagesizeinfo[2]];
517
-		$dummyImage = false;
518
-		if ($phpThumb->config_disable_onlycreateable_passthru || (function_exists($theImageCreateFunction) && ($dummyImage = @$theImageCreateFunction($SourceFilename)))) {
519
-
520
-			// great
521
-			if (@is_resource($dummyImage)) {
522
-				unset($dummyImage);
523
-			}
524
-
525
-			if (headers_sent()) {
526
-				$phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
527
-				exit;
528
-			}
529
-			if (!empty($_GET['phpThumbDebug'])) {
530
-				$phpThumb->DebugTimingMessage('skipped direct $SourceFilename passthru', __FILE__, __LINE__);
531
-				$phpThumb->DebugMessage('Would have passed "'.$SourceFilename.'" through directly, but skipping due to phpThumbDebug', __FILE__, __LINE__);
532
-				break;
533
-			}
534
-
535
-			SendSaveAsFileHeaderIfNeeded();
536
-			header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime($SourceFilename)).' GMT');
537
-			if ($contentType = phpthumb_functions::ImageTypeToMIMEtype(@$phpThumb->getimagesizeinfo[2])) {
538
-				header('Content-Type: '.$contentType);
539
-			}
540
-			@readfile($SourceFilename);
541
-			exit;
542
-
543
-		} else {
544
-			$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because ($phpThumb->config_disable_onlycreateable_passthru = "'.$phpThumb->config_disable_onlycreateable_passthru.'") and '.$theImageCreateFunction.'() failed', __FILE__, __LINE__);
545
-			break;
546
-		}
547
-
548
-	} else {
549
-		$phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because getimagesize() failed', __FILE__, __LINE__);
550
-		break;
551
-	}
552
-	break;
479
+    // no parameters set, passthru
480
+
481
+    if (preg_match('#^http\://[^\\?&]+\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
482
+        $phpThumb->DebugMessage('Passing HTTP source through directly as Location: redirect ('.$phpThumb->src.')', __FILE__, __LINE__);
483
+        header('Location: '.$phpThumb->src);
484
+        exit;
485
+    }
486
+
487
+    $SourceFilename = $phpThumb->ResolveFilenameToAbsolute($phpThumb->src);
488
+
489
+    // security and size checks
490
+    if ($phpThumb->getimagesizeinfo = @getimagesize($SourceFilename)) {
491
+        $phpThumb->DebugMessage('Direct passthru getimagesize() returned [w='.$phpThumb->getimagesizeinfo[0].';h='.$phpThumb->getimagesizeinfo[1].';t='.$phpThumb->getimagesizeinfo[2].']', __FILE__, __LINE__);
492
+
493
+        if (!@$_GET['w'] && !@$_GET['wp'] && !@$_GET['wl'] && !@$_GET['ws'] && !@$_GET['h'] && !@$_GET['hp'] && !@$_GET['hl'] && !@$_GET['hs']) {
494
+            // no resizing needed
495
+            $phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'")', __FILE__, __LINE__);
496
+        } elseif (($phpThumb->getimagesizeinfo[0] <= @$_GET['w']) && ($phpThumb->getimagesizeinfo[1] <= @$_GET['h']) && ((@$_GET['w'] == $phpThumb->getimagesizeinfo[0]) || (@$_GET['h'] == $phpThumb->getimagesizeinfo[1]))) {
497
+            // image fits into 'w'x'h' box, and at least one dimension matches exactly, therefore no resizing needed
498
+            $phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" fits inside "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
499
+        } else {
500
+            $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because resizing required (from "'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" to "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
501
+            break;
502
+        }
503
+        switch ($phpThumb->getimagesizeinfo[2]) {
504
+            case 1: // GIF
505
+            case 2: // JPG
506
+            case 3: // PNG
507
+                // great, let it through
508
+                break;
509
+            default:
510
+                // browser probably can't handle format, remangle it to JPEG/PNG/GIF
511
+                $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because $phpThumb->getimagesizeinfo[2] = "'.$phpThumb->getimagesizeinfo[2].'"', __FILE__, __LINE__);
512
+                break 2;
513
+        }
514
+
515
+        $ImageCreateFunctions = array(1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng');
516
+        $theImageCreateFunction = @$ImageCreateFunctions[$phpThumb->getimagesizeinfo[2]];
517
+        $dummyImage = false;
518
+        if ($phpThumb->config_disable_onlycreateable_passthru || (function_exists($theImageCreateFunction) && ($dummyImage = @$theImageCreateFunction($SourceFilename)))) {
519
+
520
+            // great
521
+            if (@is_resource($dummyImage)) {
522
+                unset($dummyImage);
523
+            }
524
+
525
+            if (headers_sent()) {
526
+                $phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
527
+                exit;
528
+            }
529
+            if (!empty($_GET['phpThumbDebug'])) {
530
+                $phpThumb->DebugTimingMessage('skipped direct $SourceFilename passthru', __FILE__, __LINE__);
531
+                $phpThumb->DebugMessage('Would have passed "'.$SourceFilename.'" through directly, but skipping due to phpThumbDebug', __FILE__, __LINE__);
532
+                break;
533
+            }
534
+
535
+            SendSaveAsFileHeaderIfNeeded();
536
+            header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime($SourceFilename)).' GMT');
537
+            if ($contentType = phpthumb_functions::ImageTypeToMIMEtype(@$phpThumb->getimagesizeinfo[2])) {
538
+                header('Content-Type: '.$contentType);
539
+            }
540
+            @readfile($SourceFilename);
541
+            exit;
542
+
543
+        } else {
544
+            $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because ($phpThumb->config_disable_onlycreateable_passthru = "'.$phpThumb->config_disable_onlycreateable_passthru.'") and '.$theImageCreateFunction.'() failed', __FILE__, __LINE__);
545
+            break;
546
+        }
547
+
548
+    } else {
549
+        $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because getimagesize() failed', __FILE__, __LINE__);
550
+        break;
551
+    }
552
+    break;
553 553
 }
554 554
 
555 555
 ////////////////////////////////////////////////////////////////
556 556
 // Debug output, to try and help me diagnose problems
557 557
 $phpThumb->DebugTimingMessage('phpThumbDebug[5]', __FILE__, __LINE__);
558 558
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '5')) {
559
-	$phpThumb->phpThumbDebug();
559
+    $phpThumb->phpThumbDebug();
560 560
 }
561 561
 ////////////////////////////////////////////////////////////////
562 562
 
563 563
 // check to see if file already exists in cache, and output it with no processing if it does
564 564
 $phpThumb->SetCacheFilename();
565 565
 if (@is_readable($phpThumb->cache_filename)) {
566
-	RedirectToCachedFile();
566
+    RedirectToCachedFile();
567 567
 } else {
568
-	$phpThumb->DebugMessage('Cached file "'.$phpThumb->cache_filename.'" does not exist, processing as normal', __FILE__, __LINE__);
568
+    $phpThumb->DebugMessage('Cached file "'.$phpThumb->cache_filename.'" does not exist, processing as normal', __FILE__, __LINE__);
569 569
 }
570 570
 
571 571
 ////////////////////////////////////////////////////////////////
572 572
 // Debug output, to try and help me diagnose problems
573 573
 $phpThumb->DebugTimingMessage('phpThumbDebug[6]', __FILE__, __LINE__);
574 574
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '6')) {
575
-	$phpThumb->phpThumbDebug();
575
+    $phpThumb->phpThumbDebug();
576 576
 }
577 577
 ////////////////////////////////////////////////////////////////
578 578
 
579 579
 if ($phpThumb->rawImageData) {
580 580
 
581
-	// great
581
+    // great
582 582
 
583 583
 } elseif (!empty($_GET['new'])) {
584 584
 
585
-	// generate a blank image resource of the specified size/background color/opacity
586
-	if (($phpThumb->w <= 0) || ($phpThumb->h <= 0)) {
587
-		$phpThumb->ErrorImage('"w" and "h" parameters required for "new"');
588
-	}
589
-	@list($bghexcolor, $opacity) = explode('|', $_GET['new']);
590
-	if (!phpthumb_functions::IsHexColor($bghexcolor)) {
591
-		$phpThumb->ErrorImage('BGcolor parameter for "new" is not valid');
592
-	}
593
-	$opacity = ('' !== $opacity ? $opacity : 100);
594
-	if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {
595
-		$alpha = (100 - min(100, max(0, $opacity))) * 1.27;
596
-		if ($alpha) {
597
-			$phpThumb->setParameter('is_alpha', true);
598
-			imagealphablending($phpThumb->gdimg_source, false);
599
-			imagesavealpha($phpThumb->gdimg_source, true);
600
-		}
601
-		$new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, $alpha);
602
-		imagefilledrectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);
603
-	} else {
604
-		$phpThumb->ErrorImage('failed to create "new" image ('.$phpThumb->w.'x'.$phpThumb->h.')');
605
-	}
585
+    // generate a blank image resource of the specified size/background color/opacity
586
+    if (($phpThumb->w <= 0) || ($phpThumb->h <= 0)) {
587
+        $phpThumb->ErrorImage('"w" and "h" parameters required for "new"');
588
+    }
589
+    @list($bghexcolor, $opacity) = explode('|', $_GET['new']);
590
+    if (!phpthumb_functions::IsHexColor($bghexcolor)) {
591
+        $phpThumb->ErrorImage('BGcolor parameter for "new" is not valid');
592
+    }
593
+    $opacity = ('' !== $opacity ? $opacity : 100);
594
+    if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {
595
+        $alpha = (100 - min(100, max(0, $opacity))) * 1.27;
596
+        if ($alpha) {
597
+            $phpThumb->setParameter('is_alpha', true);
598
+            imagealphablending($phpThumb->gdimg_source, false);
599
+            imagesavealpha($phpThumb->gdimg_source, true);
600
+        }
601
+        $new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, $alpha);
602
+        imagefilledrectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);
603
+    } else {
604
+        $phpThumb->ErrorImage('failed to create "new" image ('.$phpThumb->w.'x'.$phpThumb->h.')');
605
+    }
606 606
 
607 607
 } elseif (!$phpThumb->src) {
608 608
 
609
-	$phpThumb->ErrorImage('Usage: '.$_SERVER['PHP_SELF'].'?src=/path/and/filename.jpg'."\n".'read Usage comments for details');
609
+    $phpThumb->ErrorImage('Usage: '.$_SERVER['PHP_SELF'].'?src=/path/and/filename.jpg'."\n".'read Usage comments for details');
610 610
 
611 611
 } elseif (preg_match('#^([a-z0-9]+)://#i', $_GET['src'], $protocol_matches)) {
612 612
 
613
-	if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
614
-		$phpThumb->DebugMessage('$phpThumb->src ('.$phpThumb->src.') is remote image, attempting to download', __FILE__, __LINE__);
615
-		if ($phpThumb->config_http_user_agent) {
616
-			$phpThumb->DebugMessage('Setting "user_agent" to "'.$phpThumb->config_http_user_agent.'"', __FILE__, __LINE__);
617
-			ini_set('user_agent', $phpThumb->config_http_user_agent);
618
-		}
619
-		$cleanedupurl = phpthumb_functions::CleanUpURLencoding($phpThumb->src);
620
-		$phpThumb->DebugMessage('CleanUpURLencoding('.$phpThumb->src.') returned "'.$cleanedupurl.'"', __FILE__, __LINE__);
621
-		$phpThumb->src = $cleanedupurl;
622
-		unset($cleanedupurl);
623
-		if ($rawImageData = phpthumb_functions::SafeURLread($phpThumb->src, $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
624
-			$phpThumb->DebugMessage('SafeURLread('.$phpThumb->src.') succeeded'.($error ? ' with messages: "'.$error.'"' : ''), __FILE__, __LINE__);
625
-			$phpThumb->DebugMessage('Setting source data from URL "'.$phpThumb->src.'"', __FILE__, __LINE__);
626
-			$phpThumb->setSourceData($rawImageData, urlencode($phpThumb->src));
627
-		} else {
628
-			$phpThumb->ErrorImage($error);
629
-		}
630
-	} else {
631
-		$phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
632
-	}
613
+    if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
614
+        $phpThumb->DebugMessage('$phpThumb->src ('.$phpThumb->src.') is remote image, attempting to download', __FILE__, __LINE__);
615
+        if ($phpThumb->config_http_user_agent) {
616
+            $phpThumb->DebugMessage('Setting "user_agent" to "'.$phpThumb->config_http_user_agent.'"', __FILE__, __LINE__);
617
+            ini_set('user_agent', $phpThumb->config_http_user_agent);
618
+        }
619
+        $cleanedupurl = phpthumb_functions::CleanUpURLencoding($phpThumb->src);
620
+        $phpThumb->DebugMessage('CleanUpURLencoding('.$phpThumb->src.') returned "'.$cleanedupurl.'"', __FILE__, __LINE__);
621
+        $phpThumb->src = $cleanedupurl;
622
+        unset($cleanedupurl);
623
+        if ($rawImageData = phpthumb_functions::SafeURLread($phpThumb->src, $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
624
+            $phpThumb->DebugMessage('SafeURLread('.$phpThumb->src.') succeeded'.($error ? ' with messages: "'.$error.'"' : ''), __FILE__, __LINE__);
625
+            $phpThumb->DebugMessage('Setting source data from URL "'.$phpThumb->src.'"', __FILE__, __LINE__);
626
+            $phpThumb->setSourceData($rawImageData, urlencode($phpThumb->src));
627
+        } else {
628
+            $phpThumb->ErrorImage($error);
629
+        }
630
+    } else {
631
+        $phpThumb->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
632
+    }
633 633
 
634 634
 }
635 635
 
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 // Debug output, to try and help me diagnose problems
638 638
 $phpThumb->DebugTimingMessage('phpThumbDebug[7]', __FILE__, __LINE__);
639 639
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '7')) {
640
-	$phpThumb->phpThumbDebug();
640
+    $phpThumb->phpThumbDebug();
641 641
 }
642 642
 ////////////////////////////////////////////////////////////////
643 643
 
@@ -647,32 +647,32 @@  discard block
 block discarded – undo
647 647
 // Debug output, to try and help me diagnose problems
648 648
 $phpThumb->DebugTimingMessage('phpThumbDebug[8]', __FILE__, __LINE__);
649 649
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '8')) {
650
-	$phpThumb->phpThumbDebug();
650
+    $phpThumb->phpThumbDebug();
651 651
 }
652 652
 ////////////////////////////////////////////////////////////////
653 653
 
654 654
 if (!empty($phpThumb->config_high_security_enabled) && !empty($_GET['nocache'])) {
655 655
 
656
-	// cache disabled, don't write cachefile
656
+    // cache disabled, don't write cachefile
657 657
 
658 658
 } else {
659 659
 
660
-	phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename));
661
-	if (is_writable(dirname($phpThumb->cache_filename)) || (file_exists($phpThumb->cache_filename) && is_writable($phpThumb->cache_filename))) {
660
+    phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename));
661
+    if (is_writable(dirname($phpThumb->cache_filename)) || (file_exists($phpThumb->cache_filename) && is_writable($phpThumb->cache_filename))) {
662 662
 
663
-		$phpThumb->CleanUpCacheDirectory();
664
-		if ($phpThumb->RenderToFile($phpThumb->cache_filename) && is_readable($phpThumb->cache_filename)) {
665
-			chmod($phpThumb->cache_filename, 0644);
666
-			RedirectToCachedFile();
667
-		} else {
668
-			$phpThumb->DebugMessage('Failed: RenderToFile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
669
-		}
663
+        $phpThumb->CleanUpCacheDirectory();
664
+        if ($phpThumb->RenderToFile($phpThumb->cache_filename) && is_readable($phpThumb->cache_filename)) {
665
+            chmod($phpThumb->cache_filename, 0644);
666
+            RedirectToCachedFile();
667
+        } else {
668
+            $phpThumb->DebugMessage('Failed: RenderToFile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
669
+        }
670 670
 
671
-	} else {
671
+    } else {
672 672
 
673
-		$phpThumb->DebugMessage('Cannot write to $phpThumb->cache_filename ('.$phpThumb->cache_filename.') because that directory ('.dirname($phpThumb->cache_filename).') is not writable', __FILE__, __LINE__);
673
+        $phpThumb->DebugMessage('Cannot write to $phpThumb->cache_filename ('.$phpThumb->cache_filename.') because that directory ('.dirname($phpThumb->cache_filename).') is not writable', __FILE__, __LINE__);
674 674
 
675
-	}
675
+    }
676 676
 
677 677
 }
678 678
 
@@ -680,18 +680,18 @@  discard block
 block discarded – undo
680 680
 // Debug output, to try and help me diagnose problems
681 681
 $phpThumb->DebugTimingMessage('phpThumbDebug[9]', __FILE__, __LINE__);
682 682
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '9')) {
683
-	$phpThumb->phpThumbDebug();
683
+    $phpThumb->phpThumbDebug();
684 684
 }
685 685
 ////////////////////////////////////////////////////////////////
686 686
 
687 687
 if (!$phpThumb->OutputThumbnail()) {
688
-	$phpThumb->ErrorImage('Error in OutputThumbnail():'."\n".$phpThumb->debugmessages[(count($phpThumb->debugmessages) - 1)]);
688
+    $phpThumb->ErrorImage('Error in OutputThumbnail():'."\n".$phpThumb->debugmessages[(count($phpThumb->debugmessages) - 1)]);
689 689
 }
690 690
 
691 691
 ////////////////////////////////////////////////////////////////
692 692
 // Debug output, to try and help me diagnose problems
693 693
 $phpThumb->DebugTimingMessage('phpThumbDebug[10]', __FILE__, __LINE__);
694 694
 if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '10')) {
695
-	$phpThumb->phpThumbDebug();
695
+    $phpThumb->phpThumbDebug();
696 696
 }
697 697
 ////////////////////////////////////////////////////////////////
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 		header('Pragma: private');
81 81
 		header('Cache-Control: max-age='.$phpThumb->getParameter('config_cache_maxage'));
82
-		header('Expires: '.date(DATE_RFC1123,  time() + $phpThumb->getParameter('config_cache_maxage')));
82
+		header('Expires: '.date(DATE_RFC1123, time() + $phpThumb->getParameter('config_cache_maxage')));
83 83
 		if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && !empty($_SERVER['SERVER_PROTOCOL'])) {
84 84
 			header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
85 85
 			header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
@@ -108,9 +108,9 @@  discard block
 block discarded – undo
108 108
 
109 109
 // instantiate a new phpThumb() object
110 110
 ob_start();
111
-if (!include_once( __DIR__ .'/phpthumb.class.php')) {
111
+if (!include_once(__DIR__.'/phpthumb.class.php')) {
112 112
 	ob_end_flush();
113
-	die('failed to include_once("'.realpath( __DIR__ .'/phpthumb.class.php').'")');
113
+	die('failed to include_once("'.realpath(__DIR__.'/phpthumb.class.php').'")');
114 114
 }
115 115
 ob_end_clean();
116 116
 $phpThumb = new phpThumb();
@@ -118,28 +118,28 @@  discard block
 block discarded – undo
118 118
 $phpThumb->setParameter('config_error_die_on_error', true);
119 119
 
120 120
 if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
121
-	set_time_limit(60);  // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
121
+	set_time_limit(60); // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
122 122
 }
123 123
 
124 124
 // phpThumbDebug[0] used to be here, but may reveal too much
125 125
 // info when high_security_mode should be enabled (not set yet)
126 126
 
127
-if (file_exists( __DIR__ .'/phpThumb.config.php')) {
127
+if (file_exists(__DIR__.'/phpThumb.config.php')) {
128 128
 	ob_start();
129
-	if (include_once( __DIR__ .'/phpThumb.config.php')) {
129
+	if (include_once(__DIR__.'/phpThumb.config.php')) {
130 130
 		// great
131 131
 	} else {
132 132
 		ob_end_flush();
133 133
 		$phpThumb->config_disable_debug = false; // otherwise error message won't print
134
-		$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
134
+		$phpThumb->ErrorImage('failed to include_once('.__DIR__.'/phpThumb.config.php) - realpath="'.realpath(__DIR__.'/phpThumb.config.php').'"');
135 135
 	}
136 136
 	ob_end_clean();
137
-} elseif (file_exists( __DIR__ .'/phpThumb.config.php.default')) {
137
+} elseif (file_exists(__DIR__.'/phpThumb.config.php.default')) {
138 138
 	$phpThumb->config_disable_debug = false; // otherwise error message won't print
139 139
 	$phpThumb->ErrorImage('Please rename "phpThumb.config.php.default" to "phpThumb.config.php"');
140 140
 } else {
141 141
 	$phpThumb->config_disable_debug = false; // otherwise error message won't print
142
-	$phpThumb->ErrorImage('failed to include_once('. __DIR__ .'/phpThumb.config.php) - realpath="'.realpath( __DIR__ .'/phpThumb.config.php').'"');
142
+	$phpThumb->ErrorImage('failed to include_once('.__DIR__.'/phpThumb.config.php) - realpath="'.realpath(__DIR__.'/phpThumb.config.php').'"');
143 143
 }
144 144
 
145 145
 if (!empty($PHPTHUMB_CONFIG)) {
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 	}
153 153
 	if (!$phpThumb->config_disable_debug) {
154 154
 		// if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
155
-		$_GET['phpThumbDebug'] = (!empty($_GET['phpThumbDebug']) ? max(1, (int) $_GET[ 'phpThumbDebug']) : 9);
155
+		$_GET['phpThumbDebug'] = (!empty($_GET['phpThumbDebug']) ? max(1, (int)$_GET['phpThumbDebug']) : 9);
156 156
 		$phpThumb->setParameter('phpThumbDebug', $_GET['phpThumbDebug']);
157 157
 	}
158 158
 } else {
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 }
372 372
 ////////////////////////////////////////////////////////////////
373 373
 
374
-$PHPTHUMB_DEFAULTS_DISABLEGETPARAMS = (bool) ($phpThumb->config_cache_default_only_suffix && (strpos($phpThumb->config_cache_default_only_suffix, '*') !== false));
374
+$PHPTHUMB_DEFAULTS_DISABLEGETPARAMS = (bool)($phpThumb->config_cache_default_only_suffix && (strpos($phpThumb->config_cache_default_only_suffix, '*') !== false));
375 375
 
376 376
 // deprecated: 'err', 'file', 'goto',
377 377
 $allowedGETparameters = array('src', 'new', 'w', 'h', 'wp', 'hp', 'wl', 'hl', 'ws', 'hs', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bc', 'bg', 'bgt', 'fltr', 'xto', 'ra', 'ar', 'aoe', 'far', 'iar', 'maxb', 'down', 'phpThumbDebug', 'hash', 'md5s', 'sfn', 'dpi', 'sia', 'nocache');
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 }
475 475
 ////////////////////////////////////////////////////////////////
476 476
 
477
-$phpThumb->DebugMessage('$CanPassThroughDirectly="'. (int) $CanPassThroughDirectly .'" && $phpThumb->src="'.$phpThumb->src.'"', __FILE__, __LINE__);
477
+$phpThumb->DebugMessage('$CanPassThroughDirectly="'.(int)$CanPassThroughDirectly.'" && $phpThumb->src="'.$phpThumb->src.'"', __FILE__, __LINE__);
478 478
 while ($CanPassThroughDirectly && $phpThumb->src) {
479 479
 	// no parameters set, passthru
480 480
 
Please login to merge, or discard this patch.
htdocs/install/include/makedata.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -198,9 +198,9 @@  discard block
 block discarded – undo
198 198
     $dbm->insert('config', " VALUES (32, 0, 1, 'com_mode', '_MD_AM_COMMODE', 'flat', '_MD_AM_COMMODEDSC', 'select', 'text', 34)");
199 199
     $dbm->insert('config', " VALUES (33, 0, 1, 'com_order', '_MD_AM_COMORDER', '0', '_MD_AM_COMORDERDSC', 'select', 'int', 36)");
200 200
     $dbm->insert('config', " VALUES (34, 0, 2, 'bad_unames', '_MD_AM_BADUNAMES', '" . addslashes(serialize(array(
201
-                                                                                                               'webmaster',
202
-                                                                                                               '^xoops',
203
-                                                                                                               '^admin'))) . "', '_MD_AM_BADUNAMESDSC', 'textarea', 'array', 24)");
201
+                                                                                                                'webmaster',
202
+                                                                                                                '^xoops',
203
+                                                                                                                '^admin'))) . "', '_MD_AM_BADUNAMESDSC', 'textarea', 'array', 24)");
204 204
     $dbm->insert('config', " VALUES (35, 0, 2, 'bad_emails', '_MD_AM_BADEMAILS', '" . addslashes(serialize(array('xoops.org$'))) . "', '_MD_AM_BADEMAILSDSC', 'textarea', 'array', 26)");
205 205
     $dbm->insert('config', " VALUES (36, 0, 2, 'maxuname', '_MD_AM_MAXUNAME', '10', '_MD_AM_MAXUNAMEDSC', 'textbox', 'int', 3)");
206 206
     $dbm->insert('config', " VALUES (37, 0, 1, 'bad_ips', '_MD_AM_BADIPS', '" . addslashes(serialize(array('127.0.0.1'))) . "', '_MD_AM_BADIPSDSC', 'textarea', 'array', 42)");
@@ -208,8 +208,8 @@  discard block
 block discarded – undo
208 208
     $dbm->insert('config', " VALUES (39, 0, 3, 'footer', '_MD_AM_FOOTER', 'Powered by XOOPS &#169; 2001-" . date('Y', time()) . " <a href=\"http://xoops.org\" rel=\"external\" title=\"The XOOPS Project\">The XOOPS Project</a>', '_MD_AM_FOOTERDSC', 'textarea', 'text', 20)");
209 209
     $dbm->insert('config', " VALUES (40, 0, 4, 'censor_enable', '_MD_AM_DOCENSOR', '0', '_MD_AM_DOCENSORDSC', 'yesno', 'int', 0)");
210 210
     $dbm->insert('config', " VALUES (41, 0, 4, 'censor_words', '_MD_AM_CENSORWRD', '" . addslashes(serialize(array(
211
-                                                                                                                 'fuck',
212
-                                                                                                                 'shit'))) . "', '_MD_AM_CENSORWRDDSC', 'textarea', 'array', 1)");
211
+                                                                                                                    'fuck',
212
+                                                                                                                    'shit'))) . "', '_MD_AM_CENSORWRDDSC', 'textarea', 'array', 1)");
213 213
     $dbm->insert('config', " VALUES (42, 0, 4, 'censor_replace', '_MD_AM_CENSORRPLC', '#OOPS#', '_MD_AM_CENSORRPLCDSC', 'textbox', 'text', 2)");
214 214
     $dbm->insert('config', " VALUES (43, 0, 3, 'meta_robots', '_MD_AM_METAROBOTS', 'index,follow', '_MD_AM_METAROBOTSDSC', 'textbox', 'text', 2)");
215 215
     $dbm->insert('config', " VALUES (44, 0, 5, 'enable_search', '_MD_AM_DOSEARCH', '1', '_MD_AM_DOSEARCHDSC', 'yesno', 'int', 0)");
Please login to merge, or discard this patch.
Spacing   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -33,9 +33,9 @@  discard block
 block discarded – undo
33 33
 // of missing fields in install file, when add new fields to database)
34 34
 function make_groups(&$dbm)
35 35
 {
36
-    $groups['XOOPS_GROUP_ADMIN']     = $dbm->insert('groups', " VALUES (1, '" . addslashes(_INSTALL_WEBMASTER) . "', '" . addslashes(_INSTALL_WEBMASTERD) . "', 'Admin')");
37
-    $groups['XOOPS_GROUP_USERS']     = $dbm->insert('groups', " VALUES (2, '" . addslashes(_INSTALL_REGUSERS) . "', '" . addslashes(_INSTALL_REGUSERSD) . "', 'User')");
38
-    $groups['XOOPS_GROUP_ANONYMOUS'] = $dbm->insert('groups', " VALUES (3, '" . addslashes(_INSTALL_ANONUSERS) . "', '" . addslashes(_INSTALL_ANONUSERSD) . "', 'Anonymous')");
36
+    $groups['XOOPS_GROUP_ADMIN']     = $dbm->insert('groups', " VALUES (1, '".addslashes(_INSTALL_WEBMASTER)."', '".addslashes(_INSTALL_WEBMASTERD)."', 'Admin')");
37
+    $groups['XOOPS_GROUP_USERS']     = $dbm->insert('groups', " VALUES (2, '".addslashes(_INSTALL_REGUSERS)."', '".addslashes(_INSTALL_REGUSERSD)."', 'User')");
38
+    $groups['XOOPS_GROUP_ANONYMOUS'] = $dbm->insert('groups', " VALUES (3, '".addslashes(_INSTALL_ANONUSERS)."', '".addslashes(_INSTALL_ANONUSERSD)."', 'Anonymous')");
39 39
     if (!$groups['XOOPS_GROUP_ADMIN'] || !$groups['XOOPS_GROUP_USERS'] || !$groups['XOOPS_GROUP_ANONYMOUS']) {
40 40
         return false;
41 41
     }
@@ -61,42 +61,42 @@  discard block
 block discarded – undo
61 61
     $tables = array();
62 62
     // data for table 'groups_users_link'
63 63
     /* @var  $dbm Db_manager */
64
-    $dbm->insert('groups_users_link', ' VALUES (0, ' . $groups['XOOPS_GROUP_ADMIN'] . ', 1)');
65
-    $dbm->insert('groups_users_link', ' VALUES (0, ' . $groups['XOOPS_GROUP_USERS'] . ', 1)');
64
+    $dbm->insert('groups_users_link', ' VALUES (0, '.$groups['XOOPS_GROUP_ADMIN'].', 1)');
65
+    $dbm->insert('groups_users_link', ' VALUES (0, '.$groups['XOOPS_GROUP_USERS'].', 1)');
66 66
     // data for table 'group_permission'
67
-    $dbm->insert('group_permission', ' VALUES (0,' . $groups['XOOPS_GROUP_ADMIN'] . ",1,1,'module_admin')");
68
-    $dbm->insert('group_permission', ' VALUES (0,' . $groups['XOOPS_GROUP_ADMIN'] . ",1,1, 'module_read')");
69
-    $dbm->insert('group_permission', ' VALUES (0,' . $groups['XOOPS_GROUP_USERS'] . ",1,1,'module_read')");
70
-    $dbm->insert('group_permission', ' VALUES (0,' . $groups['XOOPS_GROUP_ANONYMOUS'] . ",1,1,'module_read')");
67
+    $dbm->insert('group_permission', ' VALUES (0,'.$groups['XOOPS_GROUP_ADMIN'].",1,1,'module_admin')");
68
+    $dbm->insert('group_permission', ' VALUES (0,'.$groups['XOOPS_GROUP_ADMIN'].",1,1, 'module_read')");
69
+    $dbm->insert('group_permission', ' VALUES (0,'.$groups['XOOPS_GROUP_USERS'].",1,1,'module_read')");
70
+    $dbm->insert('group_permission', ' VALUES (0,'.$groups['XOOPS_GROUP_ANONYMOUS'].",1,1,'module_read')");
71 71
 
72
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",1,1,'system_admin')");
73
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",2,1,'system_admin')");
74
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",3,1,'system_admin')");
75
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",4,1,'system_admin')");
76
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",5,1,'system_admin')");
77
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",6,1,'system_admin')");
78
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",7,1,'system_admin')");
79
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",8,1,'system_admin')");
80
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",9,1,'system_admin')");
81
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",10,1,'system_admin')");
82
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",11,1,'system_admin')");
83
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",12,1,'system_admin')");
84
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",13,1,'system_admin')");
85
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",14,1,'system_admin')");
86
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",15,1,'system_admin')");
87
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",16,1,'system_admin')");
88
-    $dbm->insert('group_permission', ' VALUES(0,' . $groups['XOOPS_GROUP_ADMIN'] . ",17,1,'system_admin')");
72
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",1,1,'system_admin')");
73
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",2,1,'system_admin')");
74
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",3,1,'system_admin')");
75
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",4,1,'system_admin')");
76
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",5,1,'system_admin')");
77
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",6,1,'system_admin')");
78
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",7,1,'system_admin')");
79
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",8,1,'system_admin')");
80
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",9,1,'system_admin')");
81
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",10,1,'system_admin')");
82
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",11,1,'system_admin')");
83
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",12,1,'system_admin')");
84
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",13,1,'system_admin')");
85
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",14,1,'system_admin')");
86
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",15,1,'system_admin')");
87
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",16,1,'system_admin')");
88
+    $dbm->insert('group_permission', ' VALUES(0,'.$groups['XOOPS_GROUP_ADMIN'].",17,1,'system_admin')");
89 89
     // data for table 'banner'
90
-    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '" . XOOPS_URL . "/images/banners/xoops_flashbanner2.htm', 'http://www.xoops.org/', 1008813250, 1,'')");
91
-    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '" . XOOPS_URL . "/images/banners/xoops_banner_2.gif', 'http://www.xoops.org/', 1008813250, 0, '')");
92
-    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '" . XOOPS_URL . "/images/banners/banner.htm', 'http://www.xoops.org/', 1008813250, 1, '')");
93
-    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '" . XOOPS_URL . "/images/banners/xoopsifyIt.gif', 'http://www.xoops.org/', 1008813250, 1, '')");
90
+    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '".XOOPS_URL."/images/banners/xoops_flashbanner2.htm', 'http://www.xoops.org/', 1008813250, 1,'')");
91
+    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '".XOOPS_URL."/images/banners/xoops_banner_2.gif', 'http://www.xoops.org/', 1008813250, 0, '')");
92
+    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '".XOOPS_URL."/images/banners/banner.htm', 'http://www.xoops.org/', 1008813250, 1, '')");
93
+    $dbm->insert('banner', " (bid, cid, imptotal, impmade, clicks, imageurl, clickurl, date, htmlbanner, htmlcode) VALUES (0, 1, 0, 1, 0, '".XOOPS_URL."/images/banners/xoopsifyIt.gif', 'http://www.xoops.org/', 1008813250, 1, '')");
94 94
     // default theme
95 95
     $time = time();
96
-    $dbm->insert('tplset', " VALUES (1, 'default', 'XOOPS Default Template Set', '', " . $time . ')');
96
+    $dbm->insert('tplset', " VALUES (1, 'default', 'XOOPS Default Template Set', '', ".$time.')');
97 97
     // system modules
98
-    if (file_exists('../modules/system/language/' . $language . '/modinfo.php')) {
99
-        include '../modules/system/language/' . $language . '/modinfo.php';
98
+    if (file_exists('../modules/system/language/'.$language.'/modinfo.php')) {
99
+        include '../modules/system/language/'.$language.'/modinfo.php';
100 100
     } else {
101 101
         include '../modules/system/language/english/modinfo.php';
102 102
         $language = 'english';
@@ -106,46 +106,46 @@  discard block
 block discarded – undo
106 106
     include_once '../modules/system/xoops_version.php';
107 107
     $time = time();
108 108
     // RMV-NOTIFY (updated for extra column in table)
109
-    $dbm->insert('modules', " VALUES (1, '" . _MI_SYSTEM_NAME . "', " . ($modversion['version'] * 100) . ', ' . $time . ", 0, 1, 'system', 0, 1, 0, 0, 0, 0)");
109
+    $dbm->insert('modules', " VALUES (1, '"._MI_SYSTEM_NAME."', ".($modversion['version'] * 100).', '.$time.", 0, 1, 'system', 0, 1, 0, 0, 0, 0)");
110 110
 
111 111
     foreach ($modversion['templates'] as $tplfile) {
112 112
         // Main templates
113
-        if ($fp = fopen('../modules/system/templates/' . $tplfile['file'], 'r')) {
114
-            $newtplid = $dbm->insert('tplfile', " VALUES (0, 1, 'system', 'default', '" . addslashes($tplfile['file']) . "', '" . addslashes($tplfile['description']) . "', " . $time . ', ' . $time . ", 'module')");
113
+        if ($fp = fopen('../modules/system/templates/'.$tplfile['file'], 'r')) {
114
+            $newtplid = $dbm->insert('tplfile', " VALUES (0, 1, 'system', 'default', '".addslashes($tplfile['file'])."', '".addslashes($tplfile['description'])."', ".$time.', '.$time.", 'module')");
115 115
             // $newtplid = $xoopsDB->getInsertId();
116
-            $tplsource = fread($fp, filesize('../modules/system/templates/' . $tplfile['file']));
116
+            $tplsource = fread($fp, filesize('../modules/system/templates/'.$tplfile['file']));
117 117
             fclose($fp);
118
-            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES (' . $newtplid . ", '" . addslashes($tplsource) . "')");
118
+            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES ('.$newtplid.", '".addslashes($tplsource)."')");
119 119
         }
120 120
         // Admin templates
121
-        if ($fp = fopen('../modules/system/templates/admin/' . $tplfile['file'], 'r')) {
122
-            $newtplid = $dbm->insert('tplfile', " VALUES (0, 1, 'system', 'default', '" . addslashes($tplfile['file']) . "', '" . addslashes($tplfile['description']) . "', " . $time . ', ' . $time . ", 'admin')");
121
+        if ($fp = fopen('../modules/system/templates/admin/'.$tplfile['file'], 'r')) {
122
+            $newtplid = $dbm->insert('tplfile', " VALUES (0, 1, 'system', 'default', '".addslashes($tplfile['file'])."', '".addslashes($tplfile['description'])."', ".$time.', '.$time.", 'admin')");
123 123
             // $newtplid = $xoopsDB->getInsertId();
124
-            $tplsource = fread($fp, filesize('../modules/system/templates/admin/' . $tplfile['file']));
124
+            $tplsource = fread($fp, filesize('../modules/system/templates/admin/'.$tplfile['file']));
125 125
             fclose($fp);
126
-            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES (' . $newtplid . ", '" . addslashes($tplsource) . "')");
126
+            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES ('.$newtplid.", '".addslashes($tplsource)."')");
127 127
         }
128 128
     }
129 129
 
130 130
     foreach ($modversion['blocks'] as $func_num => $newblock) {
131
-        if ($fp = fopen('../modules/system/templates/blocks/' . $newblock['template'], 'r')) {
131
+        if ($fp = fopen('../modules/system/templates/blocks/'.$newblock['template'], 'r')) {
132 132
             $visible = 0;
133 133
             if (in_array($newblock['template'], array('system_block_user.tpl', 'system_block_login.tpl', 'system_block_mainmenu.tpl'))) {
134 134
                 $visible = 1;
135 135
             }
136 136
             $options   = !isset($newblock['options']) ? '' : trim($newblock['options']);
137 137
             $edit_func = !isset($newblock['edit_func']) ? '' : trim($newblock['edit_func']);
138
-            $newbid    = $dbm->insert('newblocks', ' VALUES (0, 1, ' . $func_num . ", '" . addslashes($options) . "', '" . addslashes($newblock['name']) . "', '" . addslashes($newblock['name']) . "', '', 0, 0, " . $visible . ", 'S', 'H', 1, 'system', '" . addslashes($newblock['file']) . "', '" . addslashes($newblock['show_func']) . "', '" . addslashes($edit_func) . "', '" . addslashes($newblock['template']) . "', 0, " . $time . ')');
138
+            $newbid    = $dbm->insert('newblocks', ' VALUES (0, 1, '.$func_num.", '".addslashes($options)."', '".addslashes($newblock['name'])."', '".addslashes($newblock['name'])."', '', 0, 0, ".$visible.", 'S', 'H', 1, 'system', '".addslashes($newblock['file'])."', '".addslashes($newblock['show_func'])."', '".addslashes($edit_func)."', '".addslashes($newblock['template'])."', 0, ".$time.')');
139 139
             // $newbid = $xoopsDB->getInsertId();
140
-            $newtplid = $dbm->insert('tplfile', ' VALUES (0, ' . $newbid . ", 'system', 'default', '" . addslashes($newblock['template']) . "', '" . addslashes($newblock['description']) . "', " . $time . ', ' . $time . ", 'block')");
140
+            $newtplid = $dbm->insert('tplfile', ' VALUES (0, '.$newbid.", 'system', 'default', '".addslashes($newblock['template'])."', '".addslashes($newblock['description'])."', ".$time.', '.$time.", 'block')");
141 141
             // $newtplid = $xoopsDB->getInsertId();
142
-            $tplsource = fread($fp, filesize('../modules/system/templates/blocks/' . $newblock['template']));
142
+            $tplsource = fread($fp, filesize('../modules/system/templates/blocks/'.$newblock['template']));
143 143
             fclose($fp);
144
-            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES (' . $newtplid . ", '" . addslashes($tplsource) . "')");
145
-            $dbm->insert('group_permission', ' VALUES (0, ' . $groups['XOOPS_GROUP_ADMIN'] . ', ' . $newbid . ", 1, 'block_read')");
144
+            $dbm->insert('tplsource', ' (tpl_id, tpl_source) VALUES ('.$newtplid.", '".addslashes($tplsource)."')");
145
+            $dbm->insert('group_permission', ' VALUES (0, '.$groups['XOOPS_GROUP_ADMIN'].', '.$newbid.", 1, 'block_read')");
146 146
             // $dbm->insert("group_permission", " VALUES (0, ".$groups['XOOPS_GROUP_ADMIN'].", ".$newbid.", 'xoops_blockadmiin')");
147
-            $dbm->insert('group_permission', ' VALUES (0, ' . $groups['XOOPS_GROUP_USERS'] . ', ' . $newbid . ", 1, 'block_read')");
148
-            $dbm->insert('group_permission', ' VALUES (0, ' . $groups['XOOPS_GROUP_ANONYMOUS'] . ', ' . $newbid . ", 1, 'block_read')");
147
+            $dbm->insert('group_permission', ' VALUES (0, '.$groups['XOOPS_GROUP_USERS'].', '.$newbid.", 1, 'block_read')");
148
+            $dbm->insert('group_permission', ' VALUES (0, '.$groups['XOOPS_GROUP_ANONYMOUS'].', '.$newbid.", 1, 'block_read')");
149 149
         }
150 150
     }
151 151
     // data for table 'users'
@@ -153,63 +153,63 @@  discard block
 block discarded – undo
153 153
     $regdate = time();
154 154
     // $dbadminname= addslashes($adminname);
155 155
     // RMV-NOTIFY (updated for extra columns in user table)
156
-    $dbm->insert('users', " VALUES (1,'','" . addslashes($adminname) . "','" . addslashes($adminmail) . "','" . XOOPS_URL . "/','avatars/blank.gif','" . $regdate . "','','','',1,'','','','','" . $temp . "',0,0,7,5,'default','0.0'," . time() . ",'flat',0,1,0,'','','',0)");
156
+    $dbm->insert('users', " VALUES (1,'','".addslashes($adminname)."','".addslashes($adminmail)."','".XOOPS_URL."/','avatars/blank.gif','".$regdate."','','','',1,'','','','','".$temp."',0,0,7,5,'default','0.0',".time().",'flat',0,1,0,'','','',0)");
157 157
     // data for table 'block_module_link'
158
-    $sql    = 'SELECT bid, side FROM ' . $dbm->prefix('newblocks');
158
+    $sql    = 'SELECT bid, side FROM '.$dbm->prefix('newblocks');
159 159
     $result = $dbm->query($sql);
160 160
 
161 161
     while (false !== ($myrow = $dbm->fetchArray($result))) {
162 162
         if ($myrow['side'] == 0) {
163
-            $dbm->insert('block_module_link', ' VALUES (' . $myrow['bid'] . ', 0)');
163
+            $dbm->insert('block_module_link', ' VALUES ('.$myrow['bid'].', 0)');
164 164
         } else {
165
-            $dbm->insert('block_module_link', ' VALUES (' . $myrow['bid'] . ', -1)');
165
+            $dbm->insert('block_module_link', ' VALUES ('.$myrow['bid'].', -1)');
166 166
         }
167 167
     }
168 168
     // data for table 'config'
169 169
     $dbm->insert('config', " VALUES (1, 0, 1, 'sitename', '_MD_AM_SITENAME', 'XOOPS Site', '_MD_AM_SITENAMEDSC', 'textbox', 'text', 0)");
170 170
     $dbm->insert('config', " VALUES (2, 0, 1, 'slogan', '_MD_AM_SLOGAN', 'Just Use it!', '_MD_AM_SLOGANDSC', 'textbox', 'text', 2)");
171
-    $dbm->insert('config', " VALUES (3, 0, 1, 'language', '_MD_AM_LANGUAGE', '" . addslashes($language) . "', '_MD_AM_LANGUAGEDSC', 'language', 'other', 4)");
171
+    $dbm->insert('config', " VALUES (3, 0, 1, 'language', '_MD_AM_LANGUAGE', '".addslashes($language)."', '_MD_AM_LANGUAGEDSC', 'language', 'other', 4)");
172 172
     $dbm->insert('config', " VALUES (4, 0, 1, 'startpage', '_MD_AM_STARTPAGE', '--', '_MD_AM_STARTPAGEDSC', 'startpage', 'other', 6)");
173 173
     $dbm->insert('config', " VALUES (5, 0, 1, 'server_TZ', '_MD_AM_SERVERTZ', '0', '_MD_AM_SERVERTZDSC', 'timezone', 'float', 8)");
174 174
     $dbm->insert('config', " VALUES (6, 0, 1, 'default_TZ', '_MD_AM_DEFAULTTZ', '0', '_MD_AM_DEFAULTTZDSC', 'timezone', 'float', 10)");
175
-    $dbm->insert('config', " VALUES (7, 0, 1, 'theme_set', '_MD_AM_DTHEME', '" . $defaultTheme ."', '_MD_AM_DTHEMEDSC', 'theme', 'other', 12)");
176
-    $dbm->insert('config', " VALUES (8, 0, 1, 'anonymous', '_MD_AM_ANONNAME', '" . addslashes(_INSTALL_ANON) . "', '_MD_AM_ANONNAMEDSC', 'textbox', 'text', 15)");
175
+    $dbm->insert('config', " VALUES (7, 0, 1, 'theme_set', '_MD_AM_DTHEME', '".$defaultTheme."', '_MD_AM_DTHEMEDSC', 'theme', 'other', 12)");
176
+    $dbm->insert('config', " VALUES (8, 0, 1, 'anonymous', '_MD_AM_ANONNAME', '".addslashes(_INSTALL_ANON)."', '_MD_AM_ANONNAMEDSC', 'textbox', 'text', 15)");
177 177
     $dbm->insert('config', " VALUES (9, 0, 1, 'gzip_compression', '_MD_AM_USEGZIP', '0', '_MD_AM_USEGZIPDSC', 'yesno', 'int', 16)");
178
-    $dbm->insert('config', " VALUES (10, 0, 1, 'usercookie', '_MD_AM_USERCOOKIE', 'xoops_user_" . dechex(time()) . "', '_MD_AM_USERCOOKIEDSC', 'textbox', 'text', 18)");
178
+    $dbm->insert('config', " VALUES (10, 0, 1, 'usercookie', '_MD_AM_USERCOOKIE', 'xoops_user_".dechex(time())."', '_MD_AM_USERCOOKIEDSC', 'textbox', 'text', 18)");
179 179
     $dbm->insert('config', " VALUES (11, 0, 1, 'session_expire', '_MD_AM_SESSEXPIRE', '15', '_MD_AM_SESSEXPIREDSC', 'textbox', 'int', 22)");
180 180
     $dbm->insert('config', " VALUES (12, 0, 1, 'banners', '_MD_AM_BANNERS', '1', '_MD_AM_BANNERSDSC', 'yesno', 'int', 26)");
181 181
     $dbm->insert('config', " VALUES (13, 0, 1, 'debug_mode', '_MD_AM_DEBUGMODE', '0', '_MD_AM_DEBUGMODEDSC', 'select', 'int', 24)");
182 182
     $dbm->insert('config', " VALUES (14, 0, 1, 'my_ip', '_MD_AM_MYIP', '127.0.0.1', '_MD_AM_MYIPDSC', 'textbox', 'text', 29)");
183 183
     $dbm->insert('config', " VALUES (15, 0, 1, 'use_ssl', '_MD_AM_USESSL', '0', '_MD_AM_USESSLDSC', 'yesno', 'int', 30)");
184
-    $dbm->insert('config', " VALUES (16, 0, 1, 'session_name', '_MD_AM_SESSNAME', 'xoops_session_" . dechex(time()) . "', '_MD_AM_SESSNAMEDSC', 'textbox', 'text', 20)");
184
+    $dbm->insert('config', " VALUES (16, 0, 1, 'session_name', '_MD_AM_SESSNAME', 'xoops_session_".dechex(time())."', '_MD_AM_SESSNAMEDSC', 'textbox', 'text', 20)");
185 185
     $dbm->insert('config', " VALUES (17, 0, 2, 'minpass', '_MD_AM_MINPASS', '5', '_MD_AM_MINPASSDSC', 'textbox', 'int', 1)");
186 186
     $dbm->insert('config', " VALUES (18, 0, 2, 'minuname', '_MD_AM_MINUNAME', '3', '_MD_AM_MINUNAMEDSC', 'textbox', 'int', 2)");
187 187
     $dbm->insert('config', " VALUES (19, 0, 2, 'new_user_notify', '_MD_AM_NEWUNOTIFY', '1', '_MD_AM_NEWUNOTIFYDSC', 'yesno', 'int', 4)");
188
-    $dbm->insert('config', " VALUES (20, 0, 2, 'new_user_notify_group', '_MD_AM_NOTIFYTO', " . $groups['XOOPS_GROUP_ADMIN'] . ", '_MD_AM_NOTIFYTODSC', 'group', 'int', 6)");
188
+    $dbm->insert('config', " VALUES (20, 0, 2, 'new_user_notify_group', '_MD_AM_NOTIFYTO', ".$groups['XOOPS_GROUP_ADMIN'].", '_MD_AM_NOTIFYTODSC', 'group', 'int', 6)");
189 189
     $dbm->insert('config', " VALUES (21, 0, 2, 'activation_type', '_MD_AM_ACTVTYPE', '0', '_MD_AM_ACTVTYPEDSC', 'select', 'int', 8)");
190
-    $dbm->insert('config', " VALUES (22, 0, 2, 'activation_group', '_MD_AM_ACTVGROUP', " . $groups['XOOPS_GROUP_ADMIN'] . ", '_MD_AM_ACTVGROUPDSC', 'group', 'int', 10)");
190
+    $dbm->insert('config', " VALUES (22, 0, 2, 'activation_group', '_MD_AM_ACTVGROUP', ".$groups['XOOPS_GROUP_ADMIN'].", '_MD_AM_ACTVGROUPDSC', 'group', 'int', 10)");
191 191
     $dbm->insert('config', " VALUES (23, 0, 2, 'uname_test_level', '_MD_AM_UNAMELVL', '0', '_MD_AM_UNAMELVLDSC', 'select', 'int', 12)");
192 192
     $dbm->insert('config', " VALUES (24, 0, 2, 'avatar_allow_upload', '_MD_AM_AVATARALLOW', '0', '_MD_AM_AVATARALWDSC', 'yesno', 'int', 14)");
193 193
     $dbm->insert('config', " VALUES (27, 0, 2, 'avatar_width', '_MD_AM_AVATARW', '128', '_MD_AM_AVATARWDSC', 'textbox', 'int', 16)");
194 194
     $dbm->insert('config', " VALUES (28, 0, 2, 'avatar_height', '_MD_AM_AVATARH', '128', '_MD_AM_AVATARHDSC', 'textbox', 'int', 18)");
195 195
     $dbm->insert('config', " VALUES (29, 0, 2, 'avatar_maxsize', '_MD_AM_AVATARMAX', '35000', '_MD_AM_AVATARMAXDSC', 'textbox', 'int', 20)");
196
-    $dbm->insert('config', " VALUES (30, 0, 1, 'adminmail', '_MD_AM_ADMINML', '" . addslashes($adminmail) . "', '_MD_AM_ADMINMLDSC', 'textbox', 'text', 3)");
196
+    $dbm->insert('config', " VALUES (30, 0, 1, 'adminmail', '_MD_AM_ADMINML', '".addslashes($adminmail)."', '_MD_AM_ADMINMLDSC', 'textbox', 'text', 3)");
197 197
     $dbm->insert('config', " VALUES (31, 0, 2, 'self_delete', '_MD_AM_SELFDELETE', '0', '_MD_AM_SELFDELETEDSC', 'yesno', 'int', 22)");
198 198
     $dbm->insert('config', " VALUES (32, 0, 1, 'com_mode', '_MD_AM_COMMODE', 'flat', '_MD_AM_COMMODEDSC', 'select', 'text', 34)");
199 199
     $dbm->insert('config', " VALUES (33, 0, 1, 'com_order', '_MD_AM_COMORDER', '0', '_MD_AM_COMORDERDSC', 'select', 'int', 36)");
200
-    $dbm->insert('config', " VALUES (34, 0, 2, 'bad_unames', '_MD_AM_BADUNAMES', '" . addslashes(serialize(array(
200
+    $dbm->insert('config', " VALUES (34, 0, 2, 'bad_unames', '_MD_AM_BADUNAMES', '".addslashes(serialize(array(
201 201
                                                                                                                'webmaster',
202 202
                                                                                                                '^xoops',
203
-                                                                                                               '^admin'))) . "', '_MD_AM_BADUNAMESDSC', 'textarea', 'array', 24)");
204
-    $dbm->insert('config', " VALUES (35, 0, 2, 'bad_emails', '_MD_AM_BADEMAILS', '" . addslashes(serialize(array('xoops.org$'))) . "', '_MD_AM_BADEMAILSDSC', 'textarea', 'array', 26)");
203
+                                                                                                               '^admin')))."', '_MD_AM_BADUNAMESDSC', 'textarea', 'array', 24)");
204
+    $dbm->insert('config', " VALUES (35, 0, 2, 'bad_emails', '_MD_AM_BADEMAILS', '".addslashes(serialize(array('xoops.org$')))."', '_MD_AM_BADEMAILSDSC', 'textarea', 'array', 26)");
205 205
     $dbm->insert('config', " VALUES (36, 0, 2, 'maxuname', '_MD_AM_MAXUNAME', '10', '_MD_AM_MAXUNAMEDSC', 'textbox', 'int', 3)");
206
-    $dbm->insert('config', " VALUES (37, 0, 1, 'bad_ips', '_MD_AM_BADIPS', '" . addslashes(serialize(array('127.0.0.1'))) . "', '_MD_AM_BADIPSDSC', 'textarea', 'array', 42)");
206
+    $dbm->insert('config', " VALUES (37, 0, 1, 'bad_ips', '_MD_AM_BADIPS', '".addslashes(serialize(array('127.0.0.1')))."', '_MD_AM_BADIPSDSC', 'textarea', 'array', 42)");
207 207
     $dbm->insert('config', " VALUES (38, 0, 3, 'meta_keywords', '_MD_AM_METAKEY', 'xoops, web application framework, cms, content management system', '_MD_AM_METAKEYDSC', 'textarea', 'text', 0)");
208
-    $dbm->insert('config', " VALUES (39, 0, 3, 'footer', '_MD_AM_FOOTER', 'Powered by XOOPS &#169; 2001-" . date('Y', time()) . " <a href=\"http://xoops.org\" rel=\"external\" title=\"The XOOPS Project\">The XOOPS Project</a>', '_MD_AM_FOOTERDSC', 'textarea', 'text', 20)");
208
+    $dbm->insert('config', " VALUES (39, 0, 3, 'footer', '_MD_AM_FOOTER', 'Powered by XOOPS &#169; 2001-".date('Y', time())." <a href=\"http://xoops.org\" rel=\"external\" title=\"The XOOPS Project\">The XOOPS Project</a>', '_MD_AM_FOOTERDSC', 'textarea', 'text', 20)");
209 209
     $dbm->insert('config', " VALUES (40, 0, 4, 'censor_enable', '_MD_AM_DOCENSOR', '0', '_MD_AM_DOCENSORDSC', 'yesno', 'int', 0)");
210
-    $dbm->insert('config', " VALUES (41, 0, 4, 'censor_words', '_MD_AM_CENSORWRD', '" . addslashes(serialize(array(
210
+    $dbm->insert('config', " VALUES (41, 0, 4, 'censor_words', '_MD_AM_CENSORWRD', '".addslashes(serialize(array(
211 211
                                                                                                                  'fuck',
212
-                                                                                                                 'shit'))) . "', '_MD_AM_CENSORWRDDSC', 'textarea', 'array', 1)");
212
+                                                                                                                 'shit')))."', '_MD_AM_CENSORWRDDSC', 'textarea', 'array', 1)");
213 213
     $dbm->insert('config', " VALUES (42, 0, 4, 'censor_replace', '_MD_AM_CENSORRPLC', '#OOPS#', '_MD_AM_CENSORRPLCDSC', 'textbox', 'text', 2)");
214 214
     $dbm->insert('config', " VALUES (43, 0, 3, 'meta_robots', '_MD_AM_METAROBOTS', 'index,follow', '_MD_AM_METAROBOTSDSC', 'textbox', 'text', 2)");
215 215
     $dbm->insert('config', " VALUES (44, 0, 5, 'enable_search', '_MD_AM_DOSEARCH', '1', '_MD_AM_DOSEARCHDSC', 'yesno', 'int', 0)");
@@ -218,17 +218,17 @@  discard block
 block discarded – undo
218 218
     $dbm->insert('config', " VALUES (47, 0, 1, 'enable_badips', '_MD_AM_DOBADIPS', '0', '_MD_AM_DOBADIPSDSC', 'yesno', 'int', 40)");
219 219
     $dbm->insert('config', " VALUES (48, 0, 3, 'meta_rating', '_MD_AM_METARATING', 'general', '_MD_AM_METARATINGDSC', 'select', 'text', 4)");
220 220
     $dbm->insert('config', " VALUES (49, 0, 3, 'meta_author', '_MD_AM_METAAUTHOR', 'XOOPS', '_MD_AM_METAAUTHORDSC', 'textbox', 'text', 6)");
221
-    $dbm->insert('config', " VALUES (50, 0, 3, 'meta_copyright', '_MD_AM_METACOPYR', 'Copyright &#169; 2001-" . date('Y', time()) . "', '_MD_AM_METACOPYRDSC', 'textbox', 'text', 8)");
221
+    $dbm->insert('config', " VALUES (50, 0, 3, 'meta_copyright', '_MD_AM_METACOPYR', 'Copyright &#169; 2001-".date('Y', time())."', '_MD_AM_METACOPYRDSC', 'textbox', 'text', 8)");
222 222
     $dbm->insert('config', " VALUES (51, 0, 3, 'meta_description', '_MD_AM_METADESC', 'XOOPS is a dynamic Object Oriented based open source portal script written in PHP.', '_MD_AM_METADESCDSC', 'textarea', 'text', 1)");
223 223
     $dbm->insert('config', " VALUES (52, 0, 2, 'allow_chgmail', '_MD_AM_ALLWCHGMAIL', '0', '_MD_AM_ALLWCHGMAILDSC', 'yesno', 'int', 3)");
224 224
     $dbm->insert('config', " VALUES (53, 0, 1, 'use_mysession', '_MD_AM_USEMYSESS', '1', '_MD_AM_USEMYSESSDSC', 'yesno', 'int', 19)");
225 225
     $dbm->insert('config', " VALUES (54, 0, 2, 'reg_dispdsclmr', '_MD_AM_DSPDSCLMR', 1, '_MD_AM_DSPDSCLMRDSC', 'yesno', 'int', 30)");
226
-    $dbm->insert('config', " VALUES (55, 0, 2, 'reg_disclaimer', '_MD_AM_REGDSCLMR', '" . addslashes(_INSTALL_DISCLMR) . "', '_MD_AM_REGDSCLMRDSC', 'textarea', 'text', 32)");
226
+    $dbm->insert('config', " VALUES (55, 0, 2, 'reg_disclaimer', '_MD_AM_REGDSCLMR', '".addslashes(_INSTALL_DISCLMR)."', '_MD_AM_REGDSCLMRDSC', 'textarea', 'text', 32)");
227 227
     $dbm->insert('config', " VALUES (56, 0, 2, 'allow_register', '_MD_AM_ALLOWREG', 1, '_MD_AM_ALLOWREGDSC', 'yesno', 'int', 0)");
228 228
     $dbm->insert('config', " VALUES (57, 0, 1, 'theme_fromfile', '_MD_AM_THEMEFILE', '0', '_MD_AM_THEMEFILEDSC', 'yesno', 'int', 13)");
229 229
     $dbm->insert('config', " VALUES (58, 0, 1, 'closesite', '_MD_AM_CLOSESITE', '0', '_MD_AM_CLOSESITEDSC', 'yesno', 'int', 26)");
230
-    $dbm->insert('config', " VALUES (59, 0, 1, 'closesite_okgrp', '_MD_AM_CLOSESITEOK', '" . addslashes(serialize(array('1'))) . "', '_MD_AM_CLOSESITEOKDSC', 'group_multi', 'array', 27)");
231
-    $dbm->insert('config', " VALUES (60, 0, 1, 'closesite_text', '_MD_AM_CLOSESITETXT', '" . _INSTALL_L165 . "', '_MD_AM_CLOSESITETXTDSC', 'textarea', 'text', 28)");
230
+    $dbm->insert('config', " VALUES (59, 0, 1, 'closesite_okgrp', '_MD_AM_CLOSESITEOK', '".addslashes(serialize(array('1')))."', '_MD_AM_CLOSESITEOKDSC', 'group_multi', 'array', 27)");
231
+    $dbm->insert('config', " VALUES (60, 0, 1, 'closesite_text', '_MD_AM_CLOSESITETXT', '"._INSTALL_L165."', '_MD_AM_CLOSESITETXTDSC', 'textarea', 'text', 28)");
232 232
     $dbm->insert('config', " VALUES (61, 0, 1, 'sslpost_name', '_MD_AM_SSLPOST', 'xoops_ssl', '_MD_AM_SSLPOSTDSC', 'textbox', 'text', 31)");
233 233
     $dbm->insert('config', " VALUES (62, 0, 1, 'module_cache', '_MD_AM_MODCACHE', '', '_MD_AM_MODCACHEDSC', 'module_cache', 'array', 50)");
234 234
     $dbm->insert('config', " VALUES (63, 0, 1, 'template_set', '_MD_AM_DTPLSET', 'default', '_MD_AM_DTPLSETDSC', 'tplset', 'other', 14)");
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
     $dbm->insert('config', " VALUES (69,0,6,'from','_MD_AM_MAILFROM','','_MD_AM_MAILFROMDESC','textbox','text', 1)");
242 242
     $dbm->insert('config', " VALUES (70,0,6,'fromname','_MD_AM_MAILFROMNAME','','_MD_AM_MAILFROMNAMEDESC','textbox','text',2)");
243 243
     $dbm->insert('config', " VALUES (71, 0, 1, 'sslloginlink', '_MD_AM_SSLLINK', 'https://', '_MD_AM_SSLLINKDSC', 'textbox', 'text', 33)");
244
-    $dbm->insert('config', " VALUES (72, 0, 1, 'theme_set_allowed', '_MD_AM_THEMEOK', '" . serialize(array($defaultTheme)) . "', '_MD_AM_THEMEOKDSC', 'theme_multi', 'array', 13)");
244
+    $dbm->insert('config', " VALUES (72, 0, 1, 'theme_set_allowed', '_MD_AM_THEMEOK', '".serialize(array($defaultTheme))."', '_MD_AM_THEMEOKDSC', 'theme_multi', 'array', 13)");
245 245
     // RMV-NOTIFY... Need to specify which user is sender of notification PM
246 246
     $dbm->insert('config', " VALUES (73,0,6,'fromuid','_MD_AM_MAILFROMUID','1','_MD_AM_MAILFROMUIDDESC','user','int',3)");
247 247
 
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
     $dbm->insert('config', " VALUES (78,0,7,'ldap_manager_dn','_MD_AM_LDAP_MANAGER_DN','manager_dn','_MD_AM_LDAP_MANAGER_DN_DESC','textbox','text',5)");
253 253
     $dbm->insert('config', " VALUES (79,0,7,'ldap_manager_pass','_MD_AM_LDAP_MANAGER_PASS','manager_pass','_MD_AM_LDAP_MANAGER_PASS_DESC','password','text',6)");
254 254
     $dbm->insert('config', " VALUES (80,0,7,'ldap_version','_MD_AM_LDAP_VERSION','3','_MD_AM_LDAP_VERSION_DESC','textbox','text', 7)");
255
-    $dbm->insert('config', " VALUES (81,0,7,'ldap_users_bypass','_MD_AM_LDAP_USERS_BYPASS','" . serialize(array('admin')) . "','_MD_AM_LDAP_USERS_BYPASS_DESC','textarea','array',8)");
255
+    $dbm->insert('config', " VALUES (81,0,7,'ldap_users_bypass','_MD_AM_LDAP_USERS_BYPASS','".serialize(array('admin'))."','_MD_AM_LDAP_USERS_BYPASS_DESC','textarea','array',8)");
256 256
     $dbm->insert('config', " VALUES (82,0,7,'ldap_loginname_asdn','_MD_AM_LDAP_LOGINNAME_ASDN','uid_asdn','_MD_AM_LDAP_LOGINNAME_ASDN_D','yesno','int',9)");
257 257
     $dbm->insert('config', " VALUES (83,0,7,'ldap_loginldap_attr', '_MD_AM_LDAP_LOGINLDAP_ATTR', 'uid', '_MD_AM_LDAP_LOGINLDAP_ATTR_D', 'textbox', 'text', 10)");
258 258
     $dbm->insert('config', " VALUES (84,0,7,'ldap_filter_person','_MD_AM_LDAP_FILTER_PERSON','','_MD_AM_LDAP_FILTER_PERSON_DESC','textbox','text',11)");
@@ -314,30 +314,30 @@  discard block
 block discarded – undo
314 314
     $editors = XoopsLists::getDirListAsArray('../class/xoopseditor');
315 315
     $conf    = 35;
316 316
     foreach ($editors as $dir) {
317
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 126)");
317
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 126)");
318 318
         ++$conf;
319 319
     }
320 320
     foreach ($editors as $dir) {
321
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 127)");
321
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 127)");
322 322
         ++$conf;
323 323
     }
324 324
     foreach ($editors as $dir) {
325
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 128)");
325
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 128)");
326 326
         ++$conf;
327 327
     }
328 328
     $icons = XoopsLists::getDirListAsArray('../modules/system/images/icons');
329 329
     foreach ($icons as $dir) {
330
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 98)");
330
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 98)");
331 331
         ++$conf;
332 332
     }
333 333
     $breadcrumb = XoopsLists::getDirListAsArray('../modules/system/images/breadcrumb');
334 334
     foreach ($breadcrumb as $dir) {
335
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 99)");
335
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 99)");
336 336
         ++$conf;
337 337
     }
338 338
     $jqueryui = XoopsLists::getDirListAsArray('../modules/system/css/ui');
339 339
     foreach ($jqueryui as $dir) {
340
-        $dbm->insert('configoption', ' VALUES (' . $conf . ", '" . $dir . "', '" . $dir . "', 133)");
340
+        $dbm->insert('configoption', ' VALUES ('.$conf.", '".$dir."', '".$dir."', 133)");
341 341
         ++$conf;
342 342
     }
343 343
 
Please login to merge, or discard this patch.
htdocs/install/include/config.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@
 block discarded – undo
48 48
     'xml'      => array('XML', sprintf(PHP_EXTENSION, XML_PARSING)),
49 49
     'zlib'     => array('Zlib', sprintf(PHP_EXTENSION, ZLIB_COMPRESSION)),
50 50
     'gd'       => array(
51
-        (function_exists('gd_info') && $gdlib = @gd_info()) ? 'GD ' . $gdlib['GD Version'] : '',
51
+        (function_exists('gd_info') && $gdlib = @gd_info()) ? 'GD '.$gdlib['GD Version'] : '',
52 52
         sprintf(PHP_EXTENSION, IMAGE_FUNCTIONS)),
53 53
     'exif'     => array('Exif', sprintf(PHP_EXTENSION, IMAGE_METAS)),
54 54
     'curl'     => array('Curl', sprintf(PHP_EXTENSION, CURL_HTTP)),
Please login to merge, or discard this patch.
htdocs/install/page_siteinit.php 1 patch
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -31,9 +31,9 @@  discard block
 block discarded – undo
31 31
 $pageHasForm = true;
32 32
 $pageHasHelp = false;
33 33
 
34
-$vars =& $_SESSION['siteconfig'];
34
+$vars = & $_SESSION['siteconfig'];
35 35
 
36
-$error =& $_SESSION['error'];
36
+$error = & $_SESSION['error'];
37 37
 
38 38
 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
39 39
     $vars['adminname']  = trim($_POST['adminname']);
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
         exit();
76 76
     }
77 77
 
78
-    $res = $dbm->query('SELECT COUNT(*) FROM ' . $dbm->db->prefix('users'));
78
+    $res = $dbm->query('SELECT COUNT(*) FROM '.$dbm->db->prefix('users'));
79 79
     list($isadmin) = $dbm->db->fetchRow($res);
80 80
 }
81 81
 
@@ -85,15 +85,15 @@  discard block
 block discarded – undo
85 85
 if ($isadmin) {
86 86
     $pageHasForm = false;
87 87
     $pageHasHelp = false;
88
-    echo "<div class='alert alert-warning'>" . ADMIN_EXIST . "</div>\n";
88
+    echo "<div class='alert alert-warning'>".ADMIN_EXIST."</div>\n";
89 89
 } else {
90 90
         echo '<script type="text/javascript">
91 91
                 var desc = new Array();
92
-                desc[0] = "' . PASSWORD_VERY_WEAK . '";
93
-                desc[1] = "' . PASSWORD_WEAK . '";
94
-                desc[2] = "' . PASSWORD_BETTER . '";
95
-                desc[3] = "' . PASSWORD_MEDIUM . '";
96
-                desc[4] = "' . PASSWORD_STRONG . '";
92
+                desc[0] = "' . PASSWORD_VERY_WEAK.'";
93
+                desc[1] = "' . PASSWORD_WEAK.'";
94
+                desc[2] = "' . PASSWORD_BETTER.'";
95
+                desc[3] = "' . PASSWORD_MEDIUM.'";
96
+                desc[4] = "' . PASSWORD_STRONG.'";
97 97
         </script>';
98 98
 
99 99
     ?>
@@ -106,14 +106,14 @@  discard block
 block discarded – undo
106 106
         echo xoFormField('adminname', $vars['adminname'], ADMIN_LOGIN_LABEL);
107 107
         if (isset($error['name'])) {
108 108
             foreach ($error['name'] as $errmsg) {
109
-                echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> ' . $errmsg . '</div>';
109
+                echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> '.$errmsg.'</div>';
110 110
             }
111 111
         }
112 112
 
113 113
         echo xoFormField('adminmail', $vars['adminmail'], ADMIN_EMAIL_LABEL);
114 114
         if (isset($error['email'])) {
115 115
             foreach ($error['email'] as $errmsg) {
116
-                echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> ' . $errmsg . '</div>';
116
+                echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> '.$errmsg.'</div>';
117 117
             }
118 118
         }
119 119
         ?>
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
                 echo xoPassField('adminpass2', '', ADMIN_CONFIRMPASS_LABEL);
126 126
                 if (isset($error['pass'])) {
127 127
                     foreach ($error['pass'] as $errmsg) {
128
-                        echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> ' . $errmsg . '</div>';
128
+                        echo '<div class="alert alert-danger"><span class="fa fa-ban text-danger"></span> '.$errmsg.'</div>';
129 129
                     }
130 130
                 }
131 131
                 ?>
Please login to merge, or discard this patch.
upgrade/upd-2.5.9-to-2.5.10/index.php 1 patch
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
             $row = $db->fetchRow($result);
51 51
             if ($row) {
52 52
                 $count = $row[0];
53
-                return (0 === (int) $count) ? true : false;
53
+                return (0 === (int)$count) ? true : false;
54 54
             }
55 55
         }
56 56
         return false;
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
      */
82 82
     public function check_protectordata()
83 83
     {
84
-        $destinationPath = XOOPS_VAR_PATH . '/protector/';
84
+        $destinationPath = XOOPS_VAR_PATH.'/protector/';
85 85
         return file_exists($destinationPath);
86 86
     }
87 87
 
@@ -93,8 +93,8 @@  discard block
 block discarded – undo
93 93
     public function apply_protectordata()
94 94
     {
95 95
         $returnResult = false;
96
-        $sourcePath = XOOPS_PATH . '/modules/protector/configs/';
97
-        $destinationPath = XOOPS_VAR_PATH . '/protector/';
96
+        $sourcePath = XOOPS_PATH.'/modules/protector/configs/';
97
+        $destinationPath = XOOPS_VAR_PATH.'/protector/';
98 98
 
99 99
         if (!file_exists($destinationPath)) {
100 100
             mkdir($destinationPath);
@@ -104,8 +104,8 @@  discard block
 block discarded – undo
104 104
             $returnResult = true;
105 105
             while (false !== ($entry = $directory->read())) {
106 106
                 if ('.' !== $entry && '..' !== $entry) {
107
-                    $src = $sourcePath . $entry;
108
-                    $dest = $destinationPath . $entry;
107
+                    $src = $sourcePath.$entry;
108
+                    $dest = $destinationPath.$entry;
109 109
                     $result = copy($src, $dest);
110 110
                     if (false === $result) {
111 111
                         $returnResult = false;
Please login to merge, or discard this patch.