Completed
Push — master ( 8ad324...cde8ba )
by Mikael
03:11
created

img.php ➔ getConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 9.4285
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 14 and the first side effect is on line 11.

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
$version = "v0.7.12 (2016-06-01)";
12
13
// For CRemoteImage
14
define("CIMAGE_USER_AGENT", "CImage/$version");
15
16
17
18
/**
19
 * Display error message.
20
 *
21
 * @param string $msg to display.
22
 * @param int $type of HTTP error to display.
23
 *
24
 * @return void
25
 */
26
function errorPage($msg, $type = 500)
27
{
28
    global $mode;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
29
30
    switch ($type) {
31
        case 403:
32
            $header = "403 Forbidden";
33
            break;
34
        case 404:
35
            $header = "404 Not Found";
36
            break;
37
        default:
38
            $header = "500 Internal Server Error";
39
    }
40
41
    if ($mode == "strict") {
42
        $header = "404 Not Found";
43
    }
44
45
    header("HTTP/1.0 $header");
46
47
    if ($mode == "development") {
48
        die("[img.php] $msg");
0 ignored issues
show
Coding Style Compatibility introduced by
The function errorPage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
49
    }
50
51
    error_log("[img.php] $msg");
52
    die("HTTP/1.0 $header");
0 ignored issues
show
Coding Style Compatibility introduced by
The function errorPage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
53
}
54
55
56
57
/**
58
 * Custom exception handler.
59
 */
60
set_exception_handler(function ($exception) {
61
    errorPage(
62
        "<p><b>img.php: Uncaught exception:</b> <p>"
63
        . $exception->getMessage()
64
        . "</p><pre>"
65
        . $exception->getTraceAsString()
66
        . "</pre>",
67
        500
68
    );
69
});
70
71
72
73
/**
74
 * Get input from query string or return default value if not set.
75
 *
76
 * @param mixed $key     as string or array of string values to look for in $_GET.
77
 * @param mixed $default value to return when $key is not set in $_GET.
78
 *
79
 * @return mixed value from $_GET or default value.
80
 */
81
function get($key, $default = null)
0 ignored issues
show
Coding Style introduced by
get uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
82
{
83
    if (is_array($key)) {
84
        foreach ($key as $val) {
85
            if (isset($_GET[$val])) {
86
                return $_GET[$val];
87
            }
88
        }
89
    } elseif (isset($_GET[$key])) {
90
        return $_GET[$key];
91
    }
92
    return $default;
93
}
94
95
96
97
/**
98
 * Get input from query string and set to $defined if defined or else $undefined.
99
 *
100
 * @param mixed $key       as string or array of string values to look for in $_GET.
101
 * @param mixed $defined   value to return when $key is set in $_GET.
102
 * @param mixed $undefined value to return when $key is not set in $_GET.
103
 *
104
 * @return mixed value as $defined or $undefined.
105
 */
106
function getDefined($key, $defined, $undefined)
107
{
108
    return get($key) === null ? $undefined : $defined;
109
}
110
111
112
113
/**
114
 * Get value from config array or default if key is not set in config array.
115
 *
116
 * @param string $key    the key in the config array.
117
 * @param mixed $default value to be default if $key is not set in config.
118
 *
119
 * @return mixed value as $config[$key] or $default.
120
 */
121
function getConfig($key, $default)
122
{
123
    global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
124
    return isset($config[$key])
125
        ? $config[$key]
126
        : $default;
127
}
128
129
130
131
/**
132
 * Log when verbose mode, when used without argument it returns the result.
133
 *
134
 * @param string $msg to log.
135
 *
136
 * @return void or array.
137
 */
138
function verbose($msg = null)
139
{
140
    global $verbose, $verboseFile;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

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