Completed
Push — master ( 33398c...a85001 )
by Michael
04:01 queued 02:05
created

functions.php ➔ xlanguage_convert_encoding()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
eloc 7
c 2
b 0
f 1
nc 2
nop 3
dl 0
loc 12
rs 9.4285
1
<?php
2
/**
3
 * xLanguage module (eXtensible Language Management For XOOPS)
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright    XOOPS Project (http://xoops.org)
13
 * @license      {@link http://www.gnu.org/licenses/gpl-2.0.html GNU Public License}
14
 * @package      xlanguage
15
 * @since        2.0
16
 * @author       D.J.(phppp) [email protected]
17
 * @param $value
18
 * @param $out_charset
19
 * @param $in_charset
20
 * @return array|string
21
 */
22
23
function xlanguage_convert_encoding($value, $out_charset, $in_charset)
24
{
25
    if (is_array($value)) {
26
        foreach ($value as $key => $val) {
27
            $value[$key] = xlanguage_convert_encoding($val, $out_charset, $in_charset);
28
        }
29
    } else {
30
        $value = xlanguage_convert_item($value, $out_charset, $in_charset);
31
    }
32
33
    return $value;
34
}
35
36
/**
37
 * @param $value
38
 * @param $out_charset
39
 * @param $in_charset
40
 * @return string
41
 */
42
function xlanguage_convert_item($value, $out_charset, $in_charset)
43
{
44
    if (strtolower($in_charset) == strtolower($out_charset)) {
45
        return $value;
46
    }
47
    $xconv_handler = @xoops_getModuleHandler('xconv', 'xconv', true);
48
    if (is_object($xconv_handler) && $converted_value = @$xconv_handler->convert_encoding($value, $out_charset, $in_charset)) {
49
        return $converted_value;
50
    }
51
    if (XOOPS_USE_MULTIBYTES && function_exists('mb_convert_encoding')) {
52
        $converted_value = @mb_convert_encoding($value, $out_charset, $in_charset);
53
    } elseif (function_exists('iconv')) {
54
        $converted_value = @iconv($in_charset, $out_charset, $value);
55
    }
56
    $value = empty($converted_value) ? $value : $converted_value;
57
58
    return $value;
59
}
60
61
/**
62
 * @return mixed
63
 */
64
function xlanguage_createConfig()
65
{
66
    $xlang_handler = xoops_getModuleHandler('language', 'xlanguage');
67
68
    return $xlang_handler->createConfig();
69
}
70
71
/**
72
 * @return mixed
73
 */
74
function xlanguage_loadConfig()
75
{
76
    $xlang_handler = xoops_getModuleHandler('language', 'xlanguage');
77
    $config        = $xlang_handler->loadFileConfig();
78
79
    return $config;
80
}
81
82
/**
83
 * Analyzes some PHP environment variables to find the most probable language
84
 * that should be used
85
 *
86
 * @param  string $str
87
 * @param  string $envType
88
 * @return int|string
89
 * @internal param $string $ string to analyze
90
 * @internal param $integer $ type of the PHP environment variable which value is $str
91
 *
92
 * @global        array    the list of available translations
93
 * @global        string   the retained translation keyword
94
 * @access   private
95
 */
96
function xlanguage_lang_detect($str = '', $envType = '')
97
{
98
    global $available_languages;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
99
    $lang = '';
100
101
    if (!empty($available_languages)) {
102
        foreach ($available_languages as $key => $value) {
103
            // $envType =  1 for the 'HTTP_ACCEPT_LANGUAGE' environment variable,
104
            //             2 for the 'HTTP_USER_AGENT' one
105
            $expr = $value[0];
106
            if (strpos($expr, '[-_]') === false) {
107
                $expr = str_replace('|', '([-_][[:alpha:]]{2,3})?|', $expr);
108
            }
109
            //        if (($envType == 1 && eregi('^(' . $expr . ')(;q=[0-9]\\.[0-9])?$', $str))
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...
110
            //            || ($envType == 2 && eregi('(\(|\[|;[[:space:]])(' . $expr . ')(;|\]|\))', $str))) {
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...
111
            if (($envType == 1 && preg_match('#^(' . $expr . ')(;q=[0-9]\\.[0-9])?$#i', $str)) || ($envType == 2 && preg_match('#(\(|\[|;[[:space:]])(' . $expr . ')(;|\]|\))#i', $str))) {
112
                $lang = $key;
113
                //if($lang != 'en')
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
114
                break;
115
            }
116
        }
117
    }
118
119
    return $lang;
120
}
121
122
/**
123
 * @return string
124
 */
125
function xlanguage_detectLang()
0 ignored issues
show
Coding Style introduced by
xlanguage_detectLang 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...
126
{
127
    global $available_languages, $_SERVER;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
128
129
    if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
130
        $HTTP_ACCEPT_LANGUAGE = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
0 ignored issues
show
Unused Code introduced by
$HTTP_ACCEPT_LANGUAGE is not used, you could remove the assignment.

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

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

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

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

Loading history...
131
    }
