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 — dev ( b6442a...4385af )
by w3l
06:19
created

Misc::autoCorrectParseUrl()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 16
rs 9.2
cc 4
eloc 9
nc 4
nop 1
1
<?php
2
namespace w3l\Holt45;
3
trait Misc {
4
	
5
	/**
6
	 * Convert ISO 3166-1 alpha-2 code to (English) country name.
7
	 *
8
	 * @link https://gist.github.com/IngmarBoddington/5909709 Source
9
	 *
10
	 * @param string $key ISO 3166-1 alpha-2 code
11
	 * @return string Country name OR $key if no match.
12
	 */
13
	public static function iso3166ToName($key) {
14
	
15
		$countries = self::getCountriesList();
16
17
		return ((array_key_exists($key, $countries)) ? $countries[$key] : $key);
18
	}
19
		
20
	/**
21
	* To replace "Hallo [@var] world" with $value.
22
	*
23
	* @example replace_string($string, array("val1" => "foo", "val2" => "bar"))
24
	*
25
	* @param string $lang_string String containing placeholder.
26
	* @return string String with placeholder replaced.
27
	*/
28
	public static function replaceString($lang_string, $dynamic_content = array()) {
29
30
		foreach ($dynamic_content as $k => $v) {
31
			$lang_string = str_replace("[@".$k."]", $v, $lang_string);
32
		}
33
		return $lang_string;
34
	}
35
	
36
	/**
37
	 * Get client ip-address
38
	 *
39
	 * @return string User ip-address
40
	 */
41
	public static function getClientIpAddress() {
42
43
		if (getenv('HTTP_CLIENT_IP'))
44
			return getenv('HTTP_CLIENT_IP');
45
		else if(getenv('HTTP_X_FORWARDED_FOR'))
46
			return getenv('HTTP_X_FORWARDED_FOR');
47
		else if(getenv('HTTP_X_FORWARDED'))
48
			return getenv('HTTP_X_FORWARDED');
49
		else if(getenv('HTTP_FORWARDED_FOR'))
50
			return getenv('HTTP_FORWARDED_FOR');
51
		else if(getenv('HTTP_FORWARDED'))
52
			return getenv('HTTP_FORWARDED');
53
		else if(getenv('REMOTE_ADDR'))
54
			return getenv('REMOTE_ADDR');
55
		else
56
			return '127.0.0.1'; // Unknown IP
57
	}
58
59
	/**
60
	 * Tries to auto-correct parse_url()-output.
61
	 *
62
	 * @param string $url
63
	 * @return array
64
	 */
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,string>|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
65
	
66
	private static function autoCorrectParseUrl($url) {
67
		// multiple /// messes up parse_url, replace 3 or more with 2
68
		$url = preg_replace('/(\/{2,})/','//',$url);
69
		
70
		$parse_url = parse_url($url);
71
		
72
		if(empty($parse_url["scheme"])) {
73
			$parse_url["scheme"] = "http";
74
		}
75
		if(empty($parse_url["host"]) && !empty($parse_url["path"])) {
76
			// Strip slash from the beginning of path
77
			$parse_url["host"] = ltrim($parse_url["path"], '\/');
78
			$parse_url["path"] = "";
79
		}
80
		return $parse_url;
81
	}
82
83
	/**
84
	 * parse url, try to correct errors and return valid url + display-url.
85
	 *
86
	 * @example http:/wwww.example.com/lorum.html => http://www.example.com/lorum.html
87
	 * @example gopher:/ww.example.com => gopher://www.example.com
88
	 * @example http:/www3.example.com/?q=asd&f=#asd =>http://www3.example.com/?q=asd&f=#asd
89
	 * @example asd://.example.com/folder/folder/ =>http://example.com/folder/folder/
90
	 * @example .example.com/ => http://example.com/
91
	 * @example example.com =>http://example.com
92
	 * @example subdomain.example.com => http://subdomain.example.com
93
	 *
94
	 * @param string $url Any somewhat valid url.
95
	 * @return string[] "url" contains an auto-corrected url. "url_display" host.tld or subdomain.host.tld
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,string>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
96
	 */
97
	public static function urlParser($url) {
98
		
99
		$parse_url = self::autoCorrectParseUrl($url);
100
101
		$url_array = array("url" => "", "url_display" => "");
102
		
103
		// Check if scheme is correct
104
		if(!in_array($parse_url["scheme"], array("http", "https", "gopher"))) {
105
			$url_array["url"] .= 'http'.'://';
106
		} else {
107
			$url_array["url"] .= $parse_url["scheme"].'://';
108
		}
109
		
110
		// Check if the right amount of "www" is set.
111
		$explode_host = explode(".", $parse_url["host"]);
112
		
113
		// Remove empty entries
114
		$explode_host = array_filter($explode_host);
115
		// And reassign indexes
116
		$explode_host = array_values($explode_host);
117
		
118
		// Contains subdomain
119
		if(count($explode_host) > 2) {
120
			// Check if subdomain only contains the letter w(then not any other subdomain).
121
			if(substr_count($explode_host[0], 'w') == strlen($explode_host[0])) {
122
				// Replace with "www" to avoid "ww" or "wwww", etc.
123
				$explode_host[0] = "www";
124
				
125
			}
126
		}
127
128
		$url_array["url"] .= implode(".",$explode_host);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
129
		$url_array["url_display"] = trim(implode(".",$explode_host), '\/'); // Removes trailing slash
130
		
131
		if(!empty($parse_url["port"])) {
132
			$url_array["url"] .= ":".$parse_url["port"];
133
		}
134
		if(!empty($parse_url["path"])) {
135
			$url_array["url"] .= $parse_url["path"];
136
		}
137
		if(!empty($parse_url["query"])) {
138
			$url_array["url"] .= '?'.$parse_url["query"];
139
		}
140
		if(!empty($parse_url["fragment"])) {
141
			$url_array["url"] .= '#'.$parse_url["fragment"];
142
		}
143
144
		
145
		return $url_array;
146
	}
147
	
148
	/**
149
	 * Generate a password-suggestion.
150
	 *
151
	 * @param int $length Length of password
152
	 * @param bool $simple Limit character-set to first 33 characters.
153
	 * @return string
154
	 */
155
	public static function generatePassword($length = 8, $simple = false) {
156
		$character_set = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ!#%+:=?@";
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
157
		$character_set_lenght = (($simple) ? 33 : 64);
158
		
159
		$counter = 0;
160
		
161
		while($counter < 10) {
162
		
163
			$suggested_password = "";
164
			
165
			for($i = 0; $i < $length; $i++) {
166
				$suggested_password .= $character_set[rand(0,($character_set_lenght-1))];
167
			}
168
169
			if(strlen(count_chars($suggested_password, 3)) > ($length-2)) {
170
				break;
171
			}
172
			
173
			$counter++;
174
		}
175
		
176
		return $suggested_password;
0 ignored issues
show
Bug introduced by
The variable $suggested_password 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...
177
		
178
	}
179
	
180
	/**
181
	 * Obfuscate string (url-safe and somewhat hard to guess).
182
	 *
183
	 * @param string $input The text that should be obfuscated
184
	 * @return string Obfuscated string
185
	 */
186
	function obfuscateString($input) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
187
		return bin2hex(base64_encode(strrev($input)));
188
	}
