Completed
Push — 0713 ( c637fa...b1d0cb )
by Mikael
02:55
created

img.php ➔ get()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 13
rs 8.8571
1
<?php
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
24
25
/**
26
 * Setup the autoloader, but not when using a bundle.
27
 */
28
if (!defined("CIMAGE_BUNDLE")) {
29
    if (!isset($config["autoloader"])) {
30
        die("CImage: Missing autoloader.");
31
    }
32
33
    require $config["autoloader"];
34
}
35
36
37
38
/**
39
* verbose, v - do a verbose dump of what happens
40
* vf - do verbose dump to file
41
*/
42
$verbose = getDefined(array('verbose', 'v'), true, false);
43
$verboseFile = getDefined('vf', true, false);
44
verbose("img.php version = " . CIMAGE_VERSION);
45
46
47
48
/**
49
* status - do a verbose dump of the configuration
50
*/
51
$status = getDefined('status', true, false);
52
53
54
55
/**
56
 * Set mode as strict, production or development.
57
 * Default is production environment.
58
 */
59
$mode = getConfig('mode', 'production');
60
61
// Settings for any mode
62
set_time_limit(20);
63
ini_set('gd.jpeg_ignore_warning', 1);
64
65
if (!extension_loaded('gd')) {
66
    errorPage("Extension gd is not loaded.", 500);
67
}
68
69
// Specific settings for each mode
70
if ($mode == 'strict') {
71
72
    error_reporting(0);
73
    ini_set('display_errors', 0);
74
    ini_set('log_errors', 1);
75
    $verbose = false;
76
    $status = false;
77
    $verboseFile = false;
78
79
} elseif ($mode == 'production') {
80
81
    error_reporting(-1);
82
    ini_set('display_errors', 0);
83
    ini_set('log_errors', 1);
84
    $verbose = false;
85
    $status = false;
86
    $verboseFile = false;
87
88
} elseif ($mode == 'development') {
89
90
    error_reporting(-1);
91
    ini_set('display_errors', 1);
92
    ini_set('log_errors', 0);
93
    $verboseFile = false;
94
95
} elseif ($mode == 'test') {
96
97
    error_reporting(-1);
98
    ini_set('display_errors', 1);
99
    ini_set('log_errors', 0);
100
101
} else {
102
    errorPage("Unknown mode: $mode", 500);
103
}
104
105
verbose("mode = $mode");
106
verbose("error log = " . ini_get('error_log'));
107
108
109
110
/**
111
 * Set default timezone if not set or if its set in the config-file.
112
 */
113
$defaultTimezone = getConfig('default_timezone', null);
114
115
if ($defaultTimezone) {
116
    date_default_timezone_set($defaultTimezone);
117
} elseif (!ini_get('default_timezone')) {
118
    date_default_timezone_set('UTC');
119
}
120
121
122
123
/**
124
 * Check if passwords are configured, used and match.
125
 * Options decide themself if they require passwords to be used.
126
 */
127
$pwdConfig   = getConfig('password', false);
128
$pwdAlways   = getConfig('password_always', false);
129
$pwdType     = getConfig('password_type', 'text');
130
$pwd         = get(array('password', 'pwd'), null);
131
132
// Check if passwords match, if configured to use passwords
133
$passwordMatch = null;
134
if ($pwd) {
135
    switch ($pwdType) {
136
        case 'md5':
137
            $passwordMatch = ($pwdConfig === md5($pwd));
138
            break;
139
        case 'hash':
140
            $passwordMatch = password_verify($pwd, $pwdConfig);
141
            break;
142
        case 'text':
143
            $passwordMatch = ($pwdConfig === $pwd);
144
            break;
145
        default:
146
            $passwordMatch = false;
147
    }
148
}
149
150
if ($pwdAlways && $passwordMatch !== true) {
151
    errorPage("Password required and does not match or exists.", 403);
152
}
153
154
verbose("password match = $passwordMatch");
155
156
157
158
/**
159
 * Prevent hotlinking, leeching, of images by controlling who access them
160
 * from where.
161
 *
162
 */
