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

Blanguage::hasBase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
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
 **/
18
19
//include_once(XOOPS_ROOT_PATH."/class/xoopslists.php");
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
20
//include_once(XOOPS_ROOT_PATH.'/modules/xlanguage/include/vars.php');
21
//include_once(XOOPS_ROOT_PATH.'/modules/xlanguage/include/functions.php');
22
23
/**
24
 * Class Blanguage
25
 */
26
class Blanguage extends XoopsObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
27
{
28
    public $isBase;
29
30
    /**
31
     * Blanguage constructor.
32
     */
33
    public function __construct()
34
    {
35
        $this->db    = XoopsDatabaseFactory::getDatabaseConnection();
36
        $this->table = $this->db->prefix('xlanguage_base');
37
        $this->initVar('lang_id', XOBJ_DTYPE_INT);
38
        $this->initVar('weight', XOBJ_DTYPE_INT);
39
        $this->initVar('lang_name', XOBJ_DTYPE_TXTBOX);
40
        $this->initVar('lang_desc', XOBJ_DTYPE_TXTBOX);
41
        $this->initVar('lang_code', XOBJ_DTYPE_TXTBOX);
42
        $this->initVar('lang_charset', XOBJ_DTYPE_TXTBOX);
43
        $this->initVar('lang_image', XOBJ_DTYPE_TXTBOX);
44
    }
45
46
    /**
47
     * @return bool
48
     */
49
    public function prepareVars()
50
    {
51
        foreach ($this->vars as $k => $v) {
52
            $cleanv = $this->cleanVars[$k];
53
            switch ($v['data_type']) {
54
                case XOBJ_DTYPE_TXTBOX:
55
                case XOBJ_DTYPE_TXTAREA:
56
                case XOBJ_DTYPE_SOURCE:
57
                case XOBJ_DTYPE_EMAIL:
58
                    $cleanv = $v['changed'] ? $cleanv : '';
59
                    if (!isset($v['not_gpc']) || !$v['not_gpc']) {
60
                        $cleanv = $this->db->quoteString($cleanv);
61
                    }
62
                    break;
63
                case XOBJ_DTYPE_INT:
64
                    $cleanv = $v['changed'] ? (int)$cleanv : 0;
65
                    break;
66
                case XOBJ_DTYPE_ARRAY:
67
                    $cleanv = $v['changed'] ? $cleanv : serialize(array());
68
                    break;
69
                case XOBJ_DTYPE_STIME:
70
                case XOBJ_DTYPE_MTIME:
71
                case XOBJ_DTYPE_LTIME:
72
                    $cleanv = $v['changed'] ? $cleanv : 0;
73
                    break;
74
75
                default:
76
                    break;
77
            }
78
            $this->cleanVars[$k] =& $cleanv;
79
            unset($cleanv);
80
        }
81
82
        return true;
83
    }
84
85
    public function setBase()
86
    {
87
        $this->isBase = true;
88
    }
89
90
    /**
91
     * @return mixed
92
     */
93
    public function hasBase()
94
    {
95
        return $this->isBase;
96
    }
97
}
98
99
/**
100
 * Class Xlanguage
101
 */
102
class Xlanguage extends Blanguage
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...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
103
{
104
    /**
105
     * Xlanguage constructor.
106
     */
107
    public function __construct()
108
    {
109
        parent::__construct();
110
        $this->table = $this->db->prefix('xlanguage_ext');
111
        $this->initVar('lang_base', XOBJ_DTYPE_TXTBOX);
112
        $this->isBase = false;
113
    }
114
}
115
116
/**
117
 * Class XlanguageLanguageHandler
118
 */
