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 — 2.9 ( b9cdad...2e7f5b )
by Thorsten
13:19
created

PMF_Utils::isForbiddenElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 7
c 1
b 1
f 0
nc 2
nop 1
dl 0
loc 12
rs 9.4285
1
<?php
2
3
/**
4
 * Utilities - Functions and Classes common to the whole phpMyFAQ architecture.
5
 *
6
 * PHP Version 5.5
7
 *
8
 * This Source Code Form is subject to the terms of the Mozilla Public License,
9
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
10
 * obtain one at http://mozilla.org/MPL/2.0/.
11
 *
12
 * @category  phpMyFAQ
13
 *
14
 * @author    Thorsten Rinne <[email protected]>
15
 * @author    Matteo Scaramuccia <[email protected]>
16
 * @copyright 2005-2016 phpMyFAQ Team
17
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
18
 *
19
 * @link      http://www.phpmyfaq.de
20
 * @since     2005-11-01
21
 */
22
if (!defined('IS_VALID_PHPMYFAQ')) {
23
    exit();
24
}
25
26
/**#@+
27
  * HTTP GET Parameters PMF accepted keys definitions
28
  */
29
define('HTTP_PARAMS_GET_CATID', 'catid');
30
define('HTTP_PARAMS_GET_CURRENTDAY', 'today');
31
define('HTTP_PARAMS_GET_DISPOSITION', 'dispos');
32
define('HTTP_PARAMS_GET_GIVENDATE', 'givendate');
33
define('HTTP_PARAMS_GET_LANG', 'lang');
34
define('HTTP_PARAMS_GET_DOWNWARDS', 'downwards');
35
define('HTTP_PARAMS_GET_TYPE', 'type');
36
37
/**
38
 * PMF_Utils class.
39
 *
40
 * This class has only static methods
41
 *
42
 * @category  phpMyFAQ
43
 *
44
 * @author    Thorsten Rinne <[email protected]>
45
 * @author    Matteo Scaramuccia <[email protected]>
46
 * @copyright 2005-2016 phpMyFAQ Team
47
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
48
 *
49
 * @link      http://www.phpmyfaq.de
50
 * @since     2005-11-01
51
 */