163
$allowHotlinking = getConfig('allow_hotlinking', true);
164
$hotlinkingWhitelist = getConfig('hotlinking_whitelist', array());
165
166
$serverName  = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
167
$referer     = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
168
$refererHost = parse_url($referer, PHP_URL_HOST);
169
170
if (!$allowHotlinking) {
171
    if ($passwordMatch) {
172
        ; // Always allow when password match
173
        verbose("Hotlinking since passwordmatch");
174
    } elseif ($passwordMatch === false) {
175
        errorPage("Hotlinking/leeching not allowed when password missmatch.", 403);
176
    } elseif (!$referer) {
177
        errorPage("Hotlinking/leeching not allowed and referer is missing.", 403);
178
    } elseif (strcmp($serverName, $refererHost) == 0) {
179
        ; // Allow when serverName matches refererHost
180
        verbose("Hotlinking disallowed but serverName matches refererHost.");
181
    } elseif (!empty($hotlinkingWhitelist)) {
182
        $whitelist = new CWhitelist();
183
        $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 168 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...
184
185
        if ($allowedByWhitelist) {
186
            verbose("Hotlinking/leeching allowed by whitelist.");
187
        } else {
188
            errorPage("Hotlinking/leeching not allowed by whitelist. Referer: $referer.", 403);
189
        }
190
191
    } else {
192
        errorPage("Hotlinking/leeching not allowed.", 403);
193
    }
194
}
195
196
verbose("allow_hotlinking = $allowHotlinking");
197
verbose("referer = $referer");
198
verbose("referer host = $refererHost");
199
200
201
202
/**
203
 * Create the class for the image.
204
 */
205
$CImage = getConfig('CImage', 'CImage');
206
$img = new $CImage();
207
$img->setVerbose($verbose || $verboseFile);
208
209
210
211
/**
212
 * Get the cachepath from config.
213
 */
214
$CCache = getConfig('CCache', 'CCache');
215
$cachePath = getConfig('cache_path', __DIR__ . '/../cache/');
216
$cache = new $CCache();
217
$cache->setDir($cachePath);
218
219
220
221
/**
222
 * no-cache, nc - skip the cached version and process and create a new version in cache.
223
 */
224
$useCache = getDefined(array('no-cache', 'nc'), false, true);
225
226
verbose("use cache = $useCache");
227
228
229
230
/**
231
 * Prepare fast track cache for swriting cache items.
232
 */
233
$fastTrackCache = "fasttrack";
234
$allowFastTrackCache = getConfig('fast_track_allow', false);
235
236
$CFastTrackCache = getConfig('CFastTrackCache', 'CFastTrackCache');
237
$ftc = new $CFastTrackCache();
238
$ftc->setCacheDir($cache->getPathToSubdir($fastTrackCache))
239
    ->enable($allowFastTrackCache)
240
    ->setFilename(array('no-cache', 'nc'));
241
$img->injectDependency("fastTrackCache", $ftc);
242
243
244
245
/**
246
 *  Load and output images from fast track cache, if items are available
247
 * in cache.
248
 */
249
if ($useCache && $allowFastTrackCache) {
250
    $ftc->output();
251
}
252
253
254
255
/**
256
 * Allow or disallow remote download of images from other servers.
257
 * Passwords apply if used.
258
 *
259
 */
260
$allowRemote = getConfig('remote_allow', false);
261
262
if ($allowRemote && $passwordMatch !== false) {
263
    $cacheRemote = $cache->getPathToSubdir("remote");
264
    
265
    $pattern = getConfig('remote_pattern', null);
266
    $img->setRemoteDownload($allowRemote, $cacheRemote, $pattern);
267
268
    $whitelist = getConfig('remote_whitelist', null);
269
    $img->setRemoteHostWhitelist($whitelist);
270
}
271
272
273
274
/**
275
 * shortcut, sc - extend arguments with a constant value, defined
276
 * in config-file.
277
 */
278
$shortcut       = get(array('shortcut', 'sc'), null);
279
$shortcutConfig = getConfig('shortcut', array(
280
    'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
281
));
282
283
verbose("shortcut = $shortcut");
284
285
if (isset($shortcut)
286
    && isset($shortcutConfig[$shortcut])) {
287
288
    parse_str($shortcutConfig[$shortcut], $get);
289
    verbose("shortcut-constant = {$shortcutConfig[$shortcut]}");
290
    $_GET = array_merge($_GET, $get);
291
}
292
293
294
295
/**
296
 * src - the source image file.
297
 */
298
$srcImage = urldecode(get('src'))
299
    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...
