Completed
Push — master ( 32a238...9b1100 )
by Mikael
03:28 queued 48s
created

img.php ➔ verbose()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 4
eloc 8
c 1
b 1
f 1
nc 3
nop 1
dl 0
loc 15
rs 9.2
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 25 and the first side effect is on line 15.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Resize and crop images on the fly, store generated images in a cache.
4
 *
5
 * @author  Mikael Roos [email protected]
6
 * @example http://dbwebb.se/opensource/cimage
7
 * @link    https://github.com/mosbth/cimage
8
 *
9
 */
10
11
/**
12
 * Get configuration options from file, if the file exists, else use $config
13
 * if its defined or create an empty $config.
14
 */
15
$configFile = __DIR__.'/'.basename(__FILE__, '.php').'_config.php';
16
17
if (is_file($configFile)) {
18
    $config = require $configFile;
19
} elseif (!isset($config)) {
20
    $config = array();
21
}
22
23
// Make CIMAGE_DEBUG false by default, if not already defined
24
if (!defined("CIMAGE_DEBUG")) {
25
    define("CIMAGE_DEBUG", false);
26
}
27
28
29
30
/**
31
 * Setup the autoloader, but not when using a bundle.
32
 */
33
if (!defined("CIMAGE_BUNDLE")) {
34
    if (!isset($config["autoloader"])) {
35
        die("CImage: Missing autoloader.");
36
    }
37
38
    require $config["autoloader"];
39
}
40
41
42
43
/**
44
* verbose, v - do a verbose dump of what happens
45
* vf - do verbose dump to file
46
*/
47
$verbose = getDefined(array('verbose', 'v'), true, false);
48
$verboseFile = getDefined('vf', true, false);
49
verbose("img.php version = " . CIMAGE_VERSION);
50
51
52
53
/**
54
* status - do a verbose dump of the configuration
55
*/
56
$status = getDefined('status', true, false);
57
58
59
60
/**
61
 * Set mode as strict, production or development.
62
 * Default is production environment.
63
 */
64
$mode = getConfig('mode', 'production');
65
66
// Settings for any mode
67
set_time_limit(20);
68
ini_set('gd.jpeg_ignore_warning', 1);
69
70
if (!extension_loaded('gd')) {
71
    errorPage("Extension gd is not loaded.", 500);
72
}
73
74
// Specific settings for each mode
75
if ($mode == 'strict') {
76
77
    error_reporting(0);
78
    ini_set('display_errors', 0);
79
    ini_set('log_errors', 1);
80
    $verbose = false;
81
    $status = false;
82
    $verboseFile = false;
83
84
} elseif ($mode == 'production') {
85
86
    error_reporting(-1);
87
    ini_set('display_errors', 0);
88
    ini_set('log_errors', 1);
89
    $verbose = false;
90
    $status = false;
91
    $verboseFile = false;
92
93
} elseif ($mode == 'development') {
94
95
    error_reporting(-1);
96
    ini_set('display_errors', 1);
97
    ini_set('log_errors', 0);
98
    $verboseFile = false;
99
100
} elseif ($mode == 'test') {
101
102
    error_reporting(-1);
103
    ini_set('display_errors', 1);
104
    ini_set('log_errors', 0);
105
106
} else {
107
    errorPage("Unknown mode: $mode", 500);
108
}
109
110
verbose("mode = $mode");
111
verbose("error log = " . ini_get('error_log'));
112
113
114
115
/**
116
 * Set default timezone if not set or if its set in the config-file.
117
 */
118
$defaultTimezone = getConfig('default_timezone', null);
119
120
if ($defaultTimezone) {
121
    date_default_timezone_set($defaultTimezone);
122
} elseif (!ini_get('default_timezone')) {
123
    date_default_timezone_set('UTC');
124
}
125
126
127
128
/**
129
 * Check if passwords are configured, used and match.
130
 * Options decide themself if they require passwords to be used.
131
 */
132
$pwdConfig   = getConfig('password', false);
133
$pwdAlways   = getConfig('password_always', false);
134
$pwdType     = getConfig('password_type', 'text');
135
$pwd         = get(array('password', 'pwd'), null);
136
137
// Check if passwords match, if configured to use passwords
138
$passwordMatch = null;
139
if ($pwd) {
140
    switch ($pwdType) {
141
        case 'md5':
142
            $passwordMatch = ($pwdConfig === md5($pwd));
143
            break;
144
        case 'hash':
145
            $passwordMatch = password_verify($pwd, $pwdConfig);
146
            break;
147
        case 'text':
148
            $passwordMatch = ($pwdConfig === $pwd);
149
            break;
150
        default:
151
            $passwordMatch = false;
152
    }
153
}
154
155
if ($pwdAlways && $passwordMatch !== true) {
156
    errorPage("Password required and does not match or exists.", 403);
157
}
158
159
verbose("password match = $passwordMatch");
160
161
162
163
/**
164
 * Prevent hotlinking, leeching, of images by controlling who access them
165
 * from where.
166
 *
167
 */
