Completed
Push — master ( 204b42...65a2ef )
by Michael
03:03
created

Browscap::_array2string()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 8
eloc 20
c 3
b 0
f 0
nc 13
nop 1
dl 0
loc 30
rs 5.3846
1
<?php
2
3
namespace phpbrowscap;
4
5
use Exception as BaseException;
6
7
/**
8
 * Browscap.ini parsing class with caching and update capabilities
9
 *
10
 * PHP version 5
11
 *
12
 * Copyright (c) 2006-2012 Jonathan Stoppani
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a
15
 * copy of this software and associated documentation files (the "Software"),
16
 * to deal in the Software without restriction, including without limitation
17
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
18
 * and/or sell copies of the Software, and to permit persons to whom the
19
 * Software is furnished to do so, subject to the following conditions:
20
 *
21
 * The above copyright notice and this permission notice shall be included
22
 * in all copies or substantial portions of the Software.
23
 *
24
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30
 * THE SOFTWARE.
31
 *
32
 * @package    Browscap
33
 * @author     Jonathan Stoppani <[email protected]>
34
 * @author     Vítor Brandão <[email protected]>
35
 * @author     Mikołaj Misiurewicz <[email protected]>
36
 * @copyright  Copyright (c) 2006-2012 Jonathan Stoppani
37
 * @version    1.0
38
 * @license    http://www.opensource.org/licenses/MIT MIT License
39
 * @link       https://github.com/GaretJax/phpbrowscap/
40
 */