300
301
// Get settings for src-alt as backup image
302
$srcAltImage = urldecode(get('src-alt', null));
303
$srcAltConfig = getConfig('src_alt', null);
304
if (empty($srcAltImage)) {
305
    $srcAltImage = $srcAltConfig;
306
}
307
308
// Check for valid/invalid characters
309
$imagePath           = getConfig('image_path', __DIR__ . '/img/');
310
$imagePathConstraint = getConfig('image_path_constraint', true);
311
$validFilename       = getConfig('valid_filename', '#^[a-z0-9A-Z-/_ \.:]+$#');
312
313
// Source is remote
314
$remoteSource = false;
315
316
// Dummy image feature
317
$dummyEnabled  = getConfig('dummy_enabled', true);
318
$dummyFilename = getConfig('dummy_filename', 'dummy');
319
$dummyImage = false;
320
321
preg_match($validFilename, $srcImage)
322
    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...
323
324
if ($dummyEnabled && $srcImage === $dummyFilename) {
325
326
    // Prepare to create a dummy image and use it as the source image.
327
    $dummyImage = true;
328
329
} elseif ($allowRemote && $img->isRemoteSource($srcImage)) {
330
331
    // If source is a remote file, ignore local file checks.
332
    $remoteSource = true;
333
334
} else {
335
336
    // Check if file exists on disk or try using src-alt
337
    $pathToImage = realpath($imagePath . $srcImage);
338
339
    if (!is_file($pathToImage) && !empty($srcAltImage)) {
340
        // Try using the src-alt instead
341
        $srcImage = $srcAltImage;
342
        $pathToImage = realpath($imagePath . $srcImage);
343
344
        preg_match($validFilename, $srcImage)
345
            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...
346
347
        if ($dummyEnabled && $srcImage === $dummyFilename) {
348
            // Check if src-alt is the dummy image
349
            $dummyImage = true;
350
        }
351
    }
352
353
    if (!$dummyImage) {
354
        is_file($pathToImage)
355
            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...
356
                'Source image is not a valid file, check the filename and that a
357
                matching file exists on the filesystem.',
358
                404
359
            );
360
    } 
361
}
362
363
if ($imagePathConstraint && !$dummyImage && !$remoteSource) {
364
    // Check that the image is a file below the directory 'image_path'.
365
    $imageDir = realpath($imagePath);
366
367
    substr_compare($imageDir, $pathToImage, 0, strlen($imageDir)) == 0
368
        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...
369
            'Security constraint: Source image is not below the directory "image_path"
370
            as specified in the config file img_config.php.',
371
            404
372
        );
373
}
374
375
verbose("src = $srcImage");
376
377
378
379
/**
380
 * Manage size constants from config file, use constants to replace values
381
 * for width and height.
382
 */
383
$sizeConstant = getConfig('size_constant', function () {
384
385
    // Set sizes to map constant to value, easier to use with width or height
386
    $sizes = array(
387
        'w1' => 613,
388
        'w2' => 630,
389
    );
390
391
    // Add grid column width, useful for use as predefined size for width (or height).
392
    $gridColumnWidth = 30;
393
    $gridGutterWidth = 10;
394
    $gridColumns     = 24;
395
396
    for ($i = 1; $i <= $gridColumns; $i++) {
397
        $sizes['c' . $i] = ($gridColumnWidth + $gridGutterWidth) * $i - $gridGutterWidth;
398
    }
399
400
    return $sizes;
401
});
402
403
$sizes = call_user_func($sizeConstant);
404
405
406
407
/**
408
 * width, w - set target width, affecting the resulting image width, height and resize options
409
 */
410
$newWidth     = get(array('width', 'w'));
411
$maxWidth     = getConfig('max_width', 2000);
412
413
// Check to replace predefined size
414
if (isset($sizes[$newWidth])) {
415
    $newWidth = $sizes[$newWidth];
416
}
417
418
// Support width as % of original width
419
if ($newWidth[strlen($newWidth)-1] == '%') {
420
    is_numeric(substr($newWidth, 0, -1))
421
        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...
422
} else {
423
    is_null($newWidth)
424
        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...
425
        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...
426
}
427
428
verbose("new width = $newWidth");
429
430
431
432
/**
433
 * height, h - set target height, affecting the resulting image width, height and resize options
434
 */
