basics.php ➔ env()   F
last analyzed

Complexity

Conditions 23
Paths 399

Size

Total Lines 89
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 69
c 0
b 0
f 0
nc 399
nop 1
dl 0
loc 89
rs 3.5803

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Basic CakePHP functionality.
4
 *
5
 * Core functions for including other source files, loading models and so forth.
6
 *
7
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
15
 * @link          http://cakephp.org CakePHP(tm) Project
16
 * @package       Cake
17
 * @since         CakePHP(tm) v 0.2.9
18
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
19
 */
20
21
/**
22
 * Basic defines for timing functions.
23
 */
24
	define('SECOND', 1);
25
	define('MINUTE', 60);
26
	define('HOUR', 3600);
27
	define('DAY', 86400);
28
	define('WEEK', 604800);
29
	define('MONTH', 2592000);
30
	define('YEAR', 31536000);
31
32
if (!function_exists('config')) {
33
34
/**
35
 * Loads configuration files. Receives a set of configuration files
36
 * to load.
37
 * Example:
38
 *
39
 * `config('config1', 'config2');`
40
 *
41
 * @return boolean Success
42
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#config
43
 */
44
	function config() {
45
		$args = func_get_args();
46
		$count = count($args);
47
		$included = 0;
48
		foreach ($args as $arg) {
49
			if (file_exists(APP . 'Config' . DS . $arg . '.php')) {
50
				include_once APP . 'Config' . DS . $arg . '.php';
51
				$included++;
52
			}
53
		}
54
		return $included === $count;
55
	}
56
57
}
58
59
if (!function_exists('debug')) {
60
61
/**
62
 * Prints out debug information about given variable.
63
 *
64
 * Only runs if debug level is greater than zero.
65
 *
66
 * @param mixed $var Variable to show debug information for.
67
 * @param boolean $showHtml If set to true, the method prints the debug data in a browser-friendly way.
68
 * @param boolean $showFrom If set to true, the method prints from where the function was called.
69
 * @return void
70
 * @link http://book.cakephp.org/2.0/en/development/debugging.html#basic-debugging
71
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#debug
72
 */
73
	function debug($var, $showHtml = null, $showFrom = true) {
74
		if (Configure::read('debug') > 0) {
75
			App::uses('Debugger', 'Utility');
76
			$file = '';
77
			$line = '';
78
			$lineInfo = '';
79
			if ($showFrom) {
80
				$trace = Debugger::trace(array('start' => 1, 'depth' => 2, 'format' => 'array'));
81
				$file = str_replace(array(CAKE_CORE_INCLUDE_PATH, ROOT), '', $trace[0]['file']);
82
				$line = $trace[0]['line'];
83
			}
84
			$html = <<<HTML
85
<div class="cake-debug-output">
86
%s
87
<pre class="cake-debug">
88
%s
89
</pre>
90
</div>
91
HTML;
92
			$text = <<<TEXT
93
%s
94
########## DEBUG ##########
95
%s
96
###########################
97
98
TEXT;
99
			$template = $html;
100
			if (php_sapi_name() === 'cli' || $showHtml === false) {
101
				$template = $text;
102
				if ($showFrom) {
103
					$lineInfo = sprintf('%s (line %s)', $file, $line);
104
				}
105
			}
106
			if ($showHtml === null && $template !== $text) {
107
				$showHtml = true;
108
			}
109
			$var = Debugger::exportVar($var, 25);
110
			if ($showHtml) {
111
				$template = $html;
112
				$var = h($var);
113
				if ($showFrom) {
114
					$lineInfo = sprintf('<span><strong>%s</strong> (line <strong>%s</strong>)</span>', $file, $line);
115
				}
116
			}
117
			printf($template, $lineInfo, $var);
118
		}
119
	}
120
121
}
122
123
if (!function_exists('sortByKey')) {
124
125
/**
126
 * Sorts given $array by key $sortBy.
127
 *
128
 * @param array $array Array to sort
129
 * @param string $sortBy Sort by this key
130
 * @param string $order Sort order asc/desc (ascending or descending).
131
 * @param integer $type Type of sorting to perform
132
 * @return mixed Sorted array
133
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#sortByKey
134
 */
135
	function sortByKey(&$array, $sortBy, $order = 'asc', $type = SORT_NUMERIC) {
136
		if (!is_array($array)) {
137
			return null;
138
		}
139
140
		foreach ($array as $key => $val) {
141
			$sa[$key] = $val[$sortBy];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sa was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sa = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
142
		}
143
144
		if ($order === 'asc') {
145
			asort($sa, $type);
146
		} else {
147
			arsort($sa, $type);
148
		}
149
150
		foreach ($sa as $key => $val) {
151
			$out[] = $array[$key];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$out was never initialized. Although not strictly required by PHP, it is generally a good practice to add $out = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
152
		}
153
		return $out;
0 ignored issues
show
Bug introduced by
The variable $out does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
154
	}
155
156
}
157
158
if (!function_exists('h')) {
159
160
/**
161
 * Convenience method for htmlspecialchars.
162
 *
163
 * @param string|array|object $text Text to wrap through htmlspecialchars. Also works with arrays, and objects.
164
 *    Arrays will be mapped and have all their elements escaped. Objects will be string cast if they
165
 *    implement a `__toString` method. Otherwise the class name will be used.
166
 * @param boolean $double Encode existing html entities
167
 * @param string $charset Character set to use when escaping. Defaults to config value in 'App.encoding' or 'UTF-8'
168
 * @return string Wrapped text
169
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#h
170
 */
171
	function h($text, $double = true, $charset = null) {
172
		if (is_array($text)) {
173
			$texts = array();
174
			foreach ($text as $k => $t) {
175
				$texts[$k] = h($t, $double, $charset);
176
			}
177
			return $texts;
178
		} elseif (is_object($text)) {
179
			if (method_exists($text, '__toString')) {
180
				$text = (string)$text;
181
			} else {
182
				$text = '(object)' . get_class($text);
183
			}
184
		} elseif (is_bool($text)) {
185
			return $text;
186
		}
187
188
		static $defaultCharset = false;
189 View Code Duplication
		if ($defaultCharset === false) {
190
			$defaultCharset = Configure::read('App.encoding');
191
			if ($defaultCharset === null) {
192
				$defaultCharset = 'UTF-8';
193
			}
194
		}
195
		if (is_string($double)) {
196
			$charset = $double;
197
		}
198
		return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double);
199
	}