41
class Browscap
42
{
43
    /**
44
     * Current version of the class.
45
     */
46
    const VERSION = '2.1.1';
47
48
    const CACHE_FILE_VERSION = '2.1.0';
49
50
    /**
51
     * Different ways to access remote and local files.
52
     *
53
     * UPDATE_FOPEN: Uses the fopen url wrapper (use file_get_contents).
54
     * UPDATE_FSOCKOPEN: Uses the socket functions (fsockopen).
55
     * UPDATE_CURL: Uses the cURL extension.
56
     * UPDATE_LOCAL: Updates from a local file (file_get_contents).
57
     */
58
    const UPDATE_FOPEN = 'URL-wrapper';
59
    const UPDATE_FSOCKOPEN = 'socket';
60
    const UPDATE_CURL = 'cURL';
61
    const UPDATE_LOCAL = 'local';
62
63
    /**
64
     * Options for regex patterns.
65
     *
66
     * REGEX_DELIMITER: Delimiter of all the regex patterns in the whole class.
67
     * REGEX_MODIFIERS: Regex modifiers.
68
     */
69
    const REGEX_DELIMITER = '@';
70
    const REGEX_MODIFIERS = 'i';
71
    const COMPRESSION_PATTERN_START = '@';
72
    const COMPRESSION_PATTERN_DELIMITER = '|';
73
74
    /**
75
     * The values to quote in the ini file
76
     */
77
    const VALUES_TO_QUOTE = 'Browser|Parent';
78
79
    const BROWSCAP_VERSION_KEY = 'GJK_Browscap_Version';
80
81
    /**
82
     * The headers to be sent for checking the version and requesting the file.
83
     */
84
    const REQUEST_HEADERS = "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: %s\r\nConnection: Close\r\n\r\n";
85
86
    /**
87
     * how many pattern should be checked at once in the first step
88
     */
89
    const COUNT_PATTERN = 100;
90
91
    /**
92
     * Options for auto update capabilities
93
     *
94
     * $remoteVerUrl: The location to use to check out if a new version of the
95
     *                browscap.ini file is available.
96
     * $remoteIniUrl: The location from which download the ini file.
97
     *                The placeholder for the file should be represented by a %s.
98
     * $timeout: The timeout for the requests.
99
     * $updateInterval: The update interval in seconds.
100
     * $errorInterval: The next update interval in seconds in case of an error.
101
     * $doAutoUpdate: Flag to disable the automatic interval based update.
102
     * $updateMethod: The method to use to update the file, has to be a value of
103
     *                an UPDATE_* constant, null or false.
104
     *
105
     * The default source file type is changed from normal to full. The performance difference
106
     * is MINIMAL, so there is no reason to use the standard file whatsoever. Either go for light,
107
     * which is blazing fast, or get the full one. (note: light version doesn't work, a fix is on its way)
108
     */
109
    public $remoteIniUrl   = 'http://browscap.org/stream?q=PHP_BrowscapINI';
110
    public $remoteVerUrl   = 'http://browscap.org/version';
111
    public $timeout        = 5;
112
    public $updateInterval = 432000; // 5 days
113
    public $errorInterval  = 7200; // 2 hours
114
    public $doAutoUpdate   = true;
115
    public $updateMethod   = null;
116
117
    /**
118
     * The path of the local version of the browscap.ini file from which to
119
     * update (to be set only if used).
120
     *
121
     * @var string
122
     */
123
    public $localFile = null;
124
125
    /**
126
     * The useragent to include in the requests made by the class during the
127
     * update process.
128
     *
129
     * @var string
130
     */
131
    public $userAgent = 'http://browscap.org/ - PHP Browscap/%v %m';
132
133
    /**
134
     * Flag to enable only lowercase indexes in the result.
135
     * The cache has to be rebuilt in order to apply this option.
136
     *
137
     * @var bool
138
     */
139
    public $lowercase = false;
140
141
    /**
142
     * Flag to enable/disable silent error management.
143
     * In case of an error during the update process the class returns an empty
144
     * array/object if the update process can't take place and the browscap.ini
145
     * file does not exist.
146
     *
147
     * @var bool
148
     */
149
    public $silent = false;
150
151
    /**
152
     * Where to store the cached PHP arrays.
153
     *
154
     * @var string
155
     */
156
    public $cacheFilename = 'cache.php';
157
158
    /**
159
     * Where to store the downloaded ini file.
160
     *
161
     * @var string
162
     */
163
    //public $iniFilename = 'browscap.ini';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
164
    public $iniFilename = 'php_browscap.ini'; // irmtfan
165
166
    /**
167
     * Path to the cache directory
168
     *
169
     * @var string
170
     */
171
    public $cacheDir = null;
172
173
    /**
174
     * Flag to be set to true after loading the cache
175
     *
176
     * @var bool
177
     */
178
    protected $_cacheLoaded = false;
179
180
    /**
181
     * Where to store the value of the included PHP cache file
182
     *
183
     * @var array
184
     */
185
    protected $_userAgents = array();
186
    protected $_browsers   = array();
187
    protected $_patterns   = array();
188
    protected $_properties = array();
189
    protected $_source_version;
190
191
    /**
192
     * An associative array of associative arrays in the format
193
     * `$arr['wrapper']['option'] = $value` passed to stream_context_create()
194
     * when building a stream resource.
195
     *
196
     * Proxy settings are stored in this variable.
197
     *
198
     * @see http://www.php.net/manual/en/function.stream-context-create.php
199
     * @var array
200
     */
201
    protected $_streamContextOptions = array();
202
203
    /**
204
     * A valid context resource created with stream_context_create().
205
     *
206
     * @see http://www.php.net/manual/en/function.stream-context-create.php
207
     * @var resource
208
     */
209
    protected $_streamContext = null;
210
211
    /**
212
     * Constructor class, checks for the existence of (and loads) the cache and
213
     * if needed updated the definitions
214
     *
215
     * @param string $cache_dir
0 ignored issues
show
Documentation introduced by
Should the type for parameter $cache_dir not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
216
     *
217
     * @throws Exception
218
     */
219
    public function __construct($cache_dir = null)
220
    {
221
        // has to be set to reach E_STRICT compatibility, does not affect system/app settings
222
        date_default_timezone_set(date_default_timezone_get());
223
224
        if (!isset($cache_dir)) {
225
            throw new Exception('You have to provide a path to read/store the browscap cache file');
226
        }
227
228
        $old_cache_dir = $cache_dir;
229
        $cache_dir     = realpath($cache_dir);
230
231
        if (false === $cache_dir) {
232
            throw new Exception(sprintf('The cache path %s is invalid. Are you sure that it exists and that you have permission to access it?',
233
                                        $old_cache_dir));
234
        }
235
236
        // Is the cache dir really the directory or is it directly the file?
237
        if (substr($cache_dir, -4) === '.php') {
238
            $this->cacheFilename = basename($cache_dir);
239
            $this->cacheDir      = dirname($cache_dir);
240
        } else {
241
            $this->cacheDir = $cache_dir;
242
        }
243
244
        $this->cacheDir .= '/';
245
    }
246
247
    /**
248
     * @return mixed
249
     */
250
    public function getSourceVersion()
251
    {
252
        return $this->_source_version;
253
    }
254
255
    /**
256
     * @return bool
257
     */
258
    public function shouldCacheBeUpdated()
259
    {
260
        // Load the cache at the first request
261
        if ($this->_cacheLoaded) {
262
            return false;
263
        }
264
265
        $cache_file = $this->cacheDir . $this->cacheFilename;
266
        $ini_file   = $this->cacheDir . $this->iniFilename;
267
268
        // Set the interval only if needed
269
        if ($this->doAutoUpdate && file_exists($ini_file)) {
270
            $interval = time() - filemtime($ini_file);
271
        } else {
272
            $interval = 0;
273
        }
274
275
        $shouldBeUpdated = true;
276
277
        if (file_exists($cache_file) && file_exists($ini_file) && ($interval <= $this->updateInterval)) {
278
            if ($this->_loadCache($cache_file)) {
279
                $shouldBeUpdated = false;
280
            }
281
        }
282
283
        return $shouldBeUpdated;
284
    }
285
286
    /**
287
     * Gets the information about the browser by User Agent
288
     *
289
     * @param string $user_agent   the user agent string
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_agent not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
290
     * @param bool   $return_array whether return an array or an object
291
     *
292
     * @throws Exception
293
     * @return \stdClass|array  the object containing the browsers details. Array if
294
     *                    $return_array is set to true.
295
     */
296
    public function getBrowser($user_agent = null, $return_array = false)
0 ignored issues
show
Coding Style introduced by
getBrowser 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...
297
    {
298
        if ($this->shouldCacheBeUpdated()) {
299
            try {
300
                $this->updateCache();
301
            }
302
            catch (Exception $e) {
303
                $ini_file = $this->cacheDir . $this->iniFilename;
304
305
                if (file_exists($ini_file)) {
306
                    // Adjust the filemtime to the $errorInterval
307
                    touch($ini_file, time() - $this->updateInterval + $this->errorInterval);
308
                } elseif ($this->silent) {
309
                    // Return an array if silent mode is active and the ini db doesn't exsist
310
                    return array();
311
                }
312
313
                if (!$this->silent) {
314
                    throw $e;
315
                }
316
            }
317
        }
318
319
        $cache_file = $this->cacheDir . $this->cacheFilename;
320
        if (!$this->_cacheLoaded && !$this->_loadCache($cache_file)) {
321
            throw new Exception('Cannot load cache file - the cache format is not compatible.');
322
        }
323
324
        // Automatically detect the useragent
325
        if (!isset($user_agent)) {
326
            if (isset($_SERVER['HTTP_USER_AGENT'])) {
327
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
328
            } else {
329
                $user_agent = '';
330
            }
331
        }
332
333
        $browser = array();
334
335
        $patterns = array_keys($this->_patterns);
336
        $chunks   = array_chunk($patterns, self::COUNT_PATTERN);
337
338
        foreach ($chunks as $chunk) {
339
            $longPattern = self::REGEX_DELIMITER . '^(?:' . implode(')|(?:', $chunk) . ')$' . self::REGEX_DELIMITER
340
                           . 'i';
341
342
            if (!preg_match($longPattern, $user_agent)) {
343
                continue;
344
            }
345
346
            foreach ($chunk as $pattern) {
347
                $patternToMatch = self::REGEX_DELIMITER . '^' . $pattern . '$' . self::REGEX_DELIMITER . 'i';
348
                $matches        = array();
349
350
                if (!preg_match($patternToMatch, $user_agent, $matches)) {
351
                    continue;
352
                }
353
354
                $patternData = $this->_patterns[$pattern];
355
356
                if (1 === count($matches)) {
357
                    // standard match
358
                    $key         = $patternData;
359
                    $simpleMatch = true;
360
                } else {
361
                    $patternData = unserialize($patternData);
362
363
                    // match with numeric replacements
364
                    array_shift($matches);
365
366
                    $matchString = self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER,
367
                                                                             $matches);
368
369
                    if (!isset($patternData[$matchString])) {
370
                        // partial match - numbers are not present, but everything else is ok
371
                        continue;
372
                    }
373
374
                    $key = $patternData[$matchString];
375
376
                    $simpleMatch = false;
377
                }
378
379
                $browser = array(
380
                    $user_agent, // Original useragent
381
                    trim(strtolower($pattern), self::REGEX_DELIMITER),
382
                    $this->_pregUnQuote($pattern, $simpleMatch ? false : $matches)
383
                );
384
385
                $browser = $value = $browser + unserialize($this->_browsers[$key]);
386
387
                while (array_key_exists(3, $value)) {
388
                    $value = unserialize($this->_browsers[$value[3]]);
389
                    $browser += $value;
390
                }
391
392
                if (!empty($browser[3]) && array_key_exists($browser[3], $this->_userAgents)) {
393
                    $browser[3] = $this->_userAgents[$browser[3]];
394
                }
395
396
                break 2;
397
            }
398
        }
399
400
        // Add the keys for each property
401
        $array = array();
402
        foreach ($browser as $key => $value) {
403
            if ($value === 'true') {
404
                $value = true;
405
            } elseif ($value === 'false') {
406
                $value = false;
407
            }
408
409
            $propertyName = $this->_properties[$key];
410
411
            if ($this->lowercase) {
412
                $propertyName = strtolower($propertyName);
413
            }
414
415
            $array[$propertyName] = $value;
416
        }
417
418
        return $return_array ? $array : (object)$array;
419
    }