435
$newHeight = get(array('height', 'h'));
436
$maxHeight = getConfig('max_height', 2000);
437
438
// Check to replace predefined size
439
if (isset($sizes[$newHeight])) {
440
    $newHeight = $sizes[$newHeight];
441
}
442
443
// height
444
if ($newHeight[strlen($newHeight)-1] == '%') {
445
    is_numeric(substr($newHeight, 0, -1))
446
        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...
447
} else {
448
    is_null($newHeight)
449
        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...
450
        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...
451
}
452
453
verbose("new height = $newHeight");
454
455
456
457
/**
458
 * aspect-ratio, ar - affecting the resulting image width, height and resize options
459
 */
460
$aspectRatio         = get(array('aspect-ratio', 'ar'));
461
$aspectRatioConstant = getConfig('aspect_ratio_constant', function () {
462
    return array(
463
        '3:1'    => 3/1,
464
        '3:2'    => 3/2,
465
        '4:3'    => 4/3,
466
        '8:5'    => 8/5,
467
        '16:10'  => 16/10,
468
        '16:9'   => 16/9,
469
        'golden' => 1.618,
470
    );
471
});
472
473
// Check to replace predefined aspect ratio
474
$aspectRatios = call_user_func($aspectRatioConstant);
475
$negateAspectRatio = ($aspectRatio[0] == '!') ? true : false;
476
$aspectRatio = $negateAspectRatio ? substr($aspectRatio, 1) : $aspectRatio;
477
478
if (isset($aspectRatios[$aspectRatio])) {
479
    $aspectRatio = $aspectRatios[$aspectRatio];
480
}
481
482
if ($negateAspectRatio) {
483
    $aspectRatio = 1 / $aspectRatio;
484
}
485
486
is_null($aspectRatio)
487
    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...
488
    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...
489
490
verbose("aspect ratio = $aspectRatio");
491
492
493
494
/**
495
 * crop-to-fit, cf - affecting the resulting image width, height and resize options
496
 */
497
$cropToFit = getDefined(array('crop-to-fit', 'cf'), true, false);
498
499
verbose("crop to fit = $cropToFit");
500
501
502
503
/**
504
 * Set default background color from config file.
505
 */
506
$backgroundColor = getConfig('background_color', null);
507
508
if ($backgroundColor) {
509
    $img->setDefaultBackgroundColor($backgroundColor);
510
    verbose("Using default background_color = $backgroundColor");
511
}
512
513
514
515
/**
516
 * bgColor - Default background color to use
517
 */
518
$bgColor = get(array('bgColor', 'bg-color', 'bgc'), null);
519
520
verbose("bgColor = $bgColor");
521
522
523
524
/**
525
 * Do or do not resample image when resizing.
526
 */
527
$resizeStrategy = getDefined(array('no-resample'), true, false);
528
529
if ($resizeStrategy) {
530
    $img->setCopyResizeStrategy($img::RESIZE);
531
    verbose("Setting = Resize instead of resample");
532
}
533
534
535
536
537
/**
538
 * fill-to-fit, ff - affecting the resulting image width, height and resize options
539
 */
540
$fillToFit = get(array('fill-to-fit', 'ff'), null);
541
542
verbose("fill-to-fit = $fillToFit");
543
544
if ($fillToFit !== null) {
545
546
    if (!empty($fillToFit)) {
547
        $bgColor   = $fillToFit;
548
        verbose("fillToFit changed bgColor to = $bgColor");
549
    }
550
551
    $fillToFit = true;
552
    verbose("fill-to-fit (fixed) = $fillToFit");
553
}
554
555
556
557
/**
558
 * no-ratio, nr, stretch - affecting the resulting image width, height and resize options
559
 */
560
$keepRatio = getDefined(array('no-ratio', 'nr', 'stretch'), false, true);
561
562
verbose("keep ratio = $keepRatio");
563
564
565
566
/**
567
 * crop, c - affecting the resulting image width, height and resize options
568
 */
569
$crop = get(array('crop', 'c'));
570
571
verbose("crop = $crop");
572
573
574
575
/**
576
 * area, a - affecting the resulting image width, height and resize options
577
 */
578
$area = get(array('area', 'a'));
579
580
verbose("area = $area");
581
582
583
584
/**
585
 * skip-original, so - skip the original image and always process a new image
586
 */