189
190
	/**
191
	 * Deobfuscate string
192
	 *
193
	 * @param string $input Obfuscated string
194
	 * @return string Deobfuscated string
195
	 */
196
	function deobfuscateString($input) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
197
		return strrev(base64_decode(hex2bin($input)));
198
	}
199
	
200
	/**
201
	 * Convert <textarea> to [textarea].
202
	 *
203
	 * @param string $html
204
	 * @return string
205
	 */
206
	public static function textareaEncode($html) {
207
		return preg_replace("/<textarea(.*?)>(.*?)<\/textarea>/is", "[textarea$1]$2[/textarea]", $html);
208
	}
209
	
210
	/**
211
	 * Convert [textarea] to <textarea>.
212
	 *
213
	 * @param string $html
214
	 * @return string
215
	 */
216
	public static function textareaDecode($html) {
217
		return preg_replace("/\[textarea(.*?)\](.*?)\[\/textarea\]/is", "<textarea$1>$2</textarea>", $html);
218
	}
219
	
220
	/**
221
	 * Create range for pagination
222
	 *
223
	 * @param int $total_pages
224
	 * @param int $selected_page
225
	 * @param int $number_of_results
226
	 * @return array Array with all page-numbers limited by $number_of_results
227
	 */
228
	public static function generatePaginationRange($total_pages,$selected_page = 1,$number_of_results = 7) {
229
230
		// Get the numbers
231
		$temp_array_range = range(1, $total_pages);
232
		
233
		if($total_pages <= $number_of_results) {
234
			// all
235
			$array_data = $temp_array_range;
236 View Code Duplication
		} elseif($selected_page <= (round(($number_of_results / 2), 0, PHP_ROUND_HALF_UP))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
237
			// 1-6+last
238
			$array_data = array_slice($temp_array_range, 0, ($number_of_results-1));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
239
			$array_data[] = $total_pages;
240
			
241
		} elseif($selected_page >= $total_pages-round(($number_of_results / 2), 0, PHP_ROUND_HALF_DOWN)) {
242
			// first + $total_pages-5 - $total_pages
243
			$array_data = array_slice($temp_array_range, $total_pages-($number_of_results-1));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
244
			$array_data[] = 1;
245 View Code Duplication
		} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
246
			// first + $total_pages-2 - $total_pages+2 + last
247
			$array_data = array_slice($temp_array_range, $selected_page-(round(($number_of_results / 2), 0, PHP_ROUND_HALF_DOWN)), ($number_of_results-2));
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 146 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
248
			$array_data[] = 1;
249
			$array_data[] = $total_pages;
250
			
251
		}
252
		
253
		sort($array_data);
254
		
255
		return $array_data;
256
		
257
	}
258
259
	
260
}