420
421
    /**
422
     * Load (auto-set) proxy settings from environment variables.
423
     */
424
    public function autodetectProxySettings()
425
    {
426
        $wrappers = array('http', 'https', 'ftp');
427
428
        foreach ($wrappers as $wrapper) {
429
            $url = getenv($wrapper . '_proxy');
430
            if (!empty($url)) {
431
                $params = array_merge(array(
432
                                          'port' => null,
433
                                          'user' => null,
434
                                          'pass' => null
435
                                      ), parse_url($url));
436
                $this->addProxySettings($params['host'], $params['port'], $wrapper, $params['user'], $params['pass']);
437
            }
438
        }
439
    }
440
441
    /**
442
     * Add proxy settings to the stream context array.
443
     *
444
     * @param string $server   Proxy server/host
445
     * @param int    $port     Port
446
     * @param string $wrapper  Wrapper: "http", "https", "ftp", others...
447
     * @param string $username Username (when requiring authentication)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $username not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
448
     * @param string $password Password (when requiring authentication)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $password not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
449
     *
450
     * @return Browscap
451
     */
452
    public function addProxySettings($server, $port = 3128, $wrapper = 'http', $username = null, $password = null)
453
    {
454
        $settings = array(
455
            $wrapper => array(
456
                'proxy'           => sprintf('tcp://%s:%d', $server, $port),
457
                'request_fulluri' => true,
458
                'timeout'         => $this->timeout
459
            )
460
        );
461
462
        // Proxy authentication (optional)
463
        if (isset($username) && isset($password)) {
464
            $settings[$wrapper]['header'] = 'Proxy-Authorization: Basic ' . base64_encode($username . ':' . $password);
465
        }
466
467
        // Add these new settings to the stream context options array
468
        $this->_streamContextOptions = array_merge($this->_streamContextOptions, $settings);
469
470
        /* Return $this so we can chain addProxySettings() calls like this:
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% 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...
471
         * $browscap->
472
         *   addProxySettings('http')->
473
         *   addProxySettings('https')->
474
         *   addProxySettings('ftp');
475
         */
476
477
        return $this;
478
    }
479
480
    /**
481
     * Clear proxy settings from the stream context options array.
482
     *
483
     * @param string $wrapper Remove settings from this wrapper only
0 ignored issues
show
Documentation introduced by
Should the type for parameter $wrapper not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
484
     *
485
     * @return array Wrappers cleared
486
     */
487
    public function clearProxySettings($wrapper = null)
488
    {
489
        $wrappers = isset($wrapper) ? array($wrapper) : array_keys($this->_streamContextOptions);
490
491
        $clearedWrappers = array();
492
        $options         = array('proxy', 'request_fulluri', 'header');
493
        foreach ($wrappers as $wrapper) {
494
495
            // remove wrapper options related to proxy settings
496
            if (isset($this->_streamContextOptions[$wrapper]['proxy'])) {
497
                foreach ($options as $option) {
498
                    unset($this->_streamContextOptions[$wrapper][$option]);
499
                }
500
501
                // remove wrapper entry if there are no other options left
502
                if (empty($this->_streamContextOptions[$wrapper])) {
503
                    unset($this->_streamContextOptions[$wrapper]);
504
                }
505
506
                $clearedWrappers[] = $wrapper;
507
            }
508
        }
509
510
        return $clearedWrappers;
511
    }
512
513
    /**
514
     * Returns the array of stream context options.
515
     *
516
     * @return array
517
     */
518
    public function getStreamContextOptions()
519
    {
520
        $streamContextOptions = $this->_streamContextOptions;
521
522
        if (empty($streamContextOptions)) {
523
            // set default context, including timeout
524
            $streamContextOptions = array(
525
                'http' => array(
526
                    'timeout' => $this->timeout
527
                )
528
            );
529
        }
530
531
        return $streamContextOptions;
532
    }
533
534
    /**
535
     * Parses the ini file and updates the cache files
536
     *
537
     * @throws Exception
538
     * @return bool whether the file was correctly written to the disk
539
     */
540
    public function updateCache()