587
$useOriginal = getDefined(array('skip-original', 'so'), false, true);
588
$useOriginalDefault = getConfig('skip_original', false);
589
590
if ($useOriginalDefault === true) {
591
    verbose("skip original is default ON");
592
    $useOriginal = false;
593
}
594
595
verbose("use original = $useOriginal");
596
597
598
599
/**
600
 * quality, q - set level of quality for jpeg images
601
 */
602
$quality = get(array('quality', 'q'));
603
$qualityDefault = getConfig('jpg_quality', null);
604
605
is_null($quality)
606
    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...
607
    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...
608
609
if (is_null($quality) && !is_null($qualityDefault)) {
610
    $quality = $qualityDefault;
611
}
612
613
verbose("quality = $quality");
614
615
616
617
/**
618
 * compress, co - what strategy to use when compressing png images
619
 */
620
$compress = get(array('compress', 'co'));
621
$compressDefault = getConfig('png_compression', null);
622
623
is_null($compress)
624
    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...
625
    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...
626
627
if (is_null($compress) && !is_null($compressDefault)) {
628
    $compress = $compressDefault;
629
}
630
631
verbose("compress = $compress");
632
633
634
635
/**
636
 * save-as, sa - what type of image to save
637
 */
638
$saveAs = get(array('save-as', 'sa'));
639
640
verbose("save as = $saveAs");
641
642
643
644
/**
645
 * scale, s - Processing option, scale up or down the image prior actual resize
646
 */
647
$scale = get(array('scale', 's'));
648
649
is_null($scale)
650
    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...
651
    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...
652
653
verbose("scale = $scale");
654
655
656
657
/**
658
 * palette, p - Processing option, create a palette version of the image
659
 */
660
$palette = getDefined(array('palette', 'p'), true, false);
661
662
verbose("palette = $palette");
663
664
665
666
/**
667
 * sharpen - Processing option, post filter for sharpen effect
668
 */
669
$sharpen = getDefined('sharpen', true, null);
670
671
verbose("sharpen = $sharpen");
672
673
674
675
/**
676
 * emboss - Processing option, post filter for emboss effect
677
 */
678
$emboss = getDefined('emboss', true, null);
679
680
verbose("emboss = $emboss");
681
682
683
684
/**
685
 * blur - Processing option, post filter for blur effect
686
 */
687
$blur = getDefined('blur', true, null);
688
689
verbose("blur = $blur");
690
691
692
693
/**
694
 * rotateBefore - Rotate the image with an angle, before processing
695
 */
696
$rotateBefore = get(array('rotateBefore', 'rotate-before', 'rb'));
697
698
is_null($rotateBefore)
699
    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...
700
    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...
701
702
verbose("rotateBefore = $rotateBefore");
703
704
705
706
/**
707
 * rotateAfter - Rotate the image with an angle, before processing
708
 */
709
$rotateAfter = get(array('rotateAfter', 'rotate-after', 'ra', 'rotate', 'r'));
710
711
is_null($rotateAfter)
712
    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...
713
    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...
714
715
verbose("rotateAfter = $rotateAfter");
716
717
718
719
/**
720
 * autoRotate - Auto rotate based on EXIF information
721
 */
722
$autoRotate = getDefined(array('autoRotate', 'auto-rotate', 'aro'), true, false);
723
724
verbose("autoRotate = $autoRotate");
725
726
727
728
/**
729
 * filter, f, f0-f9 - Processing option, post filter for various effects using imagefilter()
730
 */
731
$filters = array();
732
$filter = get(array('filter', 'f'));
733
if ($filter) {
734
    $filters[] = $filter;
735
}
736
737
for ($i = 0; $i < 10; $i++) {
738
    $filter = get(array("filter{$i}", "f{$i}"));
739
    if ($filter) {
740
        $filters[] = $filter;
741
    }
742
}
743
744
verbose("filters = " . print_r($filters, 1));
745
746
747
748
/**
749
* json -  output the image as a JSON object with details on the image.
750
* ascii - output the image as ASCII art.
751
 */