200
201
}
202
203
if (!function_exists('pluginSplit')) {
204
205
/**
206
 * Splits a dot syntax plugin name into its plugin and class name.
207
 * If $name does not have a dot, then index 0 will be null.
208
 *
209
 * Commonly used like `list($plugin, $name) = pluginSplit($name);`
210
 *
211
 * @param string $name The name you want to plugin split.
212
 * @param boolean $dotAppend Set to true if you want the plugin to have a '.' appended to it.
213
 * @param string $plugin Optional default plugin to use if no plugin is found. Defaults to null.
214
 * @return array Array with 2 indexes. 0 => plugin name, 1 => class name
215
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#pluginSplit
216
 */
217
	function pluginSplit($name, $dotAppend = false, $plugin = null) {
218
		if (strpos($name, '.') !== false) {
219
			$parts = explode('.', $name, 2);
220
			if ($dotAppend) {
221
				$parts[0] .= '.';
222
			}
223
			return $parts;
224
		}
225
		return array($plugin, $name);
226
	}
227
228
}
229
230
if (!function_exists('pr')) {
231
232
/**
233
 * print_r() convenience function
234
 *
235
 * In terminals this will act the same as using print_r() directly, when not run on cli
236
 * print_r() will wrap <PRE> tags around the output of given array. Similar to debug().
237
 *
238
 * @see debug()
239
 * @param mixed $var Variable to print out
240
 * @return void
241
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#pr
242
 */
243
	function pr($var, $exit = false) {
244
		if (Configure::read('debug') > 0) {
245
			$template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n";
246
			printf($template, print_r($var, true));
247
			if ($exit) {
248
				exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function pr() 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...
249
			}
250
		}
251
	}
252
253
}
254
255
if (!function_exists('am')) {
256
257
/**
258
 * Merge a group of arrays
259
 *
260
 * @param array First array
261
 * @param array Second array
262
 * @param array Third array
263
 * @param array Etc...
264
 * @return array All array parameters merged into one
265
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#am
266
 */
267
	function am() {
268
		$r = array();
269
		$args = func_get_args();
270
		foreach ($args as $a) {
271
			if (!is_array($a)) {
272
				$a = array($a);
273
			}
274
			$r = array_merge($r, $a);
275
		}
276
		return $r;
277
	}
278
279
}
280
281
if (!function_exists('env')) {
282
283
/**
284
 * Gets an environment variable from available sources, and provides emulation
285
 * for unsupported or inconsistent environment variables (i.e. DOCUMENT_ROOT on
286
 * IIS, or SCRIPT_NAME in CGI mode). Also exposes some additional custom
287
 * environment information.
288
 *
289
 * @param string $key Environment variable name.
290
 * @return string Environment variable setting.
291
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#env
292
 */
293
	function env($key) {
0 ignored issues
show
Coding Style introduced by
env uses the super-global variable $_SERVER 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...
Coding Style introduced by
env uses the super-global variable $_ENV 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...
294
		if ($key === 'HTTPS') {
295
			if (isset($_SERVER['HTTPS'])) {
296
				return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
297
			}
298
			return (strpos(env('SCRIPT_URI'), 'https://') === 0);
299
		}
300
301
		if ($key === 'SCRIPT_NAME') {
302
			if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
303
				$key = 'SCRIPT_URL';
304
			}
305
		}
306
307
		$val = null;
308
		if (isset($_SERVER[$key])) {
309
			$val = $_SERVER[$key];
310
		} elseif (isset($_ENV[$key])) {
311
			$val = $_ENV[$key];
312
		} elseif (getenv($key) !== false) {
313
			$val = getenv($key);
314
		}
315
316
		if ($key === 'REMOTE_ADDR' && $val === env('SERVER_ADDR')) {
317
			$addr = env('HTTP_PC_REMOTE_ADDR');
318
			if ($addr !== null) {
319
				$val = $addr;
320
			}
321
		}
322
323
		if ($val !== null) {
324
			return $val;
325
		}
326
327
		switch ($key) {
328
			case 'DOCUMENT_ROOT':
329
				$name = env('SCRIPT_NAME');
330
				$filename = env('SCRIPT_FILENAME');
331
				$offset = 0;
332
				if (!strpos($name, '.php')) {
333
					$offset = 4;
334
				}
335
				return substr($filename, 0, -(strlen($name) + $offset));
336
			case 'PHP_SELF':
337
				return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME'));
338
			case 'CGI_MODE':
339
				return (PHP_SAPI === 'cgi');
340
			case 'HTTP_BASE':
341
				$host = env('HTTP_HOST');
342
				$parts = explode('.', $host);
343
				$count = count($parts);
344
345
				if ($count === 1) {
346
					return '.' . $host;
347
				} elseif ($count === 2) {
348
					return '.' . $host;
349
				} elseif ($count === 3) {
350
					$gTLD = array(
351
						'aero',
352
						'asia',
353
						'biz',
354
						'cat',
355
						'com',
356
						'coop',
357
						'edu',
358
						'gov',
359
						'info',
360
						'int',
361
						'jobs',
362
						'mil',
363
						'mobi',
364
						'museum',
365
						'name',
366
						'net',
367
						'org',
368
						'pro',
369
						'tel',
370
						'travel',
371
						'xxx'
372
					);
373
					if (in_array($parts[1], $gTLD)) {
374
						return '.' . $host;
375
					}
376
				}
377
				array_shift($parts);
378
				return '.' . implode('.', $parts);
379
		}
380
		return null;
381
	}