52
class PMF_Utils
53
{
54
    /**
55
     * Get the content at the given URL using an HTTP GET call.
56
     *
57
     * @param string $url URL of the content
58
     *
59
     * @return string
60
     */
61
    public static function getHTTPContent($url)
62
    {
63
        // Sanity check
64
        if (empty($url)) {
65
            return false;
66
        }
67
68
        // Create the HTTP options for the HTTP stream context, see below
69
        // Set phpMyFAQ agent related data
70
        $agent = 'phpMyFAQ/'.PMF_System::getVersion().' on PHP/'.PHP_VERSION;
71
        $opts = array(
72
            'header' => 'User-Agent: '.$agent."\r\n",
73
            'method' => 'GET',
74
        );
75
        // HTTP 1.1 Virtual Host
76
        $urlParts = @parse_url($url);
77
        if (isset($urlParts['host'])) {
78
            $opts['header'] = $opts['header'].'Host: '.$urlParts['host']."\r\n";
79
        }
80
        // Socket timeout
81
        $opts['timeout'] = 5;
82
83
        // Create the HTTP stream context
84
        $ctx = stream_context_create(
85
            array(
86
                'http' => $opts,
87
            )
88
        );
89
90
        return file_get_contents($url, null, $ctx);
91
    }
92
93
    /**
94
     * Returns date from out of time.
95
     *
96
     * @return string
97
     */
98
    public static function getNeverExpireDate()
99
    {
100
        // Unix: 13 Dec 1901 20:45:54 -> 19 Jan 2038 03:14:07, signed 32 bit
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
101
        // Windows: 1 Jan 1970 -> 19 Jan 2038.
102
        // So we will use: 1 Jan 2038 -> 2038-01-01, 00:00:01
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
103
        return self::getPMFDate(mktime(0, 0, 1, 1, 1, 2038));
104
    }
105
106
    /**
107
     * Returns a phpMyFAQ date.
108
     *
109
     * @param int $unixTime Unix timestamp
110
     *
111
     * @return string
112
     */
113
    public static function getPMFDate($unixTime = null)
114
    {
115
        if (!isset($unixTime)) {
116
            // localtime
117
            $unixTime = $_SERVER['REQUEST_TIME'];
118
        }
119
120
        return date('YmdHis', $unixTime);
121
    }
122
123
    /**
124
     * Check if a given string could be a language.
125
     *
126
     * @param string $lang Language
127
     *
128
     * @return bool
129
     */
130
    public static function isLanguage($lang)
131
    {
132
        return preg_match('/^[a-zA-Z\-]+$/', $lang);
133
    }
134
135
    /**
136
     * Checks if a date is a phpMyFAQ valid date.
137
     *
138
     * @param int $date Date
139
     *
140
     * @return int
141
     */
142
    public static function isLikeOnPMFDate($date)
143
    {
144
        // Test if the passed string is in the format: %YYYYMMDDhhmmss%
145
        $testdate = $date;
146
        // Suppress first occurence of '%'
147
        if (substr($testdate, 0, 1) == '%') {
148
            $testdate = substr($testdate, 1);
149
        }
150
        // Suppress last occurence of '%'
151
        if (substr($testdate, -1, 1) == '%') {
152
            $testdate = substr($testdate, 0, strlen($testdate) - 1);
153
        }
154
        // PMF date consists of numbers only: YYYYMMDDhhmmss
155
        return is_int($testdate);
156
    }
157
158
    /**
159
     * Shortens a string for a given number of words.
160
     *
161
     * @param string $str  String
162
     * @param int    $char Characters
163
     *
164
     * @return string
165
     *
166
     * @todo This function doesn't work with Chinese, Japanese and Korean
167
     *       because they don't have spaces as word delimiters
168
     */
169
    public static function makeShorterText($str, $char)
170
    {
171
        $str = PMF_String::preg_replace('/\s+/u', ' ', $str);
172
        $arrStr = explode(' ', $str);
173
        $shortStr = '';
174
        $num = count($arrStr);
175
176
        if ($num > $char) {
177
            for ($j = 0; $j <= $char; ++$j) {
178
                $shortStr .= $arrStr[$j].' ';
179
            }
180
            $shortStr .= '...';
181
        } else {
182
            $shortStr = $str;
183
        }
184
185
        return $shortStr;
186
    }
187
188
    /**
189
     * Resolves the PMF markers like e.g. %sitename%.
190
     *
191
     * @param string            $text   Text contains PMF markers
192
     * @param PMF_Configuration $config
193
     *
194
     * @return string
195
     */
196
    public static function resolveMarkers($text, PMF_Configuration $config)
197
    {
198
        // Available markers: key and resolving value
199
        $markers = array(
200
            '%sitename%' => $config->get('main.titleFAQ'),
201
        );
202
203
        // Resolve any known pattern
204
        return str_replace(
205
            array_keys($markers),
206
            array_values($markers),
207
            $text
208
        );
209
    }
210
211
    /**
212
     * Shuffles an associative array without losing key associations.
213
     *
214
     * @param array $data Array of data
215
     *
216
     * @return array $shuffled_data Array of shuffled data
217
     */
218
    public static function shuffleData($data)
219
    {
220
        $shuffled_data = [];
221
222
        if (is_array($data)) {
223
            if (count($data) > 1) {
224
                $randomized_keys = array_rand($data, count($data));
225
226
                foreach ($randomized_keys as $current_key) {
227
                    $shuffled_data[$current_key] = $data[$current_key];
228
                }
229
            } else {
230
                $shuffled_data = $data;
231
            }
232
        }
233
234
        return $shuffled_data;
235
    }
236
237
    /**
238
     * This method chops a string.
239
     *
240
     * @param string $string String to chop
241
     * @param int    $words  Number of words
242
     *
243
     * @return string
244
     */
245
    public static function chopString($string, $words)
246
    {
247
        $str = '';
248
        $pieces = explode(' ', $string);
249
        $num = count($pieces);
250
        if ($words > $num) {
251
            $words = $num;
252
        }
253
        for ($i = 0; $i < $words; ++$i) {
254
            $str .= $pieces[$i].' ';
255
        }
256
257
        return $str;
258
    }
259
260
    /**
261
     * Adds a highlighted word to a string.
262
     *
263
     * @param string $string    String
264
     * @param string $highlight Given word for highlighting
265
     *
266
     * @return string
267
     */
268
    public static function setHighlightedString($string, $highlight)
269
    {
270
        $attributes = [
271
            'href', 'src', 'title', 'alt', 'class', 'style', 'id', 'name',
272
            'face', 'size', 'dir', 'rel', 'rev', 'role',
273
            'onmouseenter', 'onmouseleave', 'onafterprint', 'onbeforeprint',
274
            'onbeforeunload', 'onhashchange', 'onmessage', 'onoffline', 'ononline',
275
            'onpopstate', 'onpagehide', 'onpageshow', 'onresize', 'onunload',
276
            'ondevicemotion', 'ondeviceorientation', 'onabort', 'onblur',
277
            'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'oncontextmenu',
278
            'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave',
279
            'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied',
280
            'onended', 'onerror', 'onfocus', 'oninput', 'oninvalid', 'onkeydown',
281
            'onkeypress', 'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata',
282
            'onloadstart', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',
283
            'onmouseup', 'onmozfullscreenchange', 'onmozfullscreenerror', 'onpause',
284
            'onplay', 'onplaying', 'onprogress', 'onratechange', 'onreset',
285
            'onscroll', 'onseeked', 'onseeking', 'onselect', 'onshow', 'onstalled',
286
            'onsubmit', 'onsuspend', 'ontimeupdate', 'onvolumechange', 'onwaiting',
287
            'oncopy', 'oncut', 'onpaste', 'onbeforescriptexecute', 'onafterscriptexecute',
288
        ];
289
290
        return PMF_String::preg_replace_callback(
291
            '/('.$highlight.'="[^"]*")|'.
292
            '(('.implode('|', $attributes).')="[^"]*'.$highlight.'[^"]*")|'.
293
            '('.$highlight.')/mis',
294
            ['PMF_Utils', 'highlightNoLinks'],
295
            $string
296
        );
297
    }
298
299
    /**
300
     * Callback function for filtering HTML from URLs and images.
301
     *
302
     * @param array $matches Array of matches from regex pattern
303
     *
304
     * @return string
305
     */
306
    public static function highlightNoLinks(Array $matches)
307
    {
308
        $prefix = isset($matches[3]) ? $matches[3] : '';
309
        $item = isset($matches[4]) ? $matches[4] : '';
310
        $postfix = isset($matches[5]) ? $matches[5] : '';
311
312
        if (!empty($item) && !self::isForbiddenElement($item)) {
313
            return '<mark class="pmf-highlighted-string">'.$prefix.$item.$postfix.'</mark>';
314
        }
315
316
        // Fallback: the original matched string
317
        return $matches[0];
318
    }
319
320
    /**
321
     * Tries to detect if a string could be a HTML element
322
     * @param $string
323
     * @return bool
324
     */
325
    public static function isForbiddenElement($string)
326
    {
327
        $forbiddenElements = [
328
            'img', 'picture'
329
        ];
330
331
        if (false !== array_search($string, $forbiddenElements)) {
332
            return true;
333
        } else {
334
            return false;
335
        }
336
    }
337
338
    /**
339
     * debug_backtrace() wrapper function.
340
     *
341
     * @param $string
342
     *
343
     * @return string
344
     */
345
    public static function debug($string)
346
    {
347
        // sometimes Zend Optimizer causes segfaults with debug_backtrace()
348
        if (extension_loaded('Zend Optimizer')) {
349
            $ret = '<pre>'.$string."</pre><br>\n";
350
        } else {
351
            $debug = debug_backtrace();
352
            $ret = '';
353
            if (isset($debug[2]['class'])) {
354
                $ret = $debug[2]['file'].':<br>';
355
                $ret .= $debug[2]['class'].$debug[1]['type'];
356
                $ret .= $debug[2]['function'].'() in line '.$debug[2]['line'];
357
                $ret .= ': <pre>'.$string."</pre><br>\n";
358
            }
359
        }
360
361
        return $ret;
362
    }
363
364
    /**
365
     * Parses a given string and convert all the URLs into links.
366
     *
367
     * @param string $string
368
     *
369
     * @return string
370
     */
371
    public static function parseUrl($string)
372
    {
373
        $protocols = array('http://', 'https://', 'ftp://');
374
375
        $string = str_replace($protocols, '', $string);
376
        $string = str_replace('www.', 'http://www.', $string);
377
        $string = preg_replace('|http://([a-zA-Z0-9-\./]+)|', '<a href="http://$1">$1</a>', $string);
378
        $string = preg_replace(
379
            '/(([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6})/',
380
            '<a href="mailto:$1">$1</a>',
381
            $string
382
        );
383
384
        return $string;
385
    }
386
387
    /**
388
     * Moves given key of an array to the top
389
     *
390
     * @param array  $array
391
     * @param string $key
392
     */
393
    public static function moveToTop(&$array, $key)
394
    {
395
        $temp = [$key => $array[$key]];
396
        unset($array[$key]);
397
        $array = $temp + $array;
398
    }
399
}
400