752
$outputFormat = getDefined('json', 'json', null);
753
$outputFormat = getDefined('ascii', 'ascii', $outputFormat);
754
755
verbose("outputformat = $outputFormat");
756
757
if ($outputFormat == 'ascii') {
758
    $defaultOptions = getConfig(
759
        'ascii-options',
760
        array(
761
            "characterSet" => 'two',
762
            "scale" => 14,
763
            "luminanceStrategy" => 3,
764
            "customCharacterSet" => null,
765
        )
766
    );
767
    $options = get('ascii');
768
    $options = explode(',', $options);
769
770
    if (isset($options[0]) && !empty($options[0])) {
771
        $defaultOptions['characterSet'] = $options[0];
772
    }
773
774
    if (isset($options[1]) && !empty($options[1])) {
775
        $defaultOptions['scale'] = $options[1];
776
    }
777
778
    if (isset($options[2]) && !empty($options[2])) {
779
        $defaultOptions['luminanceStrategy'] = $options[2];
780
    }
781
782
    if (count($options) > 3) {
783
        // Last option is custom character string
784
        unset($options[0]);
785
        unset($options[1]);
786
        unset($options[2]);
787
        $characterString = implode($options);
788
        $defaultOptions['customCharacterSet'] = $characterString;
789
    }
790
791
    $img->setAsciiOptions($defaultOptions);
792
}
793
794
795
796
797
/**
798
 * dpr - change to get larger image to easier support larger dpr, such as retina.
799
 */
800
$dpr = get(array('ppi', 'dpr', 'device-pixel-ratio'), 1);
801
802
verbose("dpr = $dpr");
803
804
805
806
/**
807
 * convolve - image convolution as in http://php.net/manual/en/function.imageconvolution.php
808
 */
809
$convolve = get('convolve', null);
810
$convolutionConstant = getConfig('convolution_constant', array());
811
812
// Check if the convolve is matching an existing constant
813
if ($convolve && isset($convolutionConstant)) {
814
    $img->addConvolveExpressions($convolutionConstant);
815
    verbose("convolve constant = " . print_r($convolutionConstant, 1));
816
}
817
818
verbose("convolve = " . print_r($convolve, 1));
819
820
821
822
/**
823
 * no-upscale, nu - Do not upscale smaller image to larger dimension.
824
 */
825
$upscale = getDefined(array('no-upscale', 'nu'), false, true);
826
827
verbose("upscale = $upscale");
828
829
830
831
/**
832
 * Get details for post processing
833
 */
834
$postProcessing = getConfig('postprocessing', array(
835
    'png_filter'        => false,
836
    'png_filter_cmd'    => '/usr/local/bin/optipng -q',
837
838
    'png_deflate'       => false,
839
    'png_deflate_cmd'   => '/usr/local/bin/pngout -q',
840
841
    'jpeg_optimize'     => false,
842
    'jpeg_optimize_cmd' => '/usr/local/bin/jpegtran -copy none -optimize',
843
));
844
845
846
847
/**
848
 * alias - Save resulting image to another alias name.
849
 * Password always apply, must be defined.
850
 */
851
$alias          = get('alias', null);
852
$aliasPath      = getConfig('alias_path', null);
853
$validAliasname = getConfig('valid_aliasname', '#^[a-z0-9A-Z-_]+$#');
854
$aliasTarget    = null;
855
856
if ($alias && $aliasPath && $passwordMatch) {
857
858
    $aliasTarget = $aliasPath . $alias;
859
    $useCache    = false;
860
861
    is_writable($aliasPath)
862
        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...
863
864
    preg_match($validAliasname, $alias)
865
        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...
866
867
} elseif ($alias) {
868
    errorPage('Alias is not enabled in the config file or password not matching.', 403);
869
}
870
871
verbose("alias = $alias");
872
873
874
875
/**
876
 * Add cache control HTTP header.
877
 */
878
$cacheControl = getConfig('cache_control', null);
879
880
if ($cacheControl) {
881
    verbose("cacheControl = $cacheControl");
882
    $img->addHTTPHeader("Cache-Control", $cacheControl);
883
}
884
885
886
887
/**
888
 * Prepare a dummy image and use it as source image.
889
 */
890
if ($dummyImage === true) {
891
    $dummyDir = $cache->getPathToSubdir("dummy");
892
893
    $img->setSaveFolder($dummyDir)
894
        ->setSource($dummyFilename, $dummyDir)
895
        ->setOptions(
896
            array(
897
                'newWidth'  => $newWidth,
898
                'newHeight' => $newHeight,
899
                'bgColor'   => $bgColor,
900
            )
901
        )
902
        ->setJpegQuality($quality)
903
        ->setPngCompression($compress)
904
        ->createDummyImage()
905
        ->generateFilename(null, false)
906
        ->save(null, null, false);
907
908
    $srcImage = $img->getTarget();
909
    $imagePath = null;
910
911
    verbose("src (updated) = $srcImage");
912
}
913
914
915
916
/**
917
 * Prepare a sRGB version of the image and use it as source image.
918
 */