382
383
}
384
385
if (!function_exists('cache')) {
386
387
/**
388
 * Reads/writes temporary data to cache files or session.
389
 *
390
 * @param string $path File path within /tmp to save the file.
391
 * @param mixed $data The data to save to the temporary file.
392
 * @param mixed $expires A valid strtotime string when the data expires.
393
 * @param string $target The target of the cached data; either 'cache' or 'public'.
394
 * @return mixed The contents of the temporary file.
395
 * @deprecated Will be removed in 3.0. Please use Cache::write() instead.
396
 */
397
	function cache($path, $data = null, $expires = '+1 day', $target = 'cache') {
398
		if (Configure::read('Cache.disable')) {
399
			return null;
400
		}
401
		$now = time();
402
403
		if (!is_numeric($expires)) {
404
			$expires = strtotime($expires, $now);
405
		}
406
407
		switch (strtolower($target)) {
408
			case 'cache':
409
				$filename = CACHE . $path;
410
				break;
411
			case 'public':
412
				$filename = WWW_ROOT . $path;
413
				break;
414
			case 'tmp':
415
				$filename = TMP . $path;
416
				break;
417
		}
418
		$timediff = $expires - $now;
419
		$filetime = false;
420
421
		if (file_exists($filename)) {
422
			//@codingStandardsIgnoreStart
423
			$filetime = @filemtime($filename);
0 ignored issues
show
Bug introduced by
The variable $filename does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
424
			//@codingStandardsIgnoreEnd
425
		}
426
427
		if ($data === null) {
428
			if (file_exists($filename) && $filetime !== false) {
429
				if ($filetime + $timediff < $now) {
430
					//@codingStandardsIgnoreStart
431
					@unlink($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
432
					//@codingStandardsIgnoreEnd
433
				} else {
434
					//@codingStandardsIgnoreStart
435
					$data = @file_get_contents($filename);
436
					//@codingStandardsIgnoreEnd
437
				}
438
			}
439
		} elseif (is_writable(dirname($filename))) {
440
			//@codingStandardsIgnoreStart
441
			@file_put_contents($filename, $data, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
442
			//@codingStandardsIgnoreEnd
443
		}
444
		return $data;
445
	}
446
447
}
448
449
if (!function_exists('clearCache')) {
450
451
/**
452
 * Used to delete files in the cache directories, or clear contents of cache directories
453
 *
454
 * @param string|array $params As String name to be searched for deletion, if name is a directory all files in
455
 *   directory will be deleted. If array, names to be searched for deletion. If clearCache() without params,
456
 *   all files in app/tmp/cache/views will be deleted
457
 * @param string $type Directory in tmp/cache defaults to view directory
458
 * @param string $ext The file extension you are deleting
459
 * @return true if files found and deleted false otherwise
460
 */
461
	function clearCache($params = null, $type = 'views', $ext = '.php') {
462
		if (is_string($params) || $params === null) {
463
			$params = preg_replace('/\/\//', '/', $params);
464
			$cache = CACHE . $type . DS . $params;
465
466
			if (is_file($cache . $ext)) {
467
				//@codingStandardsIgnoreStart
468
				@unlink($cache . $ext);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
469
				//@codingStandardsIgnoreEnd
470
				return true;
471
			} elseif (is_dir($cache)) {
472
				$files = glob($cache . '*');
473
474
				if ($files === false) {
475
					return false;
476
				}
477
478 View Code Duplication
				foreach ($files as $file) {
479
					if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) {
480
						//@codingStandardsIgnoreStart
481
						@unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
482
						//@codingStandardsIgnoreEnd
483
					}
484
				}
485
				return true;
486
			}
487
			$cache = array(
488
				CACHE . $type . DS . '*' . $params . $ext,
489
				CACHE . $type . DS . '*' . $params . '_*' . $ext
490
			);
491
			$files = array();
492
			while ($search = array_shift($cache)) {
493
				$results = glob($search);
494
				if ($results !== false) {
495
					$files = array_merge($files, $results);
496
				}
497
			}
498
			if (empty($files)) {
499
				return false;
500
			}
501 View Code Duplication
			foreach ($files as $file) {
502
				if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) {
503
					//@codingStandardsIgnoreStart
504
					@unlink($file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
505
					//@codingStandardsIgnoreEnd
506
				}
507
			}
508
			return true;
509
510
		} elseif (is_array($params)) {
511
			foreach ($params as $file) {
512
				clearCache($file, $type, $ext);
513
			}
514
			return true;
515
		}
516
		return false;
517
	}
518
519
}
520
521
if (!function_exists('stripslashes_deep')) {
522
523
/**
524
 * Recursively strips slashes from all values in an array
525
 *
526
 * @param array $values Array of values to strip slashes
527
 * @return mixed What is returned from calling stripslashes
528
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#stripslashes_deep
529
 */
530
	function stripslashes_deep($values) {
531
		if (is_array($values)) {
532
			foreach ($values as $key => $value) {
533
				$values[$key] = stripslashes_deep($value);
534
			}
535
		} else {
536
			$values = stripslashes($values);
537
		}
538
		return $values;
539
	}
540
541
}
542
543
if (!function_exists('__')) {
544
545
/**
546
 * Returns a translated string if one is found; Otherwise, the submitted message.
547
 *
548
 * @param string $singular Text to translate
549
 * @param mixed $args Array with arguments or multiple arguments in function
550
 * @return mixed translated string
551
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__
552
 */
553
	function __($singular, $args = null) {
554
		if (!$singular) {
555
			return;
556
		}
557
558
		App::uses('I18n', 'I18n');
559
		$translated = I18n::translate($singular);
560
		if ($args === null) {
561
			return $translated;
562
		} elseif (!is_array($args)) {
563
			$args = array_slice(func_get_args(), 1);
564
		}
565
		return vsprintf($translated, $args);
566
	}
567
568
}
569
570 View Code Duplication
if (!function_exists('__n')) {
571
572
/**
573
 * Returns correct plural form of message identified by $singular and $plural for count $count.
574
 * Some languages have more than one form for plural messages dependent on the count.
575
 *
576
 * @param string $singular Singular text to translate
577
 * @param string $plural Plural text
578
 * @param integer $count Count
579
 * @param mixed $args Array with arguments or multiple arguments in function
580
 * @return mixed plural form of translated string
581
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__n
582
 */
583
	function __n($singular, $plural, $count, $args = null) {
584
		if (!$singular) {
585
			return;
586
		}
587
588
		App::uses('I18n', 'I18n');
589
		$translated = I18n::translate($singular, $plural, null, 6, $count);
590
		if ($args === null) {
591
			return $translated;
592
		} elseif (!is_array($args)) {
593
			$args = array_slice(func_get_args(), 3);
594
		}
595
		return vsprintf($translated, $args);
596
	}
597
598
}
599
600 View Code Duplication
if (!function_exists('__d')) {
601
602
/**
603
 * Allows you to override the current domain for a single message lookup.
604
 *
605
 * @param string $domain Domain
606
 * @param string $msg String to translate
607
 * @param mixed $args Array with arguments or multiple arguments in function
608
 * @return translated string
609
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__d
610
 */
611
	function __d($domain, $msg, $args = null) {
612
		if (!$msg) {
613
			return;
614
		}
615
		App::uses('I18n', 'I18n');
616
		$translated = I18n::translate($msg, null, $domain);
617
		if ($args === null) {
618
			return $translated;
619
		} elseif (!is_array($args)) {
620
			$args = array_slice(func_get_args(), 2);
621
		}
622
		return vsprintf($translated, $args);
623
	}
624
625
}
626
627 View Code Duplication
if (!function_exists('__dn')) {
628
629
/**
630
 * Allows you to override the current domain for a single plural message lookup.
631
 * Returns correct plural form of message identified by $singular and $plural for count $count
632
 * from domain $domain.
633
 *
634
 * @param string $domain Domain
635
 * @param string $singular Singular string to translate
636
 * @param string $plural Plural
637
 * @param integer $count Count
638
 * @param mixed $args Array with arguments or multiple arguments in function
639
 * @return plural form of translated string
640
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__dn
641
 */
642
	function __dn($domain, $singular, $plural, $count, $args = null) {
643
		if (!$singular) {
644
			return;
645
		}
646
		App::uses('I18n', 'I18n');
647
		$translated = I18n::translate($singular, $plural, $domain, 6, $count);
648
		if ($args === null) {
649
			return $translated;
650
		} elseif (!is_array($args)) {
651
			$args = array_slice(func_get_args(), 4);
652
		}
653
		return vsprintf($translated, $args);
654
	}
655
656
}
657
658 View Code Duplication
if (!function_exists('__dc')) {
659
660
/**
661
 * Allows you to override the current domain for a single message lookup.
662
 * It also allows you to specify a category.
663
 *
664
 * The category argument allows a specific category of the locale settings to be used for fetching a message.
665
 * Valid categories are: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.
666
 *
667
 * Note that the category must be specified with a numeric value, instead of the constant name. The values are:
668
 *
669
 * - LC_ALL       0
670
 * - LC_COLLATE   1
671
 * - LC_CTYPE     2
672
 * - LC_MONETARY  3
673
 * - LC_NUMERIC   4
674
 * - LC_TIME      5
675
 * - LC_MESSAGES  6
676
 *
677
 * @param string $domain Domain
678
 * @param string $msg Message to translate
679
 * @param integer $category Category
680
 * @param mixed $args Array with arguments or multiple arguments in function
681
 * @return translated string
682
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__dc
683
 */
684
	function __dc($domain, $msg, $category, $args = null) {
685
		if (!$msg) {
686
			return;
687
		}
688
		App::uses('I18n', 'I18n');
689
		$translated = I18n::translate($msg, null, $domain, $category);
690
		if ($args === null) {
691
			return $translated;
692
		} elseif (!is_array($args)) {
693
			$args = array_slice(func_get_args(), 3);
694
		}
695
		return vsprintf($translated, $args);
696
	}
697
698
}
699
700 View Code Duplication
if (!function_exists('__dcn')) {
701
702
/**
703
 * Allows you to override the current domain for a single plural message lookup.
704
 * It also allows you to specify a category.
705
 * Returns correct plural form of message identified by $singular and $plural for count $count
706
 * from domain $domain.
707
 *
708
 * The category argument allows a specific category of the locale settings to be used for fetching a message.
709
 * Valid categories are: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.
710
 *
711
 * Note that the category must be specified with a numeric value, instead of the constant name. The values are:
712
 *
713
 * - LC_ALL       0
714
 * - LC_COLLATE   1
715
 * - LC_CTYPE     2
716
 * - LC_MONETARY  3
717
 * - LC_NUMERIC   4
718
 * - LC_TIME      5
719
 * - LC_MESSAGES  6
720
 *
721
 * @param string $domain Domain
722
 * @param string $singular Singular string to translate
723
 * @param string $plural Plural
724
 * @param integer $count Count
725
 * @param integer $category Category
726
 * @param mixed $args Array with arguments or multiple arguments in function
727
 * @return plural form of translated string
728
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__dcn
729
 */
730
	function __dcn($domain, $singular, $plural, $count, $category, $args = null) {
731
		if (!$singular) {
732
			return;
733
		}
734
		App::uses('I18n', 'I18n');
735
		$translated = I18n::translate($singular, $plural, $domain, $category, $count);
736
		if ($args === null) {
737
			return $translated;
738
		} elseif (!is_array($args)) {
739
			$args = array_slice(func_get_args(), 5);
740
		}
741
		return vsprintf($translated, $args);
742
	}
743
744
}
745
746
if (!function_exists('__c')) {
747
748
/**
749
 * The category argument allows a specific category of the locale settings to be used for fetching a message.
750
 * Valid categories are: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.
751
 *
752
 * Note that the category must be specified with a numeric value, instead of the constant name. The values are:
753
 *
754
 * - LC_ALL       0
755
 * - LC_COLLATE   1
756
 * - LC_CTYPE     2
757
 * - LC_MONETARY  3
758
 * - LC_NUMERIC   4
759
 * - LC_TIME      5
760
 * - LC_MESSAGES  6
761
 *
762
 * @param string $msg String to translate
763
 * @param integer $category Category
764
 * @param mixed $args Array with arguments or multiple arguments in function
765
 * @return translated string
766
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#__c
767
 */
768
	function __c($msg, $category, $args = null) {
769
		if (!$msg) {
770
			return;
771
		}
772
		App::uses('I18n', 'I18n');
773
		$translated = I18n::translate($msg, null, null, $category);
774
		if ($args === null) {
775
			return $translated;
776
		} elseif (!is_array($args)) {
777
			$args = array_slice(func_get_args(), 2);
778
		}
779
		return vsprintf($translated, $args);
780
	}
781
782
}
783
784
if (!function_exists('LogError')) {
785
786
/**
787
 * Shortcut to Log::write.
788
 *
789
 * @param string $message Message to write to log
790
 * @return void
791
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#LogError
792
 */
793
	function LogError($message) {
794
		App::uses('CakeLog', 'Log');
795
		$bad = array("\n", "\r", "\t");
796
		$good = ' ';
797
		CakeLog::write('error', str_replace($bad, $good, $message));
798
	}
799
800
}
801
802
if (!function_exists('fileExistsInPath')) {
803
804
/**
805
 * Searches include path for files.
806
 *
807
 * @param string $file File to look for
808
 * @return Full path to file if exists, otherwise false
809
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#fileExistsInPath
810
 */
811
	function fileExistsInPath($file) {
812
		$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
813
		foreach ($paths as $path) {
814
			$fullPath = $path . DS . $file;
815
816
			if (file_exists($fullPath)) {
817
				return $fullPath;
818
			} elseif (file_exists($file)) {
819
				return $file;
820
			}
821
		}
822
		return false;
823
	}
824
825
}
826
827
if (!function_exists('convertSlash')) {
828
829
/**
830
 * Convert forward slashes to underscores and removes first and last underscores in a string
831
 *
832
 * @param string String to convert
833
 * @return string with underscore remove from start and end of string
834
 * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#convertSlash
835
 */
836
	function convertSlash($string) {
837
		$string = trim($string, '/');
838
		$string = preg_replace('/\/\//', '/', $string);
839
		$string = str_replace('/', '_', $string);
840
		return $string;
841
	}
842
843
}
844
845
846
function receber_data($data, $dia = true, $mes = true, $ano = true, $hora = false, $minuto = false, $segundo = false) {
847
    if ($hora || $minuto || $segundo) {
848
        $data = explode(' ', $data);
849
        $_hora = $data[1];
850
        $data = $data[0];
851
852
        $_hora = explode(':', $_hora);
853
        $_hora = ($hora ? $_hora[0] : '') . ($minuto ? ($hora ? ':' : '') . $_hora[1] : '') . ($segundo ? ($hora || $minuto ? ':' : '') . $_hora[2] : '');
854
    }
855
    $recebe = explode('-', $data);
856
    if (isset($recebe[2]) && isset($recebe[1])) {
857
        $data = ($dia ? $recebe[2] : '') . ($mes ? ($dia ? '/' : '') . $recebe[1] : '') . ($ano ? ($mes || $dia ? '/' : '') . $recebe[0] : '');
858
    }
859
860
    return $data . (isset($_hora) ? ' ' . $_hora : '');
861
}
862