541
    {
542
        $lockfile = $this->cacheDir . 'cache.lock';
543
544
        $lockRes = fopen($lockfile, 'w+');
545
        if (false === $lockRes) {
546
            throw new Exception(sprintf('error opening lockfile %s', $lockfile));
547
        }
548
        if (false === flock($lockRes, LOCK_EX | LOCK_NB)) {
549
            throw new Exception(sprintf('error locking lockfile %s', $lockfile));
550
        }
551
552
        $ini_path   = $this->cacheDir . $this->iniFilename;
553
        $cache_path = $this->cacheDir . $this->cacheFilename;
554
555
        // Choose the right url
556
        if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) {
557
            $url = realpath($this->localFile);
558
        } else {
559
            $url = $this->remoteIniUrl;
560
        }
561
562
        $this->_getRemoteIniFile($url, $ini_path);
563
564
        $this->_properties = array();
565
        $this->_browsers   = array();
566
        $this->_userAgents = array();
567
        $this->_patterns   = array();
568
569
        $iniContent = file_get_contents($ini_path);
570
571
        //$this->createCacheOldWay($iniContent);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
572
        $this->createCacheNewWay($iniContent);
573
574
        // Write out new cache file
575
        $dir = dirname($cache_path);
576
577
        // "tempnam" did not work with VFSStream for tests
578
        $tmpFile = $dir . '/temp_' . md5(time() . basename($cache_path));
579
580
        // asume that all will be ok
581
        if (false === ($fileRes = fopen($tmpFile, 'w+'))) {
582
            // opening the temparary file failed
583
            throw new Exception('opening temporary file failed');
584
        }
585
586
        if (false === fwrite($fileRes, $this->_buildCache())) {
587
            // writing to the temparary file failed
588
            throw new Exception('writing to temporary file failed');
589
        }
590
591
        fclose($fileRes);
592
593
        if (false === rename($tmpFile, $cache_path)) {
594
            // renaming file failed, remove temp file
595
            @unlink($tmpFile);
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...
596
597
            throw new Exception('could not rename temporary file to the cache file');
598
        }
599
600
        @flock($lockRes, LOCK_UN);
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...
601
        @fclose($lockRes);
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...
602
        @unlink($lockfile);
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...
603
        $this->_cacheLoaded = false;
604
605
        return true;
606
    }
607
608
    /**
609
     * creates the cache content
610
     *
611
     * @param string $iniContent The content of the downloaded ini file
612
     * @param bool   $actLikeNewVersion
613
     */
614
    protected function createCacheOldWay($iniContent, $actLikeNewVersion = false)
615
    {
616
        $browsers = parse_ini_string($iniContent, true, INI_SCANNER_RAW);
617
618
        if ($actLikeNewVersion) {
619
            $this->_source_version = (int)$browsers[self::BROWSCAP_VERSION_KEY]['Version'];
620
        } else {
621
            $this->_source_version = $browsers[self::BROWSCAP_VERSION_KEY]['Version'];
622
        }
623
624
        unset($browsers[self::BROWSCAP_VERSION_KEY]);
625
626
        if (!$actLikeNewVersion) {
627
            unset($browsers['DefaultProperties']['RenderingEngine_Description']);
628
        }
629
630
        $this->_properties = array_keys($browsers['DefaultProperties']);
631
632
        array_unshift($this->_properties, 'browser_name', 'browser_name_regex', 'browser_name_pattern', 'Parent');
633
634
        $tmpUserAgents = array_keys($browsers);
635
636
        usort($tmpUserAgents, array($this, 'compareBcStrings'));
637
638
        $userAgentsKeys = array_flip($tmpUserAgents);
639
        $propertiesKeys = array_flip($this->_properties);
640
        $tmpPatterns    = array();
641
642
        foreach ($tmpUserAgents as $i => $userAgent) {
643
            $properties = $browsers[$userAgent];
644
645
            if (empty($properties['Comment'])
646
                || false !== strpos($userAgent, '*')
647
                || false !== strpos($userAgent, '?')
648
            ) {
649
                $pattern = $this->_pregQuote($userAgent);
650
651
                $countMatches = preg_match_all(self::REGEX_DELIMITER . '\d' . self::REGEX_DELIMITER, $pattern,
652
                                               $matches);
653
654 View Code Duplication
                if (!$countMatches) {
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...
655
                    $tmpPatterns[$pattern] = $i;
656
                } else {
657
                    $compressedPattern = preg_replace(self::REGEX_DELIMITER . '\d' . self::REGEX_DELIMITER, '(\d)',
658
                                                      $pattern);
659
660
                    if (!isset($tmpPatterns[$compressedPattern])) {
661
                        $tmpPatterns[$compressedPattern] = array('first' => $pattern);
662
                    }
663
664
                    $tmpPatterns[$compressedPattern][$i] = $matches[0];
665
                }
666
            }
667
668 View Code Duplication
            if (!empty($properties['Parent'])) {
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...
669
                $parent = $properties['Parent'];
670
671
                $parentKey = $userAgentsKeys[$parent];
672
673
                $properties['Parent']                 = $parentKey;
674
                $this->_userAgents[$parentKey . '.0'] = $tmpUserAgents[$parentKey];
675
            };
676
677
            $this->_browsers[] = $this->resortProperties($properties, $propertiesKeys);
678
        }
679
680
        // reducing memory usage by unsetting $tmp_user_agents
681
        unset($tmpUserAgents);
682
683
        $this->_patterns = $this->deduplicatePattern($tmpPatterns);
684
    }
685
686
    /**
687
     * creates the cache content
688
     *
689
     * @param string $iniContent The content of the downloaded ini file
690
     *
691
     * @throws \phpbrowscap\Exception
692
     */
693
    protected function createCacheNewWay($iniContent)