132
133
    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
134
        $HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
135
    }
136
137
    $lang       = '';
0 ignored issues
show
Unused Code introduced by
$lang is not used, you could remove the assignment.

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

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

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

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

Loading history...
138
    $xoops_lang = '';
139
    // 1. try to findout user's language by checking its HTTP_ACCEPT_LANGUAGE variable
140
141
    //    if (empty($lang) && !empty($HTTP_ACCEPT_LANGUAGE)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
142
    //        $accepted    = explode(',', $HTTP_ACCEPT_LANGUAGE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
143
    //        $acceptedCnt = count($accepted);
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...
144
    //        reset($accepted);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
145
    //        for ($i = 0; $i < $acceptedCnt; ++$i) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
146
    //            $lang = xlanguage_lang_detect($accepted[$i], 1);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
147
    //            if (strncasecmp($lang, 'en', 2)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
148
    //                break;
149
    //            }
150
    //        }
151
    //    }
152
153
    //This returns the most preferred langauage "q=1"
154
    $lang = getPreferredLanguage();
155
156
    // 2. if not found in HTTP_ACCEPT_LANGUAGE, try to find user's language by checking its HTTP_USER_AGENT variable
157
    if (empty($lang) && !empty($HTTP_USER_AGENT)) {
158
        $lang = xlanguage_lang_detect($HTTP_USER_AGENT, 2);
159
    }
160
    // 3. If we catch a valid language, configure it
161
    if (!empty($lang)) {
162
        $xoops_lang = $available_languages[$lang][1];
163
    }
164
165
    return $xoops_lang;
166
}
167
168
/**
169
 * @param $output
170
 * @return array|mixed|string
171
 */
172
function xlanguage_encoding($output)
173
{
174
    global $xlanguage;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
175
    $output = xlanguage_ml($output);
176
    // escape XML doc
177
    if (preg_match("/^\<\?[\s]?xml[\s]+version=([\"'])[^\>]+\\1[\s]+encoding=([\"'])[^\>]+\\2[\s]?\?\>/i", $output)) {
178
        return $output;
179
    }
180
    $in_charset  = $xlanguage['charset_base'];
181
    $out_charset = $xlanguage['charset'];
182
183
    return $output = xlanguage_convert_encoding($output, $out_charset, $in_charset);
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

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

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

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

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

Loading history...
184
}
185
186
/**
187
 * @param $s
188
 * @return mixed
189
 */
190
function xlanguage_ml($s)
191
{
192
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
193
    global $xlanguage_langs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
194
    if (!isset($xlanguage_langs)) {
195
        $xlanguageHandler = xoops_getModuleHandler('language', 'xlanguage');
196
        $langs             = $xlanguageHandler->getAll(true);
197
        //        $langs = $GLOBALS['xlanguage_handler']->getAll(true); //mb
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
198
        foreach (array_keys($langs) as $_lang) {
199
            $xlanguage_langs[$_lang] = $langs[$_lang]->getVar('lang_code');
200
        }
201
        unset($langs);
202
    }
203
    if (empty($xlanguage_langs) || count($xlanguage_langs) == 0) {
204
        return $s;
205
    }
206
207
    // escape brackets inside of <code>...</code>
208
    $patterns[] = '/(\<code>.*\<\/code>)/isU';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$patterns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $patterns = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
209
210
    // escape brackets inside of <input type="..." value="...">
211
    $patterns[] = '/(\<input\b(?![^\>]*\btype=([\'"]?)(submit|image|reset|button))[^\>]*\>)/isU';
212
213
    // escape brackets inside of <textarea></textarea>
214
    $patterns[] = '/(\<textarea\b[^>]*>[^\<]*\<\/textarea>)/isU';
215
216
    $s = preg_replace_callback($patterns, 'xlanguage_ml_escape_bracket', $s);
217
218
    // create the pattern between language tags
219
    $pqhtmltags  = explode(',', preg_quote(XLANGUAGE_TAGS_RESERVED, '/'));
220
    $mid_pattern = '(?:(?!(' . implode('|', $pqhtmltags) . ')).)*';
221
222
    $patterns = array();
223
    $replaces = array();
224
    /* */
225
    if (isset($xlanguage_langs[$xoopsConfig['language']])) {
226
        $lang       = $xlanguage_langs[$xoopsConfig['language']];
227
        $patterns[] = '/(\[([^\]]*\|)?' . preg_quote($lang) . '(\|[^\]]*)?\])(' . $mid_pattern . ')(\[\/([^\]]*\|)?' . preg_quote($lang) . '(\|[^\]]*)?\])/isU';
228
        $replaces[] = '$4';
229
    }
230
    /* */
231
    foreach (array_keys($xlanguage_langs) as $_lang) {
232
        if ($_lang == @$xoopsConfig['language']) {
233
            continue;
234
        }
235
        $name       = $xlanguage_langs[$_lang];
236
        $patterns[] = '/(\[([^\]]*\|)?' . preg_quote($name) . '(\|[^\]]*)?\])(' . $mid_pattern . ')(\[\/([^\]]*\|)?' . preg_quote($name) . '(\|[^\]]*)?(\]\<br[\s]?[\/]?\>|\]))/isU';
237
        $replaces[] = '';
238
    }
239
    if (!empty($xoopsConfig['language'])) {
240
        $s = preg_replace('/\[[\/]?[\|]?' . preg_quote($xoopsConfig['language']) . '[\|]?\](\<br \/\>)?/i', '', $s);
241
    }
242
    if (count($replaces) > 0) {
243
        $s = preg_replace($patterns, $replaces, $s);
244
    }
245
246
    return $s;
247
}
248
249
/**
250
 * @param $matches
251
 * @return mixed
252
 */
253
function xlanguage_ml_escape_bracket($matches)
254
{
255
    global $xlanguage_langs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
256
    $ret = $matches[1];
257
    if (!empty($xlanguage_langs)) {
258
        $pattern = '/(\[([\/])?(' . implode('|', array_map('preg_quote', array_values($xlanguage_langs))) . ')([\|\]]))/isU';
259
        $ret     = preg_replace($pattern, "&#91;\\2\\3\\4", $ret);
260
    }
261
262
    return $ret;
263
}
264
265
/**
266
 * @param  null $options
267
 * @return bool
268
 */
269
function xlanguage_select_show($options = null)
270
{
271
    include_once XOOPS_ROOT_PATH . '/modules/xlanguage/blocks/xlanguage_blocks.php';
272
    if (empty($options)) {
273
        $options[0] = 'images'; // display style: image, text, select
274
        $options[1] = ' '; // delimitor
275
        $options[2] = 5; // items per line
276
    }
277
278
    $block        = b_xlanguage_select_show($options);
279
    $block['tag'] = 'xlanguage';
280
281
    $content = '';
282
    $i       = 1;
283
    if (!empty($block['display'])) { //mb
284
        if (in_array($block['display'], array('images', 'text'))) {
285
            foreach ($block['languages'] as $name => $lang) {
286
                $content .= "<a href=\"" . $block['url'] . $lang['name'] . "\" title=\"" . $lang['desc'] . "\">";
287
                if ($block['display'] === 'images') {
288
                    $content .= "<img src=\"" . $lang['image'] . "\" alt=\"" . $lang['desc'] . "\"";
289
                    if ($block['selected'] != $lang['name']) {
290
                        $content .= " style=\"MozOpacity: .8; opacity: .8; filter:Alpha(opacity=80);\"";
291
                    }
292
                    $content .= '/>';
293
                } else {
294
                    $content .= $lang['desc'];
295
                }
296
                $content .= '</a>';
297
                if ((++$i % $block['number']) == 0) {
298
                    $content .= '<br>';
299
                }
300
            }
301
        } else {
302
            $content .= "<select name=\"" . $block['tag'] . "\"
303
                onChange=\"if (this.options[this.selectedIndex].value.length >0) { window.document.location=this.options[this.selectedIndex].value;}\"
304
                >";
305
            if (!empty($block['languages'])) { //mb
306
                foreach ($block['languages'] as $name => $lang) {
0 ignored issues
show
Bug introduced by
The expression $block['languages'] of type string is not traversable.
Loading history...
307
                    $content .= "<option value=\"" . $block['url'] . $lang['name'] . "\"";
308
                    if ($block['selected'] == $lang['name']) {
309
                        $content .= ' selected ';
310
                    }
311
                    $content .= '/>' . $lang['desc'] . '</option>';
312
                }
313
            }
314
            $content .= '</select>';
315
        }
316
    }
317
318
    define('XLANGUAGE_SWITCH_CODE', $content);
319
320
    return true;
321
}
322
323
/**
324
 * @return int|string
325
 */
326
function getPreferredLanguage()
0 ignored issues
show
Coding Style introduced by
getPreferredLanguage 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...
327
{
328
    $langs = array();
329
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
330
        // break up string into pieces (languages and q factors)
331
        preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.\d+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
332
        if (count($lang_parse[1])) {
333
            // create a list like "en" => 0.8
334
            $langs = array_combine($lang_parse[1], $lang_parse[4]);
335
            // set default to 1 for any without q factor
336
            foreach ($langs as $lang => $val) {
337
                if ($val === '') {
338
                    $langs[$lang] = 1;
339
                }
340
            }
341
            // sort list based on value
342
            arsort($langs, SORT_NUMERIC);
343
        }
344
    }
345
    //extract most important (first)
346
    foreach ($langs as $lang => $val) {
347
        break;
348
    }
349
    //if complex language simplify it
350
    if (strstr($lang, '-')) {
351
        $tmp  = explode('-', $lang);
0 ignored issues
show
Bug introduced by
The variable $lang 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...
352
        $lang = $tmp[0];
353
    }
354
355
    return $lang;
356
}
357