Completed
Push — master ( 63f9e6...34eb4c )
by Kenji
10s
created

replacing/helpers/old/3.1.7-download_helper.php (10 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Part of ci-phpunit-test
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2015 Kenji Suzuki
8
 * @link       https://github.com/kenjis/ci-phpunit-test
9
 */
10
11
/**
12
 * CodeIgniter Download Helpers
13
 *
14
 * @package		CodeIgniter
15
 * @subpackage	Helpers
16
 * @category	Helpers
17
 * @author		Kenji Suzuki <http://github.com/kenjis/ci-phpunit-test>
18
 * @author		EllisLab Dev Team
19
 * @link		https://codeigniter.com/user_guide/helpers/download_helper.html
20
 */
21
22
// ------------------------------------------------------------------------
23
24
if ( ! function_exists('force_download'))
25
{
26
	/**
27
	 * Force Download
28
	 *
29
	 * Generates headers that force a download to happen
30
	 *
31
	 * @param	string	filename
32
	 * @param	mixed	the data to be downloaded
33
	 * @param	bool	whether to try and send the actual file MIME type
34
	 * @return	void
35
	 */
36
	function force_download($filename = '', $data = '', $set_mime = FALSE)
0 ignored issues
show
The function force_download() has been defined more than once; this definition is ignored, only the first definition in application/tests/_ci_ph...ers/download_helper.php (L36-163) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
force_download 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...
37
	{
38
		if ($filename === '' OR $data === '')
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...
39
		{
40
			return;
41
		}
42
		elseif ($data === NULL)
43
		{
44
			if ( ! @is_file($filename) OR ($filesize = @filesize($filename)) === FALSE)
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...
45
			{
46
				return;
47
			}
48
49
			$filepath = $filename;
50
			$filename = explode('/', str_replace(DIRECTORY_SEPARATOR, '/', $filename));
51
			$filename = end($filename);
52
		}
53
		else
54
		{
55
			$filesize = strlen($data);
56
		}
57
58
		// Set the default MIME type to send
59
		$mime = 'application/octet-stream';
60
61
		$x = explode('.', $filename);
62
		$extension = end($x);
63
64
		if ($set_mime === TRUE)
65
		{
66
			if (count($x) === 1 OR $extension === '')
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...
67
			{
68
				/* If we're going to detect the MIME type,
69
				 * we'll need a file extension.
70
				 */
71
				return;
72
			}
73
74
			// Load the mime types
75
			$mimes =& get_mimes();
76
77
			// Only change the default MIME if we can find one
78
			if (isset($mimes[$extension]))
79
			{
80
				$mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension];
81
			}
82
		}
83
84
		/* It was reported that browsers on Android 2.1 (and possibly older as well)
85
		 * need to have the filename extension upper-cased in order to be able to
86
		 * download it.
87
		 *
88
		 * Reference: http://digiblog.de/2011/04/19/android-and-the-download-file-headers/
89
		 */
90
		if (count($x) !== 1 && isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/Android\s(1|2\.[01])/', $_SERVER['HTTP_USER_AGENT']))
91
		{
92
			$x[count($x) - 1] = strtoupper($extension);
93
			$filename = implode('.', $x);
94
		}
95
96
		if ($data === NULL && ($fp = @fopen($filepath, 'rb')) === FALSE)
0 ignored issues
show
The variable $filepath 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...
97
		{
98
			return;
99
		}
100
101
		if (ENVIRONMENT !== 'testing')
102
		{
103
			// Clean output buffer
104
			if (ob_get_level() !== 0 && @ob_end_clean() === FALSE)
105
			{
106
				@ob_clean();
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...
107
			}
108
109
			// Generate the server headers
110
			header('Content-Type: '.$mime);
111
			header('Content-Disposition: attachment; filename="'.$filename.'"');
112
			header('Expires: 0');
113
			header('Content-Transfer-Encoding: binary');
114
			header('Content-Length: '.$filesize);
115
			header('Cache-Control: private, no-transform, no-store, must-revalidate');
116
		}
117
118
		if (ENVIRONMENT === 'testing')
119
		{
120
			$CI =& get_instance();
121
			$CI->output->set_header('Content-Type: '.$mime);
122
			$CI->output->set_header('Content-Disposition: attachment; filename="'.$filename.'"');
123
			$CI->output->set_header('Expires: 0');
124
			$CI->output->set_header('Content-Transfer-Encoding: binary');
125
			$CI->output->set_header('Content-Length: '.$filesize);
126
			$CI->output->set_header('Cache-Control: private, no-transform, no-store, must-revalidate');
127
128
			while (ob_get_level() > 2)
129
			{
130
				ob_end_clean();
131
			}
132
		}
133
134
		// If we have raw data - just dump it
135
		if ($data !== NULL)
136
		{
137
			if (ENVIRONMENT !== 'testing')
138
			{
139
				exit($data);
0 ignored issues
show
Coding Style Compatibility introduced by
The function force_download() 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...
140
			}
141
			else
142
			{
143
				echo($data);
144
				throw new CIPHPUnitTestExitException('exit() from force_download()');
145
			}
146
		}
147
148
		// Flush 1MB chunks of data
149
		while ( ! feof($fp) && ($data = fread($fp, 1048576)) !== FALSE)
0 ignored issues
show
The variable $fp 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...
150
		{
151
			echo $data;
152
		}
153
154
		fclose($fp);
155
		if (ENVIRONMENT !== 'testing')
156
		{
157
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function force_download() 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...
158
		}
159
		else
160
		{
161
			throw new CIPHPUnitTestExitException('exit() from force_download()');
162
		}
163
	}
164
}
165