GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — develop ( baac3d...439f66 )
by gyeong-won
17:54
created

FileHandler::getRemoteResource()   F

Complexity

Conditions 22
Paths > 20000

Size

Total Lines 97
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 22
eloc 51
c 1
b 0
f 0
nc 21717
nop 9
dl 0
loc 97
rs 2

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) NAVER <http://www.navercorp.com> */
3
4
/**
5
 * Contains methods for accessing file system
6
 *
7
 * @author NAVER ([email protected])
8
 */
9
class FileHandler
10
{
11
12
	/**
13
	 * Changes path of target file, directory into absolute path
14
	 *
15
	 * @param string $source path to change into absolute path
16
	 * @return string Absolute path
17
	 */
18
	function getRealPath($source)
19
	{
20
		if(strlen($source) >= 2 && substr_compare($source, './', 0, 2) === 0)
21
		{
22
			return _XE_PATH_ . substr($source, 2);
23
		}
24
25
		return $source;
26
	}
27
28
	/**
29
	 * Copy a directory to target
30
	 *
31
	 * If target directory does not exist, this function creates it
32
	 *
33
	 * @param string $source_dir Path of source directory
34
	 * @param string $target_dir Path of target dir
35
	 * @param string $filter Regex to filter files. If file matches this regex, the file is not copied.
36
	 * @param string $type If set as 'force'. Even if the file exists in target, the file is copied.
37
	 * @return void
38
	 */
39
	function copyDir($source_dir, $target_dir, $filter = null, $type = null)
40
	{
41
		$source_dir = self::getRealPath($source_dir);
42
		$target_dir = self::getRealPath($target_dir);
43
		if(!is_dir($source_dir))
44
		{
45
			return FALSE;
46
		}
47
48
		// generate when no target exists
49
		self::makeDir($target_dir);
50
51
		if(substr($source_dir, -1) != DIRECTORY_SEPARATOR)
52
		{
53
			$source_dir .= DIRECTORY_SEPARATOR;
54
		}
55
56
		if(substr($target_dir, -1) != DIRECTORY_SEPARATOR)
57
		{
58
			$target_dir .= DIRECTORY_SEPARATOR;
59
		}
60
61
		$oDir = dir($source_dir);
62
		while($file = $oDir->read())
63
		{
64
			if($file{0} == '.')
65
			{
66
				continue;
67
			}
68
69
			if($filter && preg_match($filter, $file))
0 ignored issues
show
Bug Best Practice introduced by
The expression $filter of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
70
			{
71
				continue;
72
			}
73
74
			if(is_dir($source_dir . $file))
75
			{
76
				self::copyDir($source_dir . $file, $target_dir . $file, $type);
77
			}
78
			else
79
			{
80
				if($type == 'force')
81
				{
82
					@unlink($target_dir . $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...
83
				}
84
				else
85
				{
86
					if(!file_exists($target_dir . $file))
87
					{
88
						@copy($source_dir . $file, $target_dir . $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...
89
					}
90
				}
91
			}
92
		}
93
		$oDir->close();
94
	}
95
96
	/**
97
	 * Copy a file to target
98
	 *
99
	 * @param string $source Path of source file
100
	 * @param string $target Path of target file
101
	 * @param string $force Y: overwrite
102
	 * @return void
103
	 */
104
	function copyFile($source, $target, $force = 'Y')
105
	{
106
		setlocale(LC_CTYPE, 'en_US.UTF8', 'ko_KR.UTF8');
107
		$source = self::getRealPath($source);
108
		$target_dir = self::getRealPath(dirname($target));
109
		$target = basename($target);
110
111
		self::makeDir($target_dir);
112
113
		if($force == 'Y')
114
		{
115
			@unlink($target_dir . DIRECTORY_SEPARATOR . $target);
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...
116
		}
117
118
		@copy($source, $target_dir . DIRECTORY_SEPARATOR . $target);
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...
119
	}
120
121
	/**
122
	 * Returns the content of the file
123
	 *
124
	 * @param string $filename Path of target file
125
	 * @return string The content of the file. If target file does not exist, this function returns nothing.
126
	 */
127
	function readFile($filename)
128
	{
129
		if(($filename = self::exists($filename)) === FALSE || filesize($filename) < 1)
130
		{
131
			return;
132
		}
133
134
		return @file_get_contents($filename);
135
	}
136
137
	/**
138
	 * Write $buff into the specified file
139
	 *
140
	 * @param string $filename Path of target file
141
	 * @param string $buff Content to be written
142
	 * @param string $mode a(append) / w(write)
143
	 * @return void
144
	 */
145
	function writeFile($filename, $buff, $mode = "w")
146
	{
147
		$filename = self::getRealPath($filename);
148
		$pathinfo = pathinfo($filename);
149
		self::makeDir($pathinfo['dirname']);
150
151
		$flags = 0;
152
		if(strtolower($mode) == 'a')
153
		{
154
			$flags = FILE_APPEND;
155
		}
156
157
		@file_put_contents($filename, $buff, $flags|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...
158
		@chmod($filename, 0644);
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...
159
	}
160
161
	/**
162
	 * Remove a file
163
	 *
164
	 * @param string $filename path of target file
165
	 * @return bool Returns TRUE on success or FALSE on failure.
166
	 */
167
	function removeFile($filename)
168
	{
169
		return (($filename = self::exists($filename)) !== FALSE) && @unlink($filename);
170
	}
171
172
	/**
173
	 * Rename a file
174
	 *
175
	 * In order to move a file, use this function.
176
	 *
177
	 * @param string $source Path of source file
178
	 * @param string $target Path of target file
179
	 * @return bool Returns TRUE on success or FALSE on failure.
180
	 */
181
	function rename($source, $target)
182
	{
183
		return @rename(self::getRealPath($source), self::getRealPath($target));
184
	}
185
186
	/**
187
	 * Move a file
188
	 *
189
	 * @param string $source Path of source file
190
	 * @param string $target Path of target file
191
	 * @return bool Returns TRUE on success or FALSE on failure.
192
	 */
193
	function moveFile($source, $target)
194
	{
195
		if(($source = self::exists($source)) !== FALSE)
196
		{
197
			self::removeFile($target);
198
			return self::rename($source, $target);
199
		}
200
		return FALSE;
201
	}
202
203
	/**
204
	 * Move a directory
205
	 *
206
	 * This function just wraps rename function.
207
	 *
208
	 * @param string $source_dir Path of source directory
209
	 * @param string $target_dir Path of target directory
210
	 * @return void
211
	 */
212
	function moveDir($source_dir, $target_dir)
213
	{
214
		self::rename($source_dir, $target_dir);
215
	}
216
217
	/**
218
	 * Return list of the files in the path
219
	 *
220
	 * The array does not contain files, such as '.', '..', and files starting with '.'
221
	 *
222
	 * @param string $path Path of target directory
223
	 * @param string $filter If specified, return only files matching with the filter
224
	 * @param bool $to_lower If TRUE, file names will be changed into lower case.
225
	 * @param bool $concat_prefix If TRUE, return file name as absolute path
226
	 * @return string[] Array of the filenames in the path
227
	 */
228
	function readDir($path, $filter = '', $to_lower = FALSE, $concat_prefix = FALSE)
229
	{
230
		$path = self::getRealPath($path);
231
		$output = array();
232
233
		if(substr($path, -1) != '/')
234
		{
235
			$path .= '/';
236
		}
237
238
		if(!is_dir($path))
239
		{
240
			return $output;
241
		}
242
243
		$files = scandir($path);
244
		foreach($files as $file)
245
		{
246
			if($file{0} == '.' || ($filter && !preg_match($filter, $file)))
247
			{
248
				continue;
249
			}
250
251
			if($to_lower)
252
			{
253
				$file = strtolower($file);
254
			}
255
256
			if($filter)
257
			{
258
				$file = preg_replace($filter, '$1', $file);
259
			}
260
261
			if($concat_prefix)
262
			{
263
				$file = sprintf('%s%s', str_replace(_XE_PATH_, '', $path), $file);
264
			}
265
266
			$output[] = str_replace(array('/\\', '//'), '/', $file);
267
		}
268
269
		return $output;
270
	}
271
272
	/**
273
	 * Creates a directory
274
	 *
275
	 * This function creates directories recursively, which means that if ancestors of the target directory does not exist, they will be created too.
276
	 *
277
	 * @param string $path_string Path of target directory
278
	 * @return bool TRUE if success. It might return nothing when ftp is used and connection to the ftp address failed.
279
	 */
280
	function makeDir($path_string)
281
	{
282
		if(self::exists($path_string) !== FALSE)
283
		{
284
			return TRUE;
285
		}
286
287
		if(!ini_get('safe_mode'))
288
		{
289
			@mkdir($path_string, 0755, TRUE);
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...
290
			@chmod($path_string, 0755);
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...
291
		}
292
		// if safe_mode is on, use FTP
293
		else
294
		{
295
			static $oFtp = NULL;
296
297
			$ftp_info = Context::getFTPInfo();
298
			if($oFtp == NULL)
299
			{
300
				if(!Context::isFTPRegisted())
301
				{
302
					return;
303
				}
304
305
				require_once(_XE_PATH_ . 'libs/ftp.class.php');
306
				$oFtp = new ftp();
307
				if(!$ftp_info->ftp_host)
308
				{
309
					$ftp_info->ftp_host = "127.0.0.1";
310
				}
311
				if(!$ftp_info->ftp_port)
312
				{
313
					$ftp_info->ftp_port = 21;
314
				}
315
				if(!$oFtp->ftp_connect($ftp_info->ftp_host, $ftp_info->ftp_port))
316
				{
317
					return;
318
				}
319
				if(!$oFtp->ftp_login($ftp_info->ftp_user, $ftp_info->ftp_password))
320
				{
321
					$oFtp->ftp_quit();
322
					return;
323
				}
324
			}
325
326
			if(!($ftp_path = $ftp_info->ftp_root_path))
327
			{
328
				$ftp_path = DIRECTORY_SEPARATOR;
329
			}
330
331
			$path_string = str_replace(_XE_PATH_, '', $path_string);
332
			$path_list = explode(DIRECTORY_SEPARATOR, $path_string);
333
334
			$path = _XE_PATH_;
335
			for($i = 0, $c = count($path_list); $i < $c; $i++)
336
			{
337
				if(!$path_list[$i])
338
				{
339
					continue;
340
				}
341
342
				$path .= $path_list[$i] . DIRECTORY_SEPARATOR;
343
				$ftp_path .= $path_list[$i] . DIRECTORY_SEPARATOR;
344
				if(!is_dir($path))
345
				{
346
					$oFtp->ftp_mkdir($ftp_path);
347
					$oFtp->ftp_site("CHMOD 777 " . $ftp_path);
348
				}
349
			}
350
		}
351
352
		return is_dir($path_string);
353
	}
354
355
	/**
356
	 * Remove all files under the path
357
	 *
358
	 * @param string $path Path of the target directory
359
	 * @return void
360
	 */
361 View Code Duplication
	function removeDir($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
362
	{
363
		if(($path = self::isDir($path)) === FALSE)
364
		{
365
			return;
366
		}
367
368
		if(self::isDir($path))
0 ignored issues
show
Bug Best Practice introduced by
The expression self::isDir($path) of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
369
		{
370
			$files = array_diff(scandir($path), array('..', '.'));
371
372
			foreach($files as $file)
373
			{
374
				if(($target = self::getRealPath($path . DIRECTORY_SEPARATOR . $file)) === FALSE)
375
				{
376
					continue;
377
				}
378
379
				if(is_dir($target))
380
				{
381
					self::removeDir($target);
382
				}
383
				else
384
				{
385
					unlink($target);
386
				}
387
			}
388
			rmdir($path);
389
		}
390
		else
391
		{
392
			unlink($path);
393
		}
394
	}
395
396
	/**
397
	 * Remove a directory only if it is empty
398
	 *
399
	 * @param string $path Path of the target directory
400
	 * @return void
401
	 */
402
	function removeBlankDir($path)
403
	{
404
		if(($path = self::isDir($path)) === FALSE)
405
		{
406
			return;
407
		}
408
409
		$files = array_diff(scandir($path), array('..', '.'));
410
411
		if(count($files) < 1)
412
		{
413
			rmdir($path);
414
			return;
415
		}
416
417
		foreach($files as $file)
418
		{
419
			if(($target = self::isDir($path . DIRECTORY_SEPARATOR . $file)) === FALSE)
420
			{
421
				continue;
422
			}
423
424
			self::removeBlankDir($target);
425
		}
426
	}
427
428
	/**
429
	 * Remove files in the target directory
430
	 *
431
	 * This function keeps the directory structure.
432
	 *
433
	 * @param string $path Path of the target directory
434
	 * @return void
435
	 */
436 View Code Duplication
	function removeFilesInDir($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
437
	{
438
		if(($path = self::getRealPath($path)) === FALSE)
439
		{
440
			return;
441
		}
442
443
		if(is_dir($path))
444
		{
445
			$files = array_diff(scandir($path), array('..', '.'));
446
447
			foreach($files as $file)
448
			{
449
				if(($target = self::getRealPath($path . DIRECTORY_SEPARATOR . $file)) === FALSE)
450
				{
451
					continue;
452
				}
453
454
				if(is_dir($target))
455
				{
456
					self::removeFilesInDir($target);
457
				}
458
				else
459
				{
460
					unlink($target);
461
				}
462
			}
463
		}
464
		else
465
		{
466
			if(self::exists($path)) unlink($path);
0 ignored issues
show
Bug Best Practice introduced by
The expression self::exists($path) of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
467
		}
468
469
	}
470
471
	/**
472
	 * Makes file size byte into KB, MB according to the size
473
	 *
474
	 * @see self::returnBytes()
475
	 * @param int $size Number of the size
476
	 * @return string File size string
477
	 */
478
	function filesize($size)
479
	{
480
		if(!$size)
481
		{
482
			return '0Byte';
483
		}
484
485
		if($size === 1)
486
		{
487
			return '1Byte';
488
		}
489
490
		if($size < 1024)
491
		{
492
			return $size . 'Bytes';
493
		}
494
495
		if($size >= 1024 && $size < 1024 * 1024)
496
		{
497
			return sprintf("%0.1fKB", $size / 1024);
498
		}
499
500
		return sprintf("%0.2fMB", $size / (1024 * 1024));
501
	}
502
503
	/**
504
	 * Return remote file's content via HTTP
505
	 *
506
	 * If the target is moved (when return code is 300~399), this function follows the location specified response header.
507
	 *
508
	 * @param string $url The address of the target file
509
	 * @param string $body HTTP request body
510
	 * @param int $timeout Connection timeout
511
	 * @param string $method GET/POST
512
	 * @param string $content_type Content type header of HTTP request
513
	 * @param string[] $headers Headers key value array.
514
	 * @param string[] $cookies Cookies key value array.
515
	 * @param string $post_data Request arguments array for POST method
516
	 * @return string If success, the content of the target file. Otherwise: none
517
	 */
518
	function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array(), $request_config = array())
519
	{
520
		require_once(_XE_PATH_ . 'libs/idna_convert/idna_convert.class.php');
521
		$IDN = new idna_convert(array('idn_version' => 2008));
522
		$url = $IDN->encode($url);
523
524
		try
525
		{
526
			requirePear();
527
			require_once('HTTP/Request.php');
528
529
			$parsed_url = parse_url(__PROXY_SERVER__);
530
			if($parsed_url["host"])
531
			{
532
				$oRequest = new HTTP_Request(__PROXY_SERVER__);
533
				$oRequest->setMethod('POST');
534
				$oRequest->addPostData('arg', serialize(array('Destination' => $url, 'method' => $method, 'body' => $body, 'content_type' => $content_type, "headers" => $headers, "post_data" => $post_data)));
535
			}
536
			else
537
			{
538
				$oRequest = new HTTP_Request($url);
0 ignored issues
show
Security Bug introduced by
It seems like $url defined by $IDN->encode($url) on line 522 can also be of type false; however, HTTP_Request2::__construct() does only seem to accept string|object<Net_URL2>|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...
539
540
				if(count($request_config) && method_exists($oRequest, 'setConfig'))
541
				{
542
					foreach($request_config as $key=>$val)
543
					{
544
						$oRequest->setConfig($key, $val);
545
					}
546
				}
547
548
				if(count($headers) > 0)
549
				{
550
					foreach($headers as $key => $val)
551
					{
552
						$oRequest->addHeader($key, $val);
553
					}
554
				}
555
				if($cookies[$host])
556
				{
557
					foreach($cookies[$host] as $key => $val)
0 ignored issues
show
Bug introduced by
The variable $host does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The expression $cookies[$host] of type string is not traversable.
Loading history...
558
					{
559
						$oRequest->addCookie($key, $val);
560
					}
561
				}
562
				if(count($post_data) > 0)
563
				{
564
					foreach($post_data as $key => $val)
0 ignored issues
show
Bug introduced by
The expression $post_data of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
565
					{
566
						$oRequest->addPostData($key, $val);
567
					}
568
				}
569
				if(!$content_type)
0 ignored issues
show
Bug Best Practice introduced by
The expression $content_type of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
570
					$oRequest->addHeader('Content-Type', 'text/html');
571
				else
572
					$oRequest->addHeader('Content-Type', $content_type);
573
				$oRequest->setMethod($method);
574
				if($body)
0 ignored issues
show
Bug Best Practice introduced by
The expression $body of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
575
					$oRequest->setBody($body);
576
			}
577
			
578
			if(method_exists($oRequest, 'setConfig'))
579
			{
580
				$oRequest->setConfig('timeout', $timeout);
581
			}
582
			elseif(property_exists($oRequest, '_timeout'))
583
			{
584
				$oRequest->_timeout = $timeout;
0 ignored issues
show
Bug introduced by
The property _timeout does not seem to exist in HTTP_Request.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
585
			}
586
587
			$oResponse = $oRequest->sendRequest();
0 ignored issues
show
Unused Code introduced by
$oResponse is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
588
589
			$code = $oRequest->getResponseCode();
590
			$header = $oRequest->getResponseHeader();
591
			$response = $oRequest->getResponseBody();
592
			if($c = $oRequest->getResponseCookies())
593
			{
594
				foreach($c as $k => $v)
595
				{
596
					$cookies[$host][$v['name']] = $v['value'];
597
				}
598
			}
599
600
			if($code > 300 && $code < 399 && $header['location'])
601
			{
602
				return self::getRemoteResource($header['location'], $body, $timeout, $method, $content_type, $headers, $cookies, $post_data);
603
			}
604
605
			if($code != 200)
606
				return;
607
608
			return $response;
609
		}
610
		catch(Exception $e)
611
		{
612
			return NULL;
613
		}
614
	}
615
616
	/**
617
	 * Retrieves remote file, then stores it into target path.
618
	 *
619
	 * @param string $url The address of the target file
620
	 * @param string $target_filename The location to store
621
	 * @param string $body HTTP request body
622
	 * @param string $timeout Connection timeout
623
	 * @param string $method GET/POST
624
	 * @param string $content_type Content type header of HTTP request
625
	 * @param string[] $headers Headers key value array.
626
	 * @return bool TRUE: success, FALSE: failed
627
	 */
628
	function getRemoteFile($url, $target_filename, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array(), $request_config = array())
629
	{
630
		if(!($body = self::getRemoteResource($url, $body, $timeout, $method, $content_type, $headers,$cookies,$post_data,$request_config)))
631
		{
632
			return FALSE;
633
		}
634
635
		self::writeFile($target_filename, $body);
636
		return TRUE;
637
	}
638
639
	/**
640
	 * Convert size in string into numeric value
641
	 *
642
	 * @see self::filesize()
643
	 * @param $val Size in string (ex., 10, 10K, 10M, 10G )
644
	 * @return int converted size
645
	 */
646
	function returnBytes($val)
647
	{
648
		$unit = strtoupper(substr($val, -1));
649
		$val = (float)$val;
650
651
		switch ($unit)
652
		{
653
			case 'G': $val *= 1024;
654
			case 'M': $val *= 1024;
655
			case 'K': $val *= 1024;
656
		}
657
658
		return round($val);
659
	}
660
661
	/**
662
	 * Check available memory to load image file
663
	 *
664
	 * @param array $imageInfo Image info retrieved by getimagesize function
665
	 * @return bool TRUE: it's ok, FALSE: otherwise
666
	 */
667
	function checkMemoryLoadImage(&$imageInfo)
668
	{
669
		$K64 = 65536;
670
		$TWEAKFACTOR = 2.0;
671
		$channels = $imageInfo['channels'];
672
		if(!$channels)
673
		{
674
			$channels = 6; //for png
675
		}
676
		$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $channels / 8 + $K64 ) * $TWEAKFACTOR);
677
		$availableMemory = self::returnBytes(ini_get('memory_limit')) - memory_get_usage();
678
		if($availableMemory < $memoryNeeded)
679
		{
680
			return FALSE;
681
		}
682
		return TRUE;
683
	}
684
685
	/**
686
	 * Moves an image file (resizing is possible)
687
	 *
688
	 * @param string $source_file Path of the source file
689
	 * @param string $target_file Path of the target file
690
	 * @param int $resize_width Width to resize
691
	 * @param int $resize_height Height to resize
692
	 * @param string $target_type If $target_type is set (gif, jpg, png, bmp), result image will be saved as target type
693
	 * @param string $thumbnail_type Thumbnail type(crop, ratio)
694
	 * @return bool TRUE: success, FALSE: failed
695
	 */
696
	function createImageFile($source_file, $target_file, $resize_width = 0, $resize_height = 0, $target_type = '', $thumbnail_type = 'crop')
697
	{
698
		// check params
699
		if (($source_file = self::exists($source_file)) === FALSE)
700
		{
701
			return;
702
		}
703
704
		$target_file = self::getRealPath($target_file);
705
		if(!$resize_width)
706
		{
707
			$resize_width = 100;
708
		}
709
710
		if(!$resize_height)
711
		{
712
			$resize_height = $resize_width;
713
		}
714
715
		// retrieve source image's information
716
		$imageInfo = getimagesize($source_file);
717
		if(!self::checkMemoryLoadImage($imageInfo))
718
		{
719
			return FALSE;
720
		}
721
722
		list($width, $height, $type, $attrs) = $imageInfo;
0 ignored issues
show
Unused Code introduced by
The assignment to $attrs is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
723
		if($width < 1 || $height < 1)
724
		{
725
			return;
726
		}
727
728
		switch($type)
729
		{
730
			case '1' :
731
				$type = 'gif';
732
				break;
733
			case '2' :
734
				$type = 'jpg';
735
				break;
736
			case '3' :
737
				$type = 'png';
738
				break;
739
			case '6' :
740
				$type = 'bmp';
741
				break;
742
			default :
743
				return;
744
		}
745
746
		if(!$target_type)
747
		{
748
			$target_type = $type;
749
		}
750
		$target_type = strtolower($target_type);
751
752
		// if original image is larger than specified size to resize, calculate the ratio
753
		$width_per = ($resize_width > 0 && $width >= $resize_width) ? $resize_width / $width : 1;
754
		$height_per = ($resize_height > 0 && $height >= $resize_height) ? $resize_height / $height : 1;
755
756
		$per = NULL;
0 ignored issues
show
Unused Code introduced by
$per is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
757
		if($thumbnail_type == 'ratio')
758
		{
759
			$per = ($width_per > $height_per) ? $height_per : $width_per;
760
			$resize_width = $width * $per;
761
			$resize_height = $height * $per;
762
		}
763
		else
764
		{
765
			$per = ($width_per < $height_per) ? $height_per : $width_per;
766
		}
767
768
		// create temporary image with target size
769
		$thumb = NULL;
770
		if(function_exists('imagecreateTRUEcolor'))
771
		{
772
			$thumb = imagecreateTRUEcolor($resize_width, $resize_height);
773
		}
774
		else if(function_exists('imagecreate'))
775
		{
776
			$thumb = imagecreate($resize_width, $resize_height);
777
		}
778
779
		if(!$thumb)
780
		{
781
			return FALSE;
782
		}
783
784
		imagefilledrectangle($thumb, 0, 0, $resize_width - 1, $resize_height - 1, imagecolorallocate($thumb, 255, 255, 255));
785
786
		// create temporary image having original type
787
		$source = NULL;
788
		switch($type)
789
		{
790
			case 'gif' :
791
				if(function_exists('imagecreatefromgif'))
792
				{
793
					$source = @imagecreatefromgif($source_file);
794
				}
795
				break;
796
			case 'jpeg' :
797
			case 'jpg' :
798
				if(function_exists('imagecreatefromjpeg'))
799
				{
800
					$source = @imagecreatefromjpeg($source_file);
801
				}
802
				break;
803
			case 'png' :
804
				if(function_exists('imagecreatefrompng'))
805
				{
806
					$source = @imagecreatefrompng($source_file);
807
				}
808
				break;
809
			case 'wbmp' :
810
			case 'bmp' :
811
				if(function_exists('imagecreatefromwbmp'))
812
				{
813
					$source = @imagecreatefromwbmp($source_file);
814
				}
815
				break;
816
		}
817
818
		if(!$source)
819
		{
820
			imagedestroy($thumb);
821
			return FALSE;
822
		}
823
824
		// resize original image and put it into temporary image
825
		$new_width = (int) ($width * $per);
826
		$new_height = (int) ($height * $per);
827
828
		$x = 0;
829
		$y = 0;
830
		if($thumbnail_type == 'crop')
831
		{
832
			$x = (int) ($resize_width / 2 - $new_width / 2);
833
			$y = (int) ($resize_height / 2 - $new_height / 2);
834
		}
835
836
		if(function_exists('imagecopyresampled'))
837
		{
838
			imagecopyresampled($thumb, $source, $x, $y, 0, 0, $new_width, $new_height, $width, $height);
839
		}
840
		else
841
		{
842
			imagecopyresized($thumb, $source, $x, $y, 0, 0, $new_width, $new_height, $width, $height);
843
		}
844
845
		// create directory
846
		self::makeDir(dirname($target_file));
847
848
		// write into the file
849
		$output = NULL;
850
		switch($target_type)
851
		{
852
			case 'gif' :
853
				if(function_exists('imagegif'))
854
				{
855
					$output = imagegif($thumb, $target_file);
856
				}
857
				break;
858
			case 'jpeg' :
859
			case 'jpg' :
860
				if(function_exists('imagejpeg'))
861
				{
862
					$output = imagejpeg($thumb, $target_file, 100);
863
				}
864
				break;
865
			case 'png' :
866
				if(function_exists('imagepng'))
867
				{
868
					$output = imagepng($thumb, $target_file, 9);
869
				}
870
				break;
871
			case 'wbmp' :
872
			case 'bmp' :
873
				if(function_exists('imagewbmp'))
874
				{
875
					$output = imagewbmp($thumb, $target_file, 100);
876
				}
877
				break;
878
		}
879
880
		imagedestroy($thumb);
881
		imagedestroy($source);
882
883
		if(!$output)
0 ignored issues
show
Bug Best Practice introduced by
The expression $output of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
884
		{
885
			return FALSE;
886
		}
887
		@chmod($target_file, 0644);
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...
888
889
		return TRUE;
890
	}
891
892
	/**
893
	 * Reads ini file, and puts result into array
894
	 *
895
	 * @see self::writeIniFile()
896
	 * @param string $filename Path of the ini file
897
	 * @return array ini array (if the target file does not exist, it returns FALSE)
898
	 */
899
	function readIniFile($filename)
900
	{
901
		if(($filename = self::exists($filename)) === FALSE)
902
		{
903
			return FALSE;
904
		}
905
		$arr = parse_ini_file($filename, TRUE);
906
		if(is_array($arr) && count($arr) > 0)
907
		{
908
			return $arr;
909
		}
910
		else
911
		{
912
			return array();
913
		}
914
	}
915
916
	/**
917
	 * Write array into ini file
918
	 *
919
	 * 	$ini['key1'] = 'value1';<br/>
920
	 * 	$ini['key2'] = 'value2';<br/>
921
	 * 	$ini['section']['key1_in_section'] = 'value1_in_section';<br/>
922
	 * 	$ini['section']['key2_in_section'] = 'value2_in_section';<br/>
923
	 * 	self::writeIniFile('exmple.ini', $ini);
924
	 *
925
	 * @see self::readIniFile()
926
	 * @param string $filename Target ini file name
927
	 * @param array $arr Array
928
	 * @return bool if array contains nothing it returns FALSE, otherwise TRUE
929
	 */
930
	function writeIniFile($filename, $arr)
931
	{
932
		if(!is_array($arr) || count($arr) == 0)
933
		{
934
			return FALSE;
935
		}
936
		self::writeFile($filename, self::_makeIniBuff($arr));
937
		return TRUE;
938
	}
939
940
	/**
941
	 * Make array to ini string
942
	 *
943
	 * @param array $arr Array
944
	 * @return string
945
	 */
946
	function _makeIniBuff($arr)
947
	{
948
		$return = array();
949
		foreach($arr as $key => $val)
950
		{
951
			// section
952
			if(is_array($val))
953
			{
954
				$return[] = sprintf("[%s]", $key);
955
				foreach($val as $k => $v)
956
				{
957
					$return[] = sprintf("%s=\"%s\"", $k, $v);
958
				}
959
				// value
960
			}
961
			else if(is_object($val))
962
			{
963
				continue;
964
			}
965
			else
966
			{
967
				$return[] = sprintf("%s=\"%s\"", $key, $val);
968
			}
969
		}
970
971
		return join("\n", $return);
972
	}
973
974
	/**
975
	 * Returns a file object
976
	 *
977
	 * If the directory of the file does not exist, create it.
978
	 *
979
	 * @param string $filename Target file name
980
	 * @param string $mode File mode for fopen
981
	 * @return FileObject File object
982
	 */
983
	function openFile($filename, $mode)
984
	{
985
		$pathinfo = pathinfo($filename);
986
		self::makeDir($pathinfo['dirname']);
987
988
		require_once("FileObject.class.php");
989
		return  new FileObject($filename, $mode);
990
	}
991
992
	/**
993
	 * Check whether the given file has the content.
994
	 *
995
	 * @param string $filename Target file name
996
	 * @return bool Returns TRUE if the file exists and contains something.
997
	 */
998
	function hasContent($filename)
999
	{
1000
		return (is_readable($filename) && (filesize($filename) > 0));
1001
	}
1002
1003
	/**
1004
	 * Check file exists.
1005
	 *
1006
	 * @param string $filename Target file name
1007
	 * @return bool Returns FALSE if the file does not exists, or Returns full path file(string).
1008
	 */
1009
	function exists($filename)
1010
	{
1011
		$filename = self::getRealPath($filename);
1012
		return file_exists($filename) ? $filename : FALSE;
1013
	}
1014
1015
	/**
1016
	 * Check it is dir
1017
	 *
1018
	 * @param string $dir Target dir path
0 ignored issues
show
Bug introduced by
There is no parameter named $dir. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1019
	 * @return bool Returns FALSE if the dir is not dir, or Returns full path of dir(string).
1020
	 */
1021
	function isDir($path)
1022
	{
1023
		$path = self::getRealPath($path);
1024
		return is_dir($path) ? $path : FALSE;
1025
	}
1026
1027
	/**
1028
	 * Check is writable dir
1029
	 *
1030
	 * @param string $path Target dir path
1031
	 * @return bool
1032
	 */
1033
	function isWritableDir($path)
1034
	{
1035
		$path = self::getRealPath($path);
1036
		if(is_dir($path)==FALSE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1037
		{
1038
			return FALSE;
1039
		}
1040
1041
		$checkFile = $path . '/_CheckWritableDir';
1042
1043
		$fp = fopen($checkFile, 'w');
1044
		if(!is_resource($fp))
1045
		{
1046
			return FALSE;
1047
		}
1048
		fclose($fp);
1049
1050
		self::removeFile($checkFile);
1051
		return TRUE;
1052
	}
1053
}
1054
1055
/* End of file FileHandler.class.php */
1056
/* Location: ./classes/file/FileHandler.class.php */
1057