168
$allowHotlinking = getConfig('allow_hotlinking', true);
169
$hotlinkingWhitelist = getConfig('hotlinking_whitelist', array());
170
171
$serverName  = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
172
$referer     = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
173
$refererHost = parse_url($referer, PHP_URL_HOST);
174
175
if (!$allowHotlinking) {
176
    if ($passwordMatch) {
177
        ; // Always allow when password match
178
        verbose("Hotlinking since passwordmatch");
179
    } elseif ($passwordMatch === false) {
180
        errorPage("Hotlinking/leeching not allowed when password missmatch.", 403);
181
    } elseif (!$referer) {
182
        errorPage("Hotlinking/leeching not allowed and referer is missing.", 403);
183
    } elseif (strcmp($serverName, $refererHost) == 0) {
184
        ; // Allow when serverName matches refererHost
185
        verbose("Hotlinking disallowed but serverName matches refererHost.");
186
    } elseif (!empty($hotlinkingWhitelist)) {
187
        $whitelist = new CWhitelist();
188
        $allowedByWhitelist = $whitelist->check($refererHost, $hotlinkingWhitelist);
0 ignored issues
show
Security Bug introduced by
It seems like $refererHost defined by parse_url($referer, PHP_URL_HOST) on line 173 can also be of type false; however, CWhitelist::check() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
189
190
        if ($allowedByWhitelist) {
191
            verbose("Hotlinking/leeching allowed by whitelist.");
192
        } else {
193
            errorPage("Hotlinking/leeching not allowed by whitelist. Referer: $referer.", 403);
194
        }
195
196
    } else {
197
        errorPage("Hotlinking/leeching not allowed.", 403);
198
    }
199
}
200
201
verbose("allow_hotlinking = $allowHotlinking");
202
verbose("referer = $referer");
203
verbose("referer host = $refererHost");
204
205
206
207
/**
208
 * Create the class for the image.
209
 */
210
$CImage = getConfig('CImage', 'CImage');
211
$img = new $CImage();
212
$img->setVerbose($verbose || $verboseFile);
213
214
215
216
/**
217
 * Get the cachepath from config.
218
 */
219
$CCache = getConfig('CCache', 'CCache');
220
$cachePath = getConfig('cache_path', __DIR__ . '/../cache/');
221
$cache = new $CCache();
222
$cache->setDir($cachePath);
223
224
225
226
/**
227
 * no-cache, nc - skip the cached version and process and create a new version in cache.
228
 */
229
$useCache = getDefined(array('no-cache', 'nc'), false, true);
230
231
verbose("use cache = $useCache");
232
233
234
235
/**
236
 * Prepare fast track cache for swriting cache items.
237
 */
238
$fastTrackCache = "fasttrack";
239
$allowFastTrackCache = getConfig('fast_track_allow', false);
240
241
$CFastTrackCache = getConfig('CFastTrackCache', 'CFastTrackCache');
242
$ftc = new $CFastTrackCache();
243
$ftc->setCacheDir($cache->getPathToSubdir($fastTrackCache))
244
    ->enable($allowFastTrackCache)
245
    ->setFilename(array('no-cache', 'nc'));
246
$img->injectDependency("fastTrackCache", $ftc);
247
248
249
250
/**
251
 *  Load and output images from fast track cache, if items are available
252
 * in cache.
253
 */
254
if ($useCache && $allowFastTrackCache) {
255
    if (CIMAGE_DEBUG) {
256
        trace("img.php fast track cache enabled and used");
257
    }
258
    $ftc->output();
259
}
260
261
262
263
/**
264
 * Allow or disallow remote download of images from other servers.
265
 * Passwords apply if used.
266
 *
267
 */
268
$allowRemote = getConfig('remote_allow', false);
269
270
if ($allowRemote && $passwordMatch !== false) {
271
    $cacheRemote = $cache->getPathToSubdir("remote");
272
    
273
    $pattern = getConfig('remote_pattern', null);
274
    $img->setRemoteDownload($allowRemote, $cacheRemote, $pattern);
275
276
    $whitelist = getConfig('remote_whitelist', null);
277
    $img->setRemoteHostWhitelist($whitelist);
278
}
279
280
281
282
/**
283
 * shortcut, sc - extend arguments with a constant value, defined
284
 * in config-file.
285
 */