694
    {
695
        $patternPositions = array();
696
697
        // get all patterns from the ini file in the correct order,
698
        // so that we can calculate with index number of the resulting array,
699
        // which part to use when the ini file is split into its sections.
700
        preg_match_all('/(?<=\[)(?:[^\r\n]+)(?=\])/m', $iniContent, $patternPositions);
701
702
        if (!isset($patternPositions[0])) {
703
            throw new Exception('could not extract patterns from ini file');
704
        }
705
706
        $patternPositions = $patternPositions[0];
707
708
        if (!count($patternPositions)) {
709
            throw new Exception('no patterns were found inside the ini file');
710
        }
711
712
        // split the ini file into sections and save the data in one line with a hash of the belonging
713
        // pattern (filtered in the previous step)
714
        $iniParts       = preg_split('/\[[^\r\n]+\]/', $iniContent);
715
        $tmpPatterns    = array();
716
        $propertiesKeys = array();
717
        $matches        = array();
718
719
        if (preg_match('/.*\[DefaultProperties\]([^[]*).*/', $iniContent, $matches)) {
720
            $properties = parse_ini_string($matches[1], true, INI_SCANNER_RAW);
721
722
            $this->_properties = array_keys($properties);
723
724
            array_unshift($this->_properties, 'browser_name', 'browser_name_regex', 'browser_name_pattern', 'Parent');
725
726
            $propertiesKeys = array_flip($this->_properties);
727
        }
728
729
        $key                   = $this->_pregQuote(self::BROWSCAP_VERSION_KEY);
730
        $this->_source_version = 0;
731
        $matches               = array();
732
733
        if (preg_match("/\\.*[" . $key . "\\][^[]*Version=(\\d+)\\D.*/", $iniContent, $matches)) {
734
            if (isset($matches[1])) {
735
                $this->_source_version = (int)$matches[1];
736
            }
737
        }
738
739
        $userAgentsKeys = array_flip($patternPositions);
740
        foreach ($patternPositions as $position => $userAgent) {
741
            if (self::BROWSCAP_VERSION_KEY === $userAgent) {
742
                continue;
743
            }
744
745
            $properties = parse_ini_string($iniParts[($position + 1)], true, INI_SCANNER_RAW);
746
747
            if (empty($properties['Comment'])
748
                || false !== strpos($userAgent, '*')
749
                || false !== strpos($userAgent, '?')
750
            ) {
751
                $pattern      = $this->_pregQuote(strtolower($userAgent));
752
                $matches      = array();
753
                $i            = $position - 1;
754
                $countMatches = preg_match_all(self::REGEX_DELIMITER . '\d' . self::REGEX_DELIMITER, $pattern,
755
                                               $matches);
756
757 View Code Duplication
                if (!$countMatches) {
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...
758
                    $tmpPatterns[$pattern] = $i;
759
                } else {
760
                    $compressedPattern = preg_replace(self::REGEX_DELIMITER . '\d' . self::REGEX_DELIMITER, '(\d)',
761
                                                      $pattern);
762
763
                    if (!isset($tmpPatterns[$compressedPattern])) {
764
                        $tmpPatterns[$compressedPattern] = array('first' => $pattern);
765
                    }
766
767
                    $tmpPatterns[$compressedPattern][$i] = $matches[0];
768
                }
769
            }
770
771 View Code Duplication
            if (!empty($properties['Parent'])) {
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...
772
                $parent    = $properties['Parent'];
773
                $parentKey = $userAgentsKeys[$parent];
774
775
                $properties['Parent']                       = $parentKey - 1;
776
                $this->_userAgents[($parentKey - 1) . '.0'] = $patternPositions[$parentKey];
777
            };
778
779
            $this->_browsers[] = $this->resortProperties($properties, $propertiesKeys);
780
        }
781
782
        $patternList = $this->deduplicatePattern($tmpPatterns);
783
784
        $positionIndex = array();
785
        $lengthIndex   = array();
786
        $shortLength   = array();
787
        $patternArray  = array();
788
        $counter       = 0;
789
790
        foreach (array_keys($patternList) as $pattern) {
791
            $decodedPattern = str_replace('(\d)', 0, $this->_pregUnQuote($pattern, false));
792
793
            // force "defaultproperties" (if available) to first position, and "*" to last position
794
            if ($decodedPattern === 'defaultproperties') {
795
                $positionIndex[$pattern] = 0;
796
            } elseif ($decodedPattern === '*') {
797
                $positionIndex[$pattern] = 2;
798
            } else {
799
                $positionIndex[$pattern] = 1;
800
            }
801
802
            // sort by length
803
            $lengthIndex[$pattern] = strlen($decodedPattern);
804
            $shortLength[$pattern] = strlen(str_replace(array('*', '?'), '', $decodedPattern));
805
806
            // sort by original order
807
            $patternArray[$pattern] = $counter;
808
809
            $counter++;
810
        }
811
812
        array_multisort($positionIndex, SORT_ASC, SORT_NUMERIC, $lengthIndex, SORT_DESC, SORT_NUMERIC, $shortLength,
813
                        SORT_DESC, SORT_NUMERIC, $patternArray, SORT_ASC, SORT_NUMERIC, $patternList);
814
815
        $this->_patterns = $patternList;
816
    }
817
818
    /**
819
     * @param array $properties
820
     * @param array $propertiesKeys
821
     *
822
     * @return array
823
     */
824
    protected function resortProperties(array $properties, array $propertiesKeys)
825
    {
826
        $browser = array();
827
828
        foreach ($properties as $propertyName => $propertyValue) {
829
            if (!isset($propertiesKeys[$propertyName])) {
830
                continue;
831
            }
832
833
            $browser[$propertiesKeys[$propertyName]] = $propertyValue;
834
        }
835
836
        return $browser;
837
    }
838
839
    /**
840
     * @param array $tmpPatterns
841
     *
842
     * @return array
843
     */
844
    protected function deduplicatePattern(array $tmpPatterns)
845
    {
846
        $patternList = array();
847
848
        foreach ($tmpPatterns as $pattern => $patternData) {
849
            if (is_int($patternData)) {
850
                $data = $patternData;
851
            } elseif (2 == count($patternData)) {
852
                end($patternData);
853
854
                $pattern = $patternData['first'];
855
                $data    = key($patternData);
856
            } else {
857
                unset($patternData['first']);
858
859
                $data = $this->deduplicateCompressionPattern($patternData, $pattern);
860
            }
861
862
            $patternList[$pattern] = $data;
863
        }
864
865
        return $patternList;
866
    }
867
868
    /**
869
     * @param string $a
870
     * @param string $b
871
     *
872
     * @return int
873
     */
874
    protected function compareBcStrings($a, $b)