919
$srgbDefault = getConfig('srgb_default', false);
920
$srgbColorProfile = getConfig('srgb_colorprofile', __DIR__ . '/../icc/sRGB_IEC61966-2-1_black_scaled.icc');
921
$srgb = getDefined('srgb', true, null);
922
923
if ($srgb || $srgbDefault) {
924
925
    $filename = $img->convert2sRGBColorSpace(
926
        $srcImage,
927
        $imagePath,
928
        $cache->getPathToSubdir("srgb"),
929
        $srgbColorProfile,
930
        $useCache
931
    );
932
933
    if ($filename) {
934
        $srcImage = $img->getTarget();
935
        $imagePath = null;
936
        verbose("srgb conversion and saved to cache = $srcImage");
937
    } else {
938
        verbose("srgb not op");
939
    }
940
}
941
942
943
944
/**
945
 * Display status
946
 */
947
if ($status) {
948
    $text  = "img.php version = " . CIMAGE_VERSION . "\n";
949
    $text .= "PHP version = " . PHP_VERSION . "\n";
950
    $text .= "Running on: " . $_SERVER['SERVER_SOFTWARE'] . "\n";
951
    $text .= "Allow remote images = $allowRemote\n";
952
953
    $res = $cache->getStatusOfSubdir("");
954
    $text .= "Cache $res\n";
955
956
    $res = $cache->getStatusOfSubdir("remote");
957
    $text .= "Cache remote $res\n";
958
959
    $res = $cache->getStatusOfSubdir("dummy");
960
    $text .= "Cache dummy $res\n";
961
962
    $res = $cache->getStatusOfSubdir("srgb");
963
    $text .= "Cache srgb $res\n";
964
965
    $res = $cache->getStatusOfSubdir($fasttrackCache);
966
    $text .= "Cache fasttrack $res\n";
967
968
    $text .= "Alias path writable = " . is_writable($aliasPath) . "\n";
969
970
    $no = extension_loaded('exif') ? null : 'NOT';
971
    $text .= "Extension exif is $no loaded.<br>";
972
973
    $no = extension_loaded('curl') ? null : 'NOT';
974
    $text .= "Extension curl is $no loaded.<br>";
975
976
    $no = extension_loaded('imagick') ? null : 'NOT';
977
    $text .= "Extension imagick is $no loaded.<br>";
978
979
    $no = extension_loaded('gd') ? null : 'NOT';
980
    $text .= "Extension gd is $no loaded.<br>";
981
982
    if (!$no) {
983
        $text .= print_r(gd_info(), 1);
984
    }
985
986
    echo <<<EOD
987
<!doctype html>
988
<html lang=en>
989
<meta charset=utf-8>
990
<title>CImage status</title>
991
<pre>$text</pre>
992
EOD;
993
    exit;
994
}
995
996
997
998
/**
999
 * Log verbose details to file
1000
 */
1001
if ($verboseFile) {
1002
    $img->setVerboseToFile("$cachePath/log.txt");
1003
}
1004
1005
1006
1007
/**
1008
 * Hook after img.php configuration and before processing with CImage
1009
 */
1010
$hookBeforeCImage = getConfig('hook_before_CImage', null);
1011
1012
if (is_callable($hookBeforeCImage)) {
1013
    verbose("hookBeforeCImage activated");
1014
1015
    $allConfig = $hookBeforeCImage($img, array(
1016
            // Options for calculate dimensions
1017
            'newWidth'  => $newWidth,
1018
            'newHeight' => $newHeight,
1019
            'aspectRatio' => $aspectRatio,
1020
            'keepRatio' => $keepRatio,
1021
            'cropToFit' => $cropToFit,
1022
            'fillToFit' => $fillToFit,
1023
            'crop'      => $crop,
1024
            'area'      => $area,
1025
            'upscale'   => $upscale,
1026
1027
            // Pre-processing, before resizing is done
1028
            'scale'        => $scale,
1029
            'rotateBefore' => $rotateBefore,
1030
            'autoRotate'   => $autoRotate,
1031
1032
            // General processing options
1033
            'bgColor'    => $bgColor,
1034
1035
            // Post-processing, after resizing is done
1036
            'palette'   => $palette,
1037
            'filters'   => $filters,
1038
            'sharpen'   => $sharpen,
1039
            'emboss'    => $emboss,
1040
            'blur'      => $blur,
1041
            'convolve'  => $convolve,
1042
            'rotateAfter' => $rotateAfter,
1043
1044
            // Output format
1045
            'outputFormat' => $outputFormat,
1046
            'dpr'          => $dpr,
1047
1048
            // Other
1049
            'postProcessing' => $postProcessing,
1050
    ));
1051
    verbose(print_r($allConfig, 1));
1052
    extract($allConfig);
1053
}
1054
1055
1056
1057
/**
1058
 * Display image if verbose mode
1059
 */