286
$shortcut       = get(array('shortcut', 'sc'), null);
287
$shortcutConfig = getConfig('shortcut', array(
288
    'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
289
));
290
291
verbose("shortcut = $shortcut");
292
293
if (isset($shortcut)
294
    && isset($shortcutConfig[$shortcut])) {
295
296
    parse_str($shortcutConfig[$shortcut], $get);
297
    verbose("shortcut-constant = {$shortcutConfig[$shortcut]}");
298
    $_GET = array_merge($_GET, $get);
299
}
300
301
302
303
/**
304
 * src - the source image file.
305
 */
306
$srcImage = urldecode(get('src'))
307
    or errorPage('Must set src-attribute.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
308
309
// Get settings for src-alt as backup image
310
$srcAltImage = urldecode(get('src-alt', null));
311
$srcAltConfig = getConfig('src_alt', null);
312
if (empty($srcAltImage)) {
313
    $srcAltImage = $srcAltConfig;
314
}
315
316
// Check for valid/invalid characters
317
$imagePath           = getConfig('image_path', __DIR__ . '/img/');
318
$imagePathConstraint = getConfig('image_path_constraint', true);
319
$validFilename       = getConfig('valid_filename', '#^[a-z0-9A-Z-/_ \.:]+$#');
320
321
// Source is remote
322
$remoteSource = false;
323
324
// Dummy image feature
325
$dummyEnabled  = getConfig('dummy_enabled', true);
326
$dummyFilename = getConfig('dummy_filename', 'dummy');
327
$dummyImage = false;
328
329
preg_match($validFilename, $srcImage)
330
    or errorPage('Source filename contains invalid characters.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
331
332
if ($dummyEnabled && $srcImage === $dummyFilename) {
333
334
    // Prepare to create a dummy image and use it as the source image.
335
    $dummyImage = true;
336
337
} elseif ($allowRemote && $img->isRemoteSource($srcImage)) {
338
339
    // If source is a remote file, ignore local file checks.
340
    $remoteSource = true;
341
342
} else {
343
344
    // Check if file exists on disk or try using src-alt
345
    $pathToImage = realpath($imagePath . $srcImage);
346
347
    if (!is_file($pathToImage) && !empty($srcAltImage)) {
348
        // Try using the src-alt instead
349
        $srcImage = $srcAltImage;
350
        $pathToImage = realpath($imagePath . $srcImage);
351
352
        preg_match($validFilename, $srcImage)
353
            or errorPage('Source (alt) filename contains invalid characters.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
354
355
        if ($dummyEnabled && $srcImage === $dummyFilename) {
356
            // Check if src-alt is the dummy image
357
            $dummyImage = true;
358
        }
359
    }
360
361
    if (!$dummyImage) {
362
        is_file($pathToImage)
363
            or errorPage(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
364
                'Source image is not a valid file, check the filename and that a
365
                matching file exists on the filesystem.',
366
                404
367
            );
368
    } 
369
}
370
371
if ($imagePathConstraint && !$dummyImage && !$remoteSource) {
372
    // Check that the image is a file below the directory 'image_path'.
373
    $imageDir = realpath($imagePath);
374
375
    substr_compare($imageDir, $pathToImage, 0, strlen($imageDir)) == 0
376
        or errorPage(
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
377
            'Security constraint: Source image is not below the directory "image_path"
378
            as specified in the config file img_config.php.',
379
            404
380
        );
381
}
382
383
verbose("src = $srcImage");
384
385
386
387
/**
388
 * Manage size constants from config file, use constants to replace values
389
 * for width and height.
390
 */
391
$sizeConstant = getConfig('size_constant', function () {
392
393
    // Set sizes to map constant to value, easier to use with width or height
394
    $sizes = array(
395
        'w1' => 613,
396
        'w2' => 630,
397
    );
398
399
    // Add grid column width, useful for use as predefined size for width (or height).
400
    $gridColumnWidth = 30;
401
    $gridGutterWidth = 10;
402
    $gridColumns     = 24;
403
404
    for ($i = 1; $i <= $gridColumns; $i++) {
405
        $sizes['c' . $i] = ($gridColumnWidth + $gridGutterWidth) * $i - $gridGutterWidth;
406
    }
407
408
    return $sizes;
409
});
410
411
$sizes = call_user_func($sizeConstant);
412
413
414
415
/**
416
 * width, w - set target width, affecting the resulting image width, height and resize options
417
 */
418
$newWidth     = get(array('width', 'w'));
419
$maxWidth     = getConfig('max_width', 2000);
420
421
// Check to replace predefined size
422
if (isset($sizes[$newWidth])) {
423
    $newWidth = $sizes[$newWidth];
424
}
425
426
// Support width as % of original width
427
if ($newWidth[strlen($newWidth)-1] == '%') {
428
    is_numeric(substr($newWidth, 0, -1))
429
        or errorPage('Width % not numeric.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
430
} else {
431
    is_null($newWidth)
432
        or ($newWidth > 10 && $newWidth <= $maxWidth)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
433
        or errorPage('Width out of range.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
434
}
435
436
verbose("new width = $newWidth");
437
438
439
440
/**
441
 * height, h - set target height, affecting the resulting image width, height and resize options
442
 */
443
$newHeight = get(array('height', 'h'));
444
$maxHeight = getConfig('max_height', 2000);
445
446
// Check to replace predefined size
447
if (isset($sizes[$newHeight])) {
448
    $newHeight = $sizes[$newHeight];
449
}
450
451
// height
452
if ($newHeight[strlen($newHeight)-1] == '%') {
453
    is_numeric(substr($newHeight, 0, -1))
454
        or errorPage('Height % out of range.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
455
} else {
456
    is_null($newHeight)
457
        or ($newHeight > 10 && $newHeight <= $maxHeight)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
458
        or errorPage('Height out of range.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
459
}
460
461
verbose("new height = $newHeight");
462
463
464
465
/**
466
 * aspect-ratio, ar - affecting the resulting image width, height and resize options
467
 */
468
$aspectRatio         = get(array('aspect-ratio', 'ar'));
469
$aspectRatioConstant = getConfig('aspect_ratio_constant', function () {
470
    return array(
471
        '3:1'    => 3/1,
472
        '3:2'    => 3/2,
473
        '4:3'    => 4/3,
474
        '8:5'    => 8/5,
475
        '16:10'  => 16/10,
476
        '16:9'   => 16/9,
477
        'golden' => 1.618,
478
    );
479
});
480
481
// Check to replace predefined aspect ratio
482
$aspectRatios = call_user_func($aspectRatioConstant);
483
$negateAspectRatio = ($aspectRatio[0] == '!') ? true : false;
484
$aspectRatio = $negateAspectRatio ? substr($aspectRatio, 1) : $aspectRatio;
485
486
if (isset($aspectRatios[$aspectRatio])) {
487
    $aspectRatio = $aspectRatios[$aspectRatio];
488
}
489
490
if ($negateAspectRatio) {
491
    $aspectRatio = 1 / $aspectRatio;
492
}
493
494
is_null($aspectRatio)
495
    or is_numeric($aspectRatio)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
496
    or errorPage('Aspect ratio out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
497
498
verbose("aspect ratio = $aspectRatio");
499
500
501
502
/**
503
 * crop-to-fit, cf - affecting the resulting image width, height and resize options
504
 */
505
$cropToFit = getDefined(array('crop-to-fit', 'cf'), true, false);
506
507
verbose("crop to fit = $cropToFit");
508
509
510
511
/**
512
 * Set default background color from config file.
513
 */
514
$backgroundColor = getConfig('background_color', null);
515
516
if ($backgroundColor) {
517
    $img->setDefaultBackgroundColor($backgroundColor);
518
    verbose("Using default background_color = $backgroundColor");
519
}
520
521
522
523
/**
524
 * bgColor - Default background color to use
525
 */
526
$bgColor = get(array('bgColor', 'bg-color', 'bgc'), null);
527
528
verbose("bgColor = $bgColor");
529
530
531
532
/**
533
 * Do or do not resample image when resizing.
534
 */
535
$resizeStrategy = getDefined(array('no-resample'), true, false);
536
537
if ($resizeStrategy) {
538
    $img->setCopyResizeStrategy($img::RESIZE);
539
    verbose("Setting = Resize instead of resample");
540
}
541
542
543
544
545
/**
546
 * fill-to-fit, ff - affecting the resulting image width, height and resize options
547
 */
548
$fillToFit = get(array('fill-to-fit', 'ff'), null);
549
550
verbose("fill-to-fit = $fillToFit");
551
552
if ($fillToFit !== null) {
553
554
    if (!empty($fillToFit)) {
555
        $bgColor   = $fillToFit;
556
        verbose("fillToFit changed bgColor to = $bgColor");
557
    }
558
559
    $fillToFit = true;
560
    verbose("fill-to-fit (fixed) = $fillToFit");
561
}
562
563
564
565
/**
566
 * no-ratio, nr, stretch - affecting the resulting image width, height and resize options
567
 */
568
$keepRatio = getDefined(array('no-ratio', 'nr', 'stretch'), false, true);
569
570
verbose("keep ratio = $keepRatio");
571
572
573
574
/**
575
 * crop, c - affecting the resulting image width, height and resize options
576
 */
577
$crop = get(array('crop', 'c'));
578
579
verbose("crop = $crop");
580
581
582
583
/**
584
 * area, a - affecting the resulting image width, height and resize options
585
 */
586
$area = get(array('area', 'a'));
587
588
verbose("area = $area");
589
590
591
592
/**
593
 * skip-original, so - skip the original image and always process a new image
594
 */
595
$useOriginal = getDefined(array('skip-original', 'so'), false, true);
596
$useOriginalDefault = getConfig('skip_original', false);
597
598
if ($useOriginalDefault === true) {
599
    verbose("skip original is default ON");
600
    $useOriginal = false;
601
}
602
603
verbose("use original = $useOriginal");
604
605
606
607
/**
608
 * quality, q - set level of quality for jpeg images
609
 */
610
$quality = get(array('quality', 'q'));
611
$qualityDefault = getConfig('jpg_quality', null);
612
613
is_null($quality)
614
    or ($quality > 0 and $quality <= 100)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
615
    or errorPage('Quality out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
616
617
if (is_null($quality) && !is_null($qualityDefault)) {
618
    $quality = $qualityDefault;
619
}
620
621
verbose("quality = $quality");
622
623
624
625
/**
626
 * compress, co - what strategy to use when compressing png images
627
 */
628
$compress = get(array('compress', 'co'));
629
$compressDefault = getConfig('png_compression', null);
630
631
is_null($compress)
632
    or ($compress > 0 and $compress <= 9)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
633
    or errorPage('Compress out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
634
635
if (is_null($compress) && !is_null($compressDefault)) {
636
    $compress = $compressDefault;
637
}
638
639
verbose("compress = $compress");
640
641
642
643
/**
644
 * save-as, sa - what type of image to save
645
 */
646
$saveAs = get(array('save-as', 'sa'));
647
648
verbose("save as = $saveAs");
649
650
651
652
/**
653
 * scale, s - Processing option, scale up or down the image prior actual resize
654
 */
655
$scale = get(array('scale', 's'));
656
657
is_null($scale)
658
    or ($scale >= 0 and $scale <= 400)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
659
    or errorPage('Scale out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
660
661
verbose("scale = $scale");
662
663
664
665
/**
666
 * palette, p - Processing option, create a palette version of the image
667
 */
668
$palette = getDefined(array('palette', 'p'), true, false);
669
670
verbose("palette = $palette");
671
672
673
674
/**
675
 * sharpen - Processing option, post filter for sharpen effect
676
 */
677
$sharpen = getDefined('sharpen', true, null);
678
679
verbose("sharpen = $sharpen");
680
681
682
683
/**
684
 * emboss - Processing option, post filter for emboss effect
685
 */
686
$emboss = getDefined('emboss', true, null);
687
688
verbose("emboss = $emboss");
689
690
691
692
/**
693
 * blur - Processing option, post filter for blur effect
694
 */
695
$blur = getDefined('blur', true, null);
696
697
verbose("blur = $blur");
698
699
700
701
/**
702
 * rotateBefore - Rotate the image with an angle, before processing
703
 */
704
$rotateBefore = get(array('rotateBefore', 'rotate-before', 'rb'));
705
706
is_null($rotateBefore)
707
    or ($rotateBefore >= -360 and $rotateBefore <= 360)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
708
    or errorPage('RotateBefore out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
709
710
verbose("rotateBefore = $rotateBefore");
711
712
713
714
/**
715
 * rotateAfter - Rotate the image with an angle, before processing
716
 */
717
$rotateAfter = get(array('rotateAfter', 'rotate-after', 'ra', 'rotate', 'r'));
718
719
is_null($rotateAfter)
720
    or ($rotateAfter >= -360 and $rotateAfter <= 360)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
721
    or errorPage('RotateBefore out of range', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
722
723
verbose("rotateAfter = $rotateAfter");
724
725
726
727
/**
728
 * autoRotate - Auto rotate based on EXIF information
729
 */
730
$autoRotate = getDefined(array('autoRotate', 'auto-rotate', 'aro'), true, false);
731
732
verbose("autoRotate = $autoRotate");
733
734
735
736
/**
737
 * filter, f, f0-f9 - Processing option, post filter for various effects using imagefilter()
738
 */
739
$filters = array();
740
$filter = get(array('filter', 'f'));
741
if ($filter) {
742
    $filters[] = $filter;
743
}
744
745
for ($i = 0; $i < 10; $i++) {
746
    $filter = get(array("filter{$i}", "f{$i}"));
747
    if ($filter) {
748
        $filters[] = $filter;
749
    }
750
}
751
752
verbose("filters = " . print_r($filters, 1));
753
754
755
756
/**
757
* json -  output the image as a JSON object with details on the image.
758
* ascii - output the image as ASCII art.
759
 */
760
$outputFormat = getDefined('json', 'json', null);
761
$outputFormat = getDefined('ascii', 'ascii', $outputFormat);
762
763
verbose("outputformat = $outputFormat");
764
765
if ($outputFormat == 'ascii') {
766
    $defaultOptions = getConfig(
767
        'ascii-options',
768
        array(
769
            "characterSet" => 'two',
770
            "scale" => 14,
771
            "luminanceStrategy" => 3,
772
            "customCharacterSet" => null,
773
        )
774
    );
775
    $options = get('ascii');
776
    $options = explode(',', $options);
777
778
    if (isset($options[0]) && !empty($options[0])) {
779
        $defaultOptions['characterSet'] = $options[0];
780
    }
781
782
    if (isset($options[1]) && !empty($options[1])) {
783
        $defaultOptions['scale'] = $options[1];
784
    }
785
786
    if (isset($options[2]) && !empty($options[2])) {
787
        $defaultOptions['luminanceStrategy'] = $options[2];
788
    }
789
790
    if (count($options) > 3) {
791
        // Last option is custom character string
792
        unset($options[0]);
793
        unset($options[1]);
794
        unset($options[2]);
795
        $characterString = implode($options);
796
        $defaultOptions['customCharacterSet'] = $characterString;
797
    }
798
799
    $img->setAsciiOptions($defaultOptions);
800
}
801
802
803
804
805
/**
806
 * dpr - change to get larger image to easier support larger dpr, such as retina.
807
 */
808
$dpr = get(array('ppi', 'dpr', 'device-pixel-ratio'), 1);
809
810
verbose("dpr = $dpr");
811
812
813
814
/**
815
 * convolve - image convolution as in http://php.net/manual/en/function.imageconvolution.php
816
 */
817
$convolve = get('convolve', null);
818
$convolutionConstant = getConfig('convolution_constant', array());
819
820
// Check if the convolve is matching an existing constant
821
if ($convolve && isset($convolutionConstant)) {
822
    $img->addConvolveExpressions($convolutionConstant);
823
    verbose("convolve constant = " . print_r($convolutionConstant, 1));
824
}
825
826
verbose("convolve = " . print_r($convolve, 1));
827
828
829
830
/**
831
 * no-upscale, nu - Do not upscale smaller image to larger dimension.
832
 */
833
$upscale = getDefined(array('no-upscale', 'nu'), false, true);
834
835
verbose("upscale = $upscale");
836
837
838
839
/**
840
 * Get details for post processing
841
 */
842
$postProcessing = getConfig('postprocessing', array(
843
    'png_filter'        => false,
844
    'png_filter_cmd'    => '/usr/local/bin/optipng -q',
845
846
    'png_deflate'       => false,
847
    'png_deflate_cmd'   => '/usr/local/bin/pngout -q',
848
849
    'jpeg_optimize'     => false,
850
    'jpeg_optimize_cmd' => '/usr/local/bin/jpegtran -copy none -optimize',
851
));
852
853
854
855
/**
856
 * alias - Save resulting image to another alias name.
857
 * Password always apply, must be defined.
858
 */
859
$alias          = get('alias', null);
860
$aliasPath      = getConfig('alias_path', null);
861
$validAliasname = getConfig('valid_aliasname', '#^[a-z0-9A-Z-_]+$#');
862
$aliasTarget    = null;
863
864
if ($alias && $aliasPath && $passwordMatch) {
865
866
    $aliasTarget = $aliasPath . $alias;
867
    $useCache    = false;
868
869
    is_writable($aliasPath)
870
        or errorPage("Directory for alias is not writable.", 403);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
871
872
    preg_match($validAliasname, $alias)
873
        or errorPage('Filename for alias contains invalid characters. Do not add extension.', 404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
874
875
} elseif ($alias) {
876
    errorPage('Alias is not enabled in the config file or password not matching.', 403);
877
}
878
879
verbose("alias = $alias");
880
881
882
883
/**
884
 * Add cache control HTTP header.
885
 */
886
$cacheControl = getConfig('cache_control', null);
887
888
if ($cacheControl) {
889
    verbose("cacheControl = $cacheControl");
890
    $img->addHTTPHeader("Cache-Control", $cacheControl);
891
}
892
893
894
895
/**
896
 * Prepare a dummy image and use it as source image.
897
 */
898
if ($dummyImage === true) {
899
    $dummyDir = $cache->getPathToSubdir("dummy");
900
901
    $img->setSaveFolder($dummyDir)
902
        ->setSource($dummyFilename, $dummyDir)
903
        ->setOptions(
904
            array(
905
                'newWidth'  => $newWidth,
906
                'newHeight' => $newHeight,
907
                'bgColor'   => $bgColor,
908
            )
909
        )
910
        ->setJpegQuality($quality)
911
        ->setPngCompression($compress)
912
        ->createDummyImage()
913
        ->generateFilename(null, false)
914
        ->save(null, null, false);
915
916
    $srcImage = $img->getTarget();
917
    $imagePath = null;
918
919
    verbose("src (updated) = $srcImage");
920
}
921
922
923
924
/**
925
 * Prepare a sRGB version of the image and use it as source image.
926
 */
927
$srgbDefault = getConfig('srgb_default', false);
928
$srgbColorProfile = getConfig('srgb_colorprofile', __DIR__ . '/../icc/sRGB_IEC61966-2-1_black_scaled.icc');
929
$srgb = getDefined('srgb', true, null);
930
931
if ($srgb || $srgbDefault) {
932
933
    $filename = $img->convert2sRGBColorSpace(
934
        $srcImage,
935
        $imagePath,
936
        $cache->getPathToSubdir("srgb"),
937
        $srgbColorProfile,
938
        $useCache
939
    );
940
941
    if ($filename) {
942
        $srcImage = $img->getTarget();
943
        $imagePath = null;
944
        verbose("srgb conversion and saved to cache = $srcImage");
945
    } else {
946
        verbose("srgb not op");
947
    }
948
}
949
950
951
952
/**
953
 * Display status
954
 */
955
if ($status) {
956
    $text  = "img.php version = " . CIMAGE_VERSION . "\n";
957
    $text .= "PHP version = " . PHP_VERSION . "\n";
958
    $text .= "Running on: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
959
    $text .= "Allow remote images = $allowRemote\n";
960
961
    $res = $cache->getStatusOfSubdir("");
962
    $text .= "Cache $res\n";
963
964
    $res = $cache->getStatusOfSubdir("remote");
965
    $text .= "Cache remote $res\n";
966
967
    $res = $cache->getStatusOfSubdir("dummy");
968
    $text .= "Cache dummy $res\n";
969
970
    $res = $cache->getStatusOfSubdir("srgb");
971
    $text .= "Cache srgb $res\n";
972
973
    $res = $cache->getStatusOfSubdir($fasttrackCache);
974
    $text .= "Cache fasttrack $res\n";
975
976
    $text .= "Alias path writable = " . is_writable($aliasPath) . "\n";
977
978
    $no = extension_loaded('exif') ? null : 'NOT';
979
    $text .= "Extension exif is $no loaded.<br>";
980
981
    $no = extension_loaded('curl') ? null : 'NOT';
982
    $text .= "Extension curl is $no loaded.<br>";
983
984
    $no = extension_loaded('imagick') ? null : 'NOT';
985
    $text .= "Extension imagick is $no loaded.<br>";
986
987
    $no = extension_loaded('gd') ? null : 'NOT';
988
    $text .= "Extension gd is $no loaded.<br>";
989
990
    if (!$no) {
991
        $text .= print_r(gd_info(), 1);
992
    }
993
994
    echo <<<EOD
995
<!doctype html>
996
<html lang=en>
997
<meta charset=utf-8>
998
<title>CImage status</title>
999
<pre>$text</pre>
1000
EOD;
1001
    exit;
1002
}
1003
1004
1005
1006
/**
1007
 * Log verbose details to file
1008
 */
1009
if ($verboseFile) {
1010
    $img->setVerboseToFile("$cachePath/log.txt");
1011
}
1012
1013
1014
1015
/**
1016
 * Hook after img.php configuration and before processing with CImage
1017
 */
1018
$hookBeforeCImage = getConfig('hook_before_CImage', null);
1019
1020
if (is_callable($hookBeforeCImage)) {
1021
    verbose("hookBeforeCImage activated");
1022
1023
    $allConfig = $hookBeforeCImage($img, array(
1024
            // Options for calculate dimensions
1025
            'newWidth'  => $newWidth,
1026
            'newHeight' => $newHeight,
1027
            'aspectRatio' => $aspectRatio,
1028
            'keepRatio' => $keepRatio,
1029
            'cropToFit' => $cropToFit,
1030
            'fillToFit' => $fillToFit,
1031
            'crop'      => $crop,
1032
            'area'      => $area,
1033
            'upscale'   => $upscale,
1034
1035
            // Pre-processing, before resizing is done
1036
            'scale'        => $scale,
1037
            'rotateBefore' => $rotateBefore,
1038
            'autoRotate'   => $autoRotate,
1039
1040
            // General processing options
1041
            'bgColor'    => $bgColor,
1042
1043
            // Post-processing, after resizing is done
1044
            'palette'   => $palette,
1045
            'filters'   => $filters,
1046
            'sharpen'   => $sharpen,
1047
            'emboss'    => $emboss,
1048
            'blur'      => $blur,
1049
            'convolve'  => $convolve,
1050
            'rotateAfter' => $rotateAfter,
1051
1052
            // Output format
1053
            'outputFormat' => $outputFormat,
1054
            'dpr'          => $dpr,
1055
1056
            // Other
1057
            'postProcessing' => $postProcessing,
1058
    ));
1059
    verbose(print_r($allConfig, 1));
1060
    extract($allConfig);
1061
}
1062
1063
1064
1065
/**
1066
 * Display image if verbose mode
1067
 */
1068
if ($verbose) {
1069
    $query = array();
1070
    parse_str($_SERVER['QUERY_STRING'], $query);
1071
    unset($query['verbose']);
1072
    unset($query['v']);
1073
    unset($query['nocache']);
1074
    unset($query['nc']);
1075
    unset($query['json']);
1076
    $url1 = '?' . htmlentities(urldecode(http_build_query($query)));
1077
    $url2 = '?' . urldecode(http_build_query($query));
1078
    echo <<<EOD
1079
<!doctype html>
1080
<html lang=en>
1081
<meta charset=utf-8>
1082
<title>CImage verbose output</title>
1083
<style>body{background-color: #ddd}</style>
1084
<a href=$url1><code>$url1</code></a><br>
1085
<img src='{$url1}' />
1086
<pre id="json"></pre>
1087
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
1088
<script type="text/javascript">
1089
window.getDetails = function (url, id) {
1090
  $.getJSON(url, function(data) {
1091
    element = document.getElementById(id);
1092
    element.innerHTML = "filename: " + data.filename + "\\nmime type: " + data.mimeType + "\\ncolors: " + data.colors + "\\nsize: " + data.size + "\\nwidth: " + data.width + "\\nheigh: " + data.height + "\\naspect-ratio: " + data.aspectRatio + ( data.pngType ? "\\npng-type: " + data.pngType : '');
1093
  });
1094
}
1095
</script>
1096
<script type="text/javascript">window.getDetails("{$url2}&json", "json")</script>
1097
EOD;
1098
}
1099
1100
1101
1102
/**
1103
 * Load, process and output the image
1104
 */
1105
$img->log("Incoming arguments: " . print_r(verbose(), 1))
1106
    ->setSaveFolder($cachePath)
1107
    ->useCache($useCache)
1108
    ->setSource($srcImage, $imagePath)
1109
    ->setOptions(
1110
        array(
1111
            // Options for calculate dimensions
1112
            'newWidth'  => $newWidth,
1113
            'newHeight' => $newHeight,
1114
            'aspectRatio' => $aspectRatio,
1115
            'keepRatio' => $keepRatio,
1116
            'cropToFit' => $cropToFit,
1117
            'fillToFit' => $fillToFit,
1118
            'crop'      => $crop,
1119
            'area'      => $area,
1120
            'upscale'   => $upscale,
1121
1122
            // Pre-processing, before resizing is done
1123
            'scale'        => $scale,
1124
            'rotateBefore' => $rotateBefore,
1125
            'autoRotate'   => $autoRotate,
1126
1127
            // General processing options
1128
            'bgColor'    => $bgColor,
1129
1130
            // Post-processing, after resizing is done
1131
            'palette'   => $palette,
1132
            'filters'   => $filters,
1133
            'sharpen'   => $sharpen,
1134
            'emboss'    => $emboss,
1135
            'blur'      => $blur,
1136
            'convolve'  => $convolve,
1137
            'rotateAfter' => $rotateAfter,
1138
1139
            // Output format
1140
            'outputFormat' => $outputFormat,
1141
            'dpr'          => $dpr,
1142
        )
1143
    )
1144
    ->loadImageDetails()
1145
    ->initDimensions()
1146
    ->calculateNewWidthAndHeight()
1147
    ->setSaveAsExtension($saveAs)
1148
    ->setJpegQuality($quality)
1149
    ->setPngCompression($compress)
1150
    ->useOriginalIfPossible($useOriginal)
1151
    ->generateFilename($cachePath)
1152
    ->useCacheIfPossible($useCache)
1153
    ->load()
1154
    ->preResize()
1155
    ->resize()
1156
    ->postResize()
1157
    ->setPostProcessingOptions($postProcessing)
1158
    ->save()
1159
    ->linkToCacheFile($aliasTarget)
1160
    ->output();
1161