875
    {
876
        $a_len = strlen($a);
877
        $b_len = strlen($b);
878
879
        if ($a_len > $b_len) {
880
            return -1;
881
        }
882
883
        if ($a_len < $b_len) {
884
            return 1;
885
        }
886
887
        $a_len = strlen(str_replace(array('*', '?'), '', $a));
888
        $b_len = strlen(str_replace(array('*', '?'), '', $b));
889
890
        if ($a_len > $b_len) {
891
            return -1;
892
        }
893
894
        if ($a_len < $b_len) {
895
            return 1;
896
        }
897
898
        return 0;
899
    }
900
901
    /**
902
     * That looks complicated...
903
     *
904
     * All numbers are taken out into $matches, so we check if any of those numbers are identical
905
     * in all the $matches and if they are we restore them to the $pattern, removing from the $matches.
906
     * This gives us patterns with "(\d)" only in places that differ for some matches.
907
     *
908
     * @param array  $matches
909
     * @param string $pattern
910
     *
911
     * @return array of $matches
912
     */
913
    protected function deduplicateCompressionPattern($matches, &$pattern)
914
    {
915
        $tmp_matches = $matches;
916
        $first_match = array_shift($tmp_matches);
917
        $differences = array();
918
919
        foreach ($tmp_matches as $some_match) {
920
            $differences += array_diff_assoc($first_match, $some_match);
921
        }
922
923
        $identical = array_diff_key($first_match, $differences);
924
925
        $prepared_matches = array();
926
927
        foreach ($matches as $i => $some_match) {
928
            $key = self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER,
929
                                                             array_diff_assoc($some_match, $identical));
930
931
            $prepared_matches[$key] = $i;
932
        }
933
934
        $pattern_parts = explode('(\d)', $pattern);
935
936
        foreach ($identical as $position => $value) {
937
            $pattern_parts[$position + 1] = $pattern_parts[$position] . $value . $pattern_parts[$position + 1];
938
            unset($pattern_parts[$position]);
939
        }
940
941
        $pattern = implode('(\d)', $pattern_parts);
942
943
        return $prepared_matches;
944
    }
945
946
    /**
947
     * Converts browscap match patterns into preg match patterns.
948
     *
949
     * @param string $user_agent
950
     *
951
     * @return string
952
     */
953
    protected function _pregQuote($user_agent)
954
    {
955
        $pattern = preg_quote($user_agent, self::REGEX_DELIMITER);
956
957
        // the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match
958
959
        return str_replace(array('\*', '\?', '\\x'), array('.*', '.', '\\\\x'), $pattern);
960
    }
961
962
    /**
963
     * Converts preg match patterns back to browscap match patterns.
964
     *
965
     * @param string        $pattern
966
     * @param array|boolean $matches
967
     *
968
     * @return string
969
     */
970
    protected function _pregUnQuote($pattern, $matches)
971
    {
972
        // list of escaped characters: http://www.php.net/manual/en/function.preg-quote.php
973
        // to properly unescape '?' which was changed to '.', I replace '\.' (real dot) with '\?',
974
        // then change '.' to '?' and then '\?' to '.'.
975
        $search  = array(
976
            '\\' . self::REGEX_DELIMITER,
977
            '\\.',
978
            '\\\\',
979
            '\\+',
980
            '\\[',
981
            '\\^',
982
            '\\]',
983
            '\\$',
984
            '\\(',
985
            '\\)',
986
            '\\{',
987
            '\\}',
988
            '\\=',
989
            '\\!',
990
            '\\<',
991
            '\\>',
992
            '\\|',
993
            '\\:',
994
            '\\-',
995
            '.*',
996
            '.',
997
            '\\?'
998
        );
999
        $replace = array(
1000
            self::REGEX_DELIMITER,
1001
            '\\?',
1002
            '\\',
1003
            '+',
1004
            '[',
1005
            '^',
1006
            ']',
1007
            '$',
1008
            '(',
1009
            ')',
1010
            '{',
1011
            '}',
1012
            '=',
1013
            '!',
1014
            '<',
1015
            '>',
1016
            '|',
1017
            ':',
1018
            '-',
1019
            '*',
1020
            '?',
1021
            '.'
1022
        );
1023
1024
        $result = substr(str_replace($search, $replace, $pattern), 2, -2);
1025
1026
        if ($matches) {
1027
            foreach ($matches as $oneMatch) {
0 ignored issues
show
Bug introduced by
The expression $matches of type array|boolean 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...
1028
                $position = strpos($result, '(\d)');
1029
                $result   = substr_replace($result, $oneMatch, $position, 4);
1030
            }
1031
        }
1032
1033
        return $result;
1034
    }
1035
1036
    /**
1037
     * Loads the cache into object's properties
1038
     *
1039
     * @param string $cache_file
1040
     *
1041
     * @return boolean
1042
     */
1043
    protected function _loadCache($cache_file)
1044
    {
1045
        $cache_version  = null;
1046
        $source_version = null;
1047
        $browsers       = array();
1048
        $userAgents     = array();
1049
        $patterns       = array();
1050
        $properties     = array();
1051
1052
        $this->_cacheLoaded = false;
1053
1054
        require $cache_file;
1055
1056
        if (!isset($cache_version) || $cache_version != self::CACHE_FILE_VERSION) {
1057
            return false;
1058
        }
1059
1060
        $this->_source_version = $source_version;
1061
        $this->_browsers       = $browsers;
1062
        $this->_userAgents     = $userAgents;
1063
        $this->_patterns       = $patterns;
1064
        $this->_properties     = $properties;
1065
1066
        $this->_cacheLoaded = true;
1067
1068
        return true;
1069
    }
1070
1071
    /**
1072
     * Parses the array to cache and writes the resulting PHP string to disk
1073
     *
1074
     * @return boolean False on write error, true otherwise
0 ignored issues
show
Documentation introduced by
Should the return type not be 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...
1075
     */
1076
    protected function _buildCache()
1077
    {
1078
        $content = sprintf("<?php\n\$source_version=%s;\n\$cache_version=%s", "'" . $this->_source_version . "'",
1079
                           "'" . self::CACHE_FILE_VERSION . "'");
1080
1081
        $content .= ";\n\$properties=";
1082
        $content .= $this->_array2string($this->_properties);
1083
1084
        $content .= ";\n\$browsers=";
1085
        $content .= $this->_array2string($this->_browsers);
1086
1087
        $content .= ";\n\$userAgents=";
1088
        $content .= $this->_array2string($this->_userAgents);
1089
1090
        $content .= ";\n\$patterns=";
1091
        $content .= $this->_array2string($this->_patterns) . ";\n";
1092
1093
        return $content;
1094
    }