1060
if ($verbose) {
1061
    $query = array();
1062
    parse_str($_SERVER['QUERY_STRING'], $query);
1063
    unset($query['verbose']);
1064
    unset($query['v']);
1065
    unset($query['nocache']);
1066
    unset($query['nc']);
1067
    unset($query['json']);
1068
    $url1 = '?' . htmlentities(urldecode(http_build_query($query)));
1069
    $url2 = '?' . urldecode(http_build_query($query));
1070
    echo <<<EOD
1071
<!doctype html>
1072
<html lang=en>
1073
<meta charset=utf-8>
1074
<title>CImage verbose output</title>
1075
<style>body{background-color: #ddd}</style>
1076
<a href=$url1><code>$url1</code></a><br>
1077
<img src='{$url1}' />
1078
<pre id="json"></pre>
1079
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
1080
<script type="text/javascript">
1081
window.getDetails = function (url, id) {
1082
  $.getJSON(url, function(data) {
1083
    element = document.getElementById(id);
1084
    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 : '');
1085
  });
1086
}
1087
</script>
1088
<script type="text/javascript">window.getDetails("{$url2}&json", "json")</script>
1089
EOD;
1090
}
1091
1092
1093
1094
/**
1095
 * Load, process and output the image
1096
 */
1097
$img->log("Incoming arguments: " . print_r(verbose(), 1))
1098
    ->setSaveFolder($cachePath)
1099
    ->useCache($useCache)
1100
    ->setSource($srcImage, $imagePath)
1101
    ->setOptions(
1102
        array(
1103
            // Options for calculate dimensions
1104
            'newWidth'  => $newWidth,
1105
            'newHeight' => $newHeight,
1106
            'aspectRatio' => $aspectRatio,
1107
            'keepRatio' => $keepRatio,
1108
            'cropToFit' => $cropToFit,
1109
            'fillToFit' => $fillToFit,
1110
            'crop'      => $crop,
1111
            'area'      => $area,
1112
            'upscale'   => $upscale,
1113
1114
            // Pre-processing, before resizing is done
1115
            'scale'        => $scale,
1116
            'rotateBefore' => $rotateBefore,
1117
            'autoRotate'   => $autoRotate,
1118
1119
            // General processing options
1120
            'bgColor'    => $bgColor,
1121
1122
            // Post-processing, after resizing is done
1123
            'palette'   => $palette,
1124
            'filters'   => $filters,
1125
            'sharpen'   => $sharpen,
1126
            'emboss'    => $emboss,
1127
            'blur'      => $blur,
1128
            'convolve'  => $convolve,
1129
            'rotateAfter' => $rotateAfter,
1130
1131
            // Output format
1132
            'outputFormat' => $outputFormat,
1133
            'dpr'          => $dpr,
1134
        )
1135
    )
1136
    ->loadImageDetails()
1137
    ->initDimensions()
1138
    ->calculateNewWidthAndHeight()
1139
    ->setSaveAsExtension($saveAs)
1140
    ->setJpegQuality($quality)
1141
    ->setPngCompression($compress)
1142
    ->useOriginalIfPossible($useOriginal)
1143
    ->generateFilename($cachePath)
1144
    ->useCacheIfPossible($useCache)
1145
    ->load()
1146
    ->preResize()
1147
    ->resize()
1148
    ->postResize()
1149
    ->setPostProcessingOptions($postProcessing)
1150
    ->save()
1151
    ->linkToCacheFile($aliasTarget)
1152
    ->output();
1153