119
class XlanguageLanguageHandler extends XoopsObjectHandler
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...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
120
{
121
    public $cached_config;
122
123
    public function loadConfig()
124
    {
125
        $this->cached_config = $this->loadFileConfig();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this->cached_config is correct as $this->loadFileConfig() (which targets XlanguageLanguageHandler::loadFileConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
126
    }
127
128
    /**
129
     * @param int  $id
130
     * @param bool $isBase
131
     *
132
     * @return Blanguage|null|Xlanguage
133
     */
134
    public function &get($id, $isBase = true)
135
    {
136
        $lang = null;
137
        $id   = (int)$id;
138
        if (!$id) {
139
            return $lang;
140
        }
141
        $prefix = $isBase ? 'xlanguage_base' : 'xlanguage_ext';
142
        if (isset($this->cached_config[$prefix][$id])) {
143
            $array = $this->cached_config[$prefix][$id];
144
        } else {
145
            $sql   = 'SELECT * FROM ' . $this->db->prefix($prefix) . ' WHERE lang_id=' . $id;
146
            $array = $this->db->fetchArray($this->db->query($sql));
147
        }
148
        if (!is_array($array) || count($array) == 0) {
149
            return $lang;
150
        }
151
        $lang = $this->create(false, $isBase);
152
        $lang->assignVars($array);
153
        if ($isBase) {
154
            $lang->isBase = true;
155
        }
156
157
        return $lang;
158
    }
159
160
    /**
161
     * @param $name
162
     *
163
     * @return Blanguage|null|Xlanguage
164
     */
165
    public function &getByName($name)
166
    {
167
        $lang = null;
168
        if (empty($name) || preg_match("/[^a-zA-Z0-9\_\-]/", $name)) {
169
            return $lang;
170
        }
171
        $isBase = false;
172
        if (isset($this->cached_config['xlanguage_base'][$name])) {
173
            $array  = $this->cached_config['xlanguage_base'][$name];
174
            $isBase = true;
175
        } elseif (isset($this->cached_config['xlanguage_ext'][$name])) {
176
            $array = $this->cached_config['xlanguage_ext'][$name];
177
        } elseif (!isset($this->cached_config)) {
178
            $sql    = 'SELECT * FROM ' . $this->db->prefix('xlanguage_base') . ' WHERE lang_name=\'' . $name . '\'';
179
            $result = $this->db->query($sql);
180
            $array  = $this->db->fetchArray($result);
181
            if (!is_array($array) || count($array) == 0) {
182
                $sql    = 'SELECT * FROM ' . $this->db->prefix('xlanguage_ext') . ' WHERE lang_name=\'' . $name . '\'';
183
                $result = $this->db->query($sql);
184
                $array  = $this->db->fetchArray($result);
185
                if (!is_array($array) || count($array) == 0) {
186
                    return $lang;
187
                }
188
            } else {
189
                $isBase = true;
190
            }
191
        }
192
        if (empty($array)) {
193
            return $lang;
194
        }
195
        $lang = $this->create(false, $isBase);
196
        $lang->assignVars($array);
197
        if (!isset($array['lang_base'])) {
198
            $lang->isBase = true;
199
        }
200
201
        return $lang;
202
    }
203
204
    /**
205
     * @param bool $isBase
206
     *
207
     * @return array
208
     */
209
    public function &getAll($isBase = true)
210
    {
211
        $prefix = $isBase ? 'xlanguage_base' : 'xlanguage_ext';
212
        $ret    = array();
213
        if (isset($this->cached_config[$prefix])) {
214
            $array = $this->cached_config[$prefix];
215
            foreach ($array as $lang_name => $myrow) {
216
                $lang = $this->create(false, $isBase);
217
                $lang->assignVars($myrow);
218
                $ret[$myrow['lang_name']] =& $lang;
219
                unset($lang);
220
            }
221
        } elseif (!isset($this->cached_config)) {
222
            $sql    = 'SELECT * FROM ' . $this->db->prefix($prefix);
223
            $result = $this->db->query($sql);
224
            while ($myrow = $this->db->fetchArray($result)) {
225
                $lang = $this->create(false, $isBase);
226
                $lang->assignVars($myrow);
227
                $ret[$myrow['lang_name']] =& $lang;
228
                unset($lang);
229
            }
230
        }
231
232
        return $ret;
233
    }
234
235
    /**
236
     * @return array
237
     */
238
    public function &getAllList()
239
    {
240
        $baseArray =& $this->getAll();
241
242
        $extArray =& $this->getAll(false);
243
        $ret      = array();
244
        if (is_array($baseArray) && count($baseArray) > 0) {
245
            foreach ($baseArray as $base) {
246
                $ret[$base->getVar('lang_name')]['base'] = $base;
247
                unset($base);
248
            }
249
        }
250
        if (is_array($extArray) && count($extArray) > 0) {
251
            foreach ($extArray as $ext) {
252
                $ret[$ext->getVar('lang_base')]['ext'][] = $ext;
253
                unset($ext);
254
            }
255
        }
256
257
        return $ret;
258
    }
259
260
    /**
261
     * @param bool $isNew
262
     * @param bool $isBase
263
     *
264
     * @return Blanguage|Xlanguage
265
     */
266
    public function create($isNew = true, $isBase = true)
267
    {
268
        if ($isBase) {
269
            $lang         = new Blanguage();
270
            $lang->isBase = true;
271
        } else {
272
            $lang = new Xlanguage();
273
        }
274
        if ($isNew) {
275
            $lang->setNew();
276
        }
277
278
        return $lang;
279
    }
280
281
    /**
282
     * @param  XoopsObject $object
283
     * @return bool
284
     * @internal param object $lang
285
     *
286
     */
287
    public function insert(XoopsObject $object)//insert(&$lang)
288
    {
289
        $lang = $object;
290
        if (!$lang->isDirty()) {
291
            return true;
292
        }
293
        if (!$lang->cleanVars()) {
294
            return false;
295
        }
296
        $lang->prepareVars();
297
        foreach ($lang->cleanVars as $k => $v) {
298
            ${$k} = $v;
299
        }
300
301
        if ($lang->isNew()) {
302
            $var_array = array('lang_id', 'weight', 'lang_name', 'lang_desc', 'lang_code', 'lang_charset', 'lang_image', 'lang_base');
303 View Code Duplication
            if ($lang->isBase) {
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...
304
                $var_array = array('lang_id', 'weight', 'lang_name', 'lang_desc', 'lang_code', 'lang_charset', 'lang_image');
305
            }
306
            $lang_id = $this->db->genId($lang->table . '_lang_id_seq');
307
            foreach ($var_array as $var) {
308
                $val_array[] = ${$var};
0 ignored issues
show
Coding Style Comprehensibility introduced by
$val_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $val_array = 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...
309
            }
310
            $sql = 'INSERT INTO ' . $lang->table . ' (' . implode(',', $var_array) . ') VALUES (' . implode(',', $val_array) . ')';
0 ignored issues
show
Bug introduced by
The variable $val_array 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...
311 View Code Duplication
            if (!$result = $this->db->queryF($sql)) {
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...
312
                xoops_error('Insert language error:' . $sql);
313
314
                return false;
315
            }
316
            if ($lang_id == 0) {
317
                $lang_id = $this->db->getInsertId();
318
            }
319
            $lang->setVar('lang_id', $lang_id);
320
        } else {
321
            $var_array = array('weight', 'lang_name', 'lang_desc', 'lang_code', 'lang_charset', 'lang_image', 'lang_base');
322 View Code Duplication
            if ($lang->isBase) {
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...
323
                $var_array = array('weight', 'lang_name', 'lang_desc', 'lang_code', 'lang_charset', 'lang_image');
324
            }
325
            $set_array = array();
326
            foreach ($var_array as $var) {
327
                $set_array[] = "$var = " . ${$var};
328
            }
329
            $set_string = implode(',', $set_array);
330
            $sql        = 'UPDATE ' . $lang->table . ' SET ' . $set_string . ' WHERE lang_id = ' . $lang->getVar('lang_id');
331 View Code Duplication
            if (!$result = $this->db->queryF($sql)) {
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...
332
                xoops_error('update language error:' . $sql);
333
334
                return false;
335
            }
336
        }
337
        $this->createConfig();
338
339
        return $lang->getVar('lang_id');
340
    }
341
342
    /**
343
     * @param  XoopsObject $lang
344
     * @return bool
345
     * @internal param object $lang
346
     *
347
     */
348
    public function delete(XoopsObject $lang)//delete(&$lang)
349
    {
350
        if (!is_object($lang) || !$lang->getVar('lang_id')) {
351
            return true;
352
        }
353
        $sql = 'DELETE FROM ' . $lang->table . ' WHERE lang_id= ' . $lang->getVar('lang_id');
354
        if (!$result = $this->db->query($sql)) {
355
            return false;
356
        }
357
        $this->createConfig();
358
359
        return true;
360
    }
361
362
    /**
363
     * @return array
364
     */
365
    public function getXoopsLangList()
366
    {
367
        return XoopsLists::getLangList();
368
    }
369
370
    /**
371
     * @return bool
372
     */
373
    public function createConfig()
374
    {
375
        $file_config = XLANGUAGE_CONFIG_FILE;
376
        @unlink($file_config);
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...
377
        if (!$fp = fopen($file_config, 'w')) {
378
            echo '<br> the config file can not be created: ' . $file_config;
379
380
            return false;
381
        }
382
383
        $file_content = '<?php';
384
        unset($this->cached_config);
385
        $baseArray =& $this->getAll();
386
        if (is_array($baseArray) && count($baseArray) > 0) {
387
            $file_content .= "\n    \$" . XLANGUAGE_CONFIG_VAR . "['xlanguage_base'] = array(";
388
            foreach ($baseArray as $lang) {
389
                $file_content .= "\n        \"" . $lang->getVar('lang_name') . "\"=>array(";
390
                $file_content .= "\n            \"lang_id\"=>" . $lang->getVar('lang_id') . ',';
391
                $file_content .= "\n            \"weight\"=>" . $lang->getVar('weight') . ',';
392
                $file_content .= "\n            \"lang_name\"=>\"" . $lang->getVar('lang_name') . "\",";
393
                $file_content .= "\n            \"lang_desc\"=>\"" . $lang->getVar('lang_desc') . "\",";
394
                $file_content .= "\n            \"lang_code\"=>\"" . $lang->getVar('lang_code') . "\",";
395
                $file_content .= "\n            \"lang_charset\"=>\"" . $lang->getVar('lang_charset') . "\",";
396
                $file_content .= "\n            \"lang_image\"=>\"" . $lang->getVar('lang_image') . "\"";
397
                $file_content .= "\n        ),";
398
            }
399
            $file_content .= "\n    );";
400
        }
401
402
        $extArray =& $this->getAll(false);
403
        if (is_array($extArray) && count($extArray) > 0) {
404
            $file_content .= "\n    \$" . XLANGUAGE_CONFIG_VAR . "['xlanguage_ext'] = array(";
405
            foreach ($extArray as $lang) {
406
                $file_content .= "\n        \"" . $lang->getVar('lang_name') . "\"=>array(";
407
                $file_content .= "\n            \"lang_id\"=>" . $lang->getVar('lang_id') . ',';
408
                $file_content .= "\n            \"weight\"=>" . $lang->getVar('weight') . ',';
409
                $file_content .= "\n            \"lang_name\"=>\"" . $lang->getVar('lang_name') . "\",";
410
                $file_content .= "\n            \"lang_desc\"=>\"" . $lang->getVar('lang_desc') . "\",";
411
                $file_content .= "\n            \"lang_code\"=>\"" . $lang->getVar('lang_code') . "\",";
412
                $file_content .= "\n            \"lang_charset\"=>\"" . $lang->getVar('lang_charset') . "\",";
413
                $file_content .= "\n            \"lang_image\"=>\"" . $lang->getVar('lang_image') . "\",";
414
                $file_content .= "\n            \"lang_base\"=>\"" . $lang->getVar('lang_base') . "\"";
415
                $file_content .= "\n        ),";
416
            }
417
            $file_content .= "\n    );";
418
        }
419
420
        $file_content .= "\n?>";
421
        fwrite($fp, $file_content);
422
        fclose($fp);
423
424
        return true;
425
    }
426
427
    /**
428
     * @return null
429
     */
430
    public function loadFileConfig()
431
    {
432
        $file_config = XLANGUAGE_CONFIG_FILE;
433
        if (!file_exists($file_config)) {
434
            $this->createConfig();
435
        }
436
        if (!is_readable($file_config)) {
437
            $config = null;
438
439
            return $config;
440
        } else {
441
            include $file_config;
442
            if (isset(${XLANGUAGE_CONFIG_VAR})) {
443
                return ${XLANGUAGE_CONFIG_VAR};
444
            } else {
445
                return false;
446
            }
447
        }
448
    }
449
}
450