1095
1096
    /**
1097
     * Lazy getter for the stream context resource.
1098
     *
1099
     * @param bool $recreate
1100
     *
1101
     * @return resource
1102
     */
1103
    protected function _getStreamContext($recreate = false)
1104
    {
1105
        if (!isset($this->_streamContext) || true === $recreate) {
1106
            $this->_streamContext = stream_context_create($this->getStreamContextOptions());
1107
        }
1108
1109
        return $this->_streamContext;
1110
    }
1111
1112
    /**
1113
     * Updates the local copy of the ini file (by version checking) and adapts
1114
     * his syntax to the PHP ini parser
1115
     *
1116
     * @param string $url  the url of the remote server
1117
     * @param string $path the path of the ini file to update
1118
     *
1119
     * @throws Exception
1120
     * @return bool if the ini file was updated
1121
     */
1122
    protected function _getRemoteIniFile($url, $path)
1123
    {
1124
        // local and remote file are the same, no update possible
1125
        if ($url == $path) {
1126
            return false;
1127
        }
1128
1129
        // Check version
1130
        if (file_exists($path) && filesize($path)) {
1131
            $local_tmstp = filemtime($path);
1132
1133
            if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) {
1134
                $remote_tmstp = $this->_getLocalMTime();
1135
            } else {
1136
                $remote_tmstp = $this->_getRemoteMTime();
1137
            }
1138
1139
            if ($remote_tmstp <= $local_tmstp) {
1140
                // No update needed, return
1141
                touch($path);
1142
1143
                return false;
1144
            }
1145
        }
1146
1147
        // Check if it's possible to write to the .ini file.
1148
        if (is_file($path)) {
1149
            if (!is_writable($path)) {
1150
                throw new Exception('Could not write to "' . $path
1151
                                    . '" (check the permissions of the current/old ini file).');
1152
            }
1153
        } else {
1154
            // Test writability by creating a file only if one already doesn't exist, so we can safely delete it after
1155
            // the test.
1156
            $test_file = fopen($path, 'a');
1157
            if ($test_file) {
1158
                fclose($test_file);
1159
                unlink($path);
1160
            } else {
1161
                throw new Exception('Could not write to "' . $path
1162
                                    . '" (check the permissions of the cache directory).');
1163
            }
1164
        }
1165
1166
        // Get updated .ini file
1167
        $content = $this->_getRemoteData($url);
1168
1169
        if (!is_string($content) || strlen($content) < 1) {
1170
            throw new Exception('Could not load .ini content from "' . $url . '"');
1171
        }
1172
1173
        if (false !== strpos('rate limit', $content)) {
1174
            throw new Exception('Could not load .ini content from "' . $url
1175
                                . '" because the rate limit is exeeded for your IP');
1176
        }
1177
1178
        // replace opening and closing php and asp tags
1179
        $content = $this->sanitizeContent($content);
1180
1181
        if (!file_put_contents($path, $content)) {
1182
            throw new Exception('Could not write .ini content to "' . $path . '"');
1183
        }
1184
1185
        return true;
1186
    }
1187
1188
    /**
1189
     * @param string $content
1190
     *
1191
     * @return mixed
1192
     */
1193
    protected function sanitizeContent($content)
1194
    {
1195
        // replace everything between opening and closing php and asp tags
1196
        $content = preg_replace('/<[?%].*[?%]>/', '', $content);
1197
1198
        // replace opening and closing php and asp tags
1199
        return str_replace(array('<?', '<%', '?>', '%>'), '', $content);
1200
    }
1201
1202
    /**
1203
     * Gets the remote ini file update timestamp
1204
     *
1205
     * @throws Exception
1206
     * @return int the remote modification timestamp
1207
     */
1208
    protected function _getRemoteMTime()
1209
    {
1210
        $remote_datetime = $this->_getRemoteData($this->remoteVerUrl);
1211
        $remote_tmstp    = strtotime($remote_datetime);
1212
1213
        if (!$remote_tmstp) {
1214
            throw new Exception("Bad datetime format from {$this->remoteVerUrl}");
1215
        }
1216
1217
        return $remote_tmstp;
1218
    }
1219
1220
    /**
1221
     * Gets the local ini file update timestamp
1222
     *
1223
     * @throws Exception
1224
     * @return int the local modification timestamp
1225
     */
1226
    protected function _getLocalMTime()
1227
    {
1228
        if (!is_readable($this->localFile) || !is_file($this->localFile)) {
1229
            throw new Exception('Local file is not readable');
1230
        }
1231
1232
        return filemtime($this->localFile);
1233
    }
1234
1235
    /**
1236
     * Converts the given array to the PHP string which represent it.
1237
     * This method optimizes the PHP code and the output differs form the
1238
     * var_export one as the internal PHP function does not strip whitespace or
1239
     * convert strings to numbers.
1240
     *
1241
     * @param array $array The array to parse and convert
1242
     *
1243
     * @return boolean False on write error, true otherwise
0 ignored issues
show
Documentation introduced by
Should the return type not be 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...
1244
     */
1245
    protected function _array2string($array)
1246
    {
1247
        $content = "array(\n";
1248
1249
        foreach ($array as $key => $value) {
1250
            if (is_int($key)) {
1251
                $key = '';
1252
            } elseif (ctype_digit((string)$key)) {
1253
                $key = (int)$key . ' => ';
1254
            } elseif ('.0' === substr($key, -2) && !preg_match('/[^\d\.]/', $key)) {
1255
                $key = (int)$key . ' => ';
1256
            } else {
1257
                $key = "'" . str_replace("'", "\'", $key) . "' => ";
1258
            }
1259
1260
            if (is_array($value)) {
1261
                $value = "'" . addcslashes(serialize($value), "'") . "'";
1262
            } elseif (ctype_digit((string)$value)) {
1263
                $value = (int)$value;
1264
            } else {
1265
                $value = "'" . str_replace("'", "\'", $value) . "'";
1266
            }
1267
1268
            $content .= $key . $value . ",\n";
1269
        }
1270
1271
        $content .= "\n)";
1272
1273
        return $content;
1274
    }
1275
1276
    /**
1277
     * Checks for the various possibilities offered by the current configuration
1278
     * of PHP to retrieve external HTTP data
1279
     *
1280
     * @return string|false the name of function to use to retrieve the file or false if no methods are available
1281
     */
1282
    protected function _getUpdateMethod()
1283
    {
1284
        // Caches the result
1285
        if ($this->updateMethod === null) {
1286
            if ($this->localFile !== null) {
1287
                $this->updateMethod = self::UPDATE_LOCAL;
1288
            } elseif (ini_get('allow_url_fopen') && function_exists('file_get_contents')) {
1289
                $this->updateMethod = self::UPDATE_FOPEN;
1290
            } elseif (function_exists('fsockopen')) {
1291
                $this->updateMethod = self::UPDATE_FSOCKOPEN;
1292
            } elseif (extension_loaded('curl')) {
1293
                $this->updateMethod = self::UPDATE_CURL;
1294
            } else {
1295
                $this->updateMethod = false;
1296
            }
1297
        }
1298
1299
        return $this->updateMethod;
1300
    }
1301
1302
    /**
1303
     * Retrieve the data identified by the URL
1304
     *
1305
     * @param string $url the url of the data
1306
     *
1307
     * @throws Exception
1308
     * @return string the retrieved data
1309
     */
1310
    protected function _getRemoteData($url)
1311
    {
1312
        ini_set('user_agent', $this->_getUserAgent());
1313
1314
        switch ($this->_getUpdateMethod()) {
1315
            case self::UPDATE_LOCAL:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
1316
                $file = file_get_contents($url);
1317
1318
                if ($file !== false) {
1319
                    return $file;
1320
                } else {
1321
                    throw new Exception('Cannot open the local file');
1322
                }
1323
            case self::UPDATE_FOPEN:
1324
                if (ini_get('allow_url_fopen') && function_exists('file_get_contents')) {
1325
                    // include proxy settings in the file_get_contents() call
1326
                    $context = $this->_getStreamContext();
1327
                    $file    = file_get_contents($url, false, $context);
1328
1329
                    if ($file !== false) {
1330
                        return $file;
1331
                    }
1332
                }// else try with the next possibility (break omitted)
1333
            case self::UPDATE_FSOCKOPEN:
1334
                if (function_exists('fsockopen')) {
1335
                    $remote_url     = parse_url($url);
1336
                    $contextOptions = $this->getStreamContextOptions();
1337
1338
                    $errno  = 0;
1339
                    $errstr = '';
1340
1341
                    if (empty($contextOptions)) {
1342
                        $port           = (empty($remote_url['port']) ? 80 : $remote_url['port']);
1343
                        $remote_handler = fsockopen($remote_url['host'], $port, $errno, $errstr, $this->timeout);
1344
                    } else {
1345
                        $context = $this->_getStreamContext();
1346
1347
                        $remote_handler = stream_socket_client($url, $errno, $errstr, $this->timeout,
1348
                                                               STREAM_CLIENT_CONNECT, $context);
1349
                    }
1350
1351
                    if ($remote_handler) {
1352
                        stream_set_timeout($remote_handler, $this->timeout);
1353
1354
                        if (isset($remote_url['query'])) {
1355
                            $remote_url['path'] .= '?' . $remote_url['query'];
1356
                        }
1357
1358
                        $out = sprintf(self::REQUEST_HEADERS, $remote_url['path'], $remote_url['host'],
1359
                                       $this->_getUserAgent());
1360
1361
                        fwrite($remote_handler, $out);
1362
1363
                        $response = fgets($remote_handler);
1364
                        if (strpos($response, '200 OK') !== false) {
1365
                            $file = '';
1366
                            while (!feof($remote_handler)) {
1367
                                $file .= fgets($remote_handler);
1368
                            }
1369
1370
                            $file = str_replace("\r\n", "\n", $file);
1371
                            $file = explode("\n\n", $file);
1372
                            array_shift($file);
1373
1374
                            $file = implode("\n\n", $file);
1375
1376
                            fclose($remote_handler);
1377
1378
                            return $file;
1379
                        }
1380
                    }
1381
                }// else try with the next possibility
1382
            case self::UPDATE_CURL:
1383
                if (extension_loaded('curl')) { // make sure curl is loaded
1384
                    $ch = curl_init($url);
1385
1386
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1387
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
1388
                    curl_setopt($ch, CURLOPT_USERAGENT, $this->_getUserAgent());
1389
1390
                    $file = curl_exec($ch);
1391
1392
                    curl_close($ch);
1393
1394
                    if ($file !== false) {
1395
                        return $file;
1396
                    }
1397
                }// else try with the next possibility
1398
            case false:
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $this->_getUpdateMethod() of type string|false against false; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
1399
                throw new Exception('Your server can\'t connect to external resources. Please update the file manually.');
1400
        }
1401
1402
        return '';
1403
    }
1404
1405
    /**
1406
     * Format the useragent string to be used in the remote requests made by the
1407
     * class during the update process.
1408
     *
1409
     * @return string the formatted user agent
1410
     */
1411
    protected function _getUserAgent()
1412
    {
1413
        $ua = str_replace('%v', self::VERSION, $this->userAgent);
1414
        $ua = str_replace('%m', $this->_getUpdateMethod(), $ua);
1415
1416
        return $ua;
1417
    }
1418
}
1419
1420
/**
1421
 * Browscap.ini parsing class exception
1422
 *
1423
 * @package    Browscap
1424
 * @author     Jonathan Stoppani <[email protected]>
1425
 * @copyright  Copyright (c) 2006-2012 Jonathan Stoppani
1426
 * @version    1.0
1427
 * @license    http://www.opensource.org/licenses/MIT MIT License
1428
 * @link       https://github.com/GaretJax/phpbrowscap/
1429
 */
1430
class Exception extends \Exception
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
1431
{
1432
    // nothing to do here
1433
}
1434