Completed
Push — develop ( 5cb106...80f130 )
by Dmytro
13:36
created

functions.php ➔ getLangs()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 12
nop 1
dl 0
loc 29
rs 8.2114
c 0
b 0
f 0
1
<?php
2
if (! function_exists('getLangOptions')) {
3
    /**
4
     * @param string $install_language
5
     * @return string
6
     */
7
    function getLangOptions($install_language = 'english')
8
    {
9
        $langs = array();
10
        if ($handle = opendir(__DIR__ . '/lang/')) {
11
            while (false !== ($file = readdir($handle))) {
12
                if (strpos($file, '.')) {
13
                    $langs[] = str_replace('.inc.php', '', $file);
14
                }
15
            }
16
            closedir($handle);
17
        }
18
        sort($langs);
19
        $_ = array();
20
        foreach ($langs as $language) {
21
            $abrv_language = explode('-', $language);
22
            $selected = ($language === $install_language) ? 'selected' : '';
23
            $_[] = sprintf('<option value="%s" %s>%s</option>', $language, $selected,
24
                    ucwords($abrv_language[0])) . "\n";
25
        }
26
27
        return implode("\n", $_);
28
    }
29
}
30
31
if (! function_exists('install_sessionCheck')) {
32
    function install_sessionCheck()
33
    {
34
        global $_lang;
35
36
        // session loop-back tester
37
        if (!isset($_GET['action']) || $_GET['action'] !== 'mode') {
38
            if (!isset($_SESSION['test']) || $_SESSION['test'] != 1) {
39
                echo '
40
<html>
41
<head>
42
	<title>Install Problem</title>
43
	<style type="text/css">
44
		*{margin:0;padding:0}
45
		body{margin:150px;background:#eee;}
46
		.install{padding:10px;border:3px solid #ffc565;background:#ffddb4;margin:0 auto;text-align:center;}
47
		p{ margin:20px 0; }
48
		a{margin-top:30px;padding:5px;}
49
	</style>
50
</head>
51
<body>
52
	<div class="install">
53
		<p>' . $_lang["session_problem"] . '</p>
54
		<p><a href="./">' . $_lang["session_problem_try_again"] . '</a></p>
55
	</div>
56
</body>
57
</html>';
58
                exit;
59
            }
60
        }
61
    }
62
}
63
64 View Code Duplication
if (!function_exists('parse')) {
65
    /**
66
     * @param string $src
67
     * @param array $ph
68
     * @param string $left
69
     * @param string $right
70
     * @return string
71
     */
72
    function parse($src, $ph, $left = '[+', $right = '+]')
73
    {
74
        foreach ($ph as $k => $v) {
75
            $k = $left . $k . $right;
76
            $src = str_replace($k, $v, $src);
77
        }
78
79
        return $src;
80
    }
81
}
82
83
if (!function_exists('ph')) {
84
    /**
85
     * @return array
86
     */
87
    function ph()
88
    {
89
        global $_lang, $moduleName, $moduleVersion, $modx_textdir, $modx_release_date;
90
        $ph = array();
91
92
        if (isset($_SESSION['installmode'])) {
93
            $installmode = $_SESSION['installmode'];
94
        } else {
95
            $installmode = get_installmode();
96
        }
97
98
        $ph['pagetitle'] = $_lang['modx_install'];
99
        $ph['textdir'] = $modx_textdir ? ' id="rtl"' : '';
100
        $ph['help_link'] = $installmode == 0 ? $_lang['help_link_new'] : $_lang['help_link_upd'];
101
        $ph['version'] = $moduleVersion;
102
        $ph['release_date'] = ($modx_textdir ? '&rlm;' : '') . $modx_release_date;
103
        $ph['footer1'] = $_lang['modx_footer1'];
104
        $ph['footer2'] = $_lang['modx_footer2'];
105
        $ph['current_year'] = date('Y');
106
107
        return $ph;
108
    }
109
}
110
111
if (!function_exists('get_installmode')) {
112
    /**
113
     * @return int
114
     */
115
    function get_installmode()
116
    {
117
        global $base_path, $database_server, $database_user, $database_password, $dbase, $table_prefix;
118
119
        $conf_path = "{$base_path}manager/includes/config.inc.php";
120
        if (!is_file($conf_path)) {
121
            $installmode = 0;
122
        } elseif (isset($_POST['installmode'])) {
123
            $installmode = $_POST['installmode'];
124
        } else {
125
            include_once("{$base_path}manager/includes/config.inc.php");
126
127
            if (!isset($dbase) || empty($dbase)) {
128
                $installmode = 0;
129
            } else {
130
                $conn = mysqli_connect($database_server, $database_user, $database_password);
131
                if ($conn) {
132
                    $_SESSION['database_server'] = $database_server;
133
                    $_SESSION['database_user'] = $database_user;
134
                    $_SESSION['database_password'] = $database_password;
135
136
                    $dbase = trim($dbase, '`');
137
                    $rs = mysqli_select_db($conn, $dbase);
138
                } else {
139
                    $rs = false;
140
                }
141
142
                if ($rs) {
143
                    $_SESSION['dbase'] = $dbase;
144
                    $_SESSION['table_prefix'] = $table_prefix;
145
                    $_SESSION['database_collation'] = 'utf8_general_ci';
146
                    $_SESSION['database_connection_method'] = 'SET CHARACTER SET';
147
148
                    $tbl_system_settings = "`{$dbase}`.`{$table_prefix}system_settings`";
149
                    $rs = mysqli_query($conn,
150
                        "SELECT setting_value FROM {$tbl_system_settings} WHERE setting_name='settings_version'");
151
                    if ($rs) {
152
                        $row = mysqli_fetch_assoc($rs);
153
                        $settings_version = $row['setting_value'];
154
                    } else {
155
                        $settings_version = '';
156
                    }
157
158
                    if (empty($settings_version)) {
159
                        $installmode = 0;
160
                    } else {
161
                        $installmode = 1;
162
                    }
163
                } else {
164
                    $installmode = 1;
165
                }
166
            }
167
        }
168
169
        return $installmode;
170
    }
171
}
172
173
if (!function_exists('getLangs')) {
174
    /**
175
     * @param string $install_language
176
     * @return string
177
     */
178
    function getLangs($install_language)
179
    {
180
        if ($install_language !== "english" && is_file(sprintf("../%s/includes/lang/%s.inc.php", MGR_DIR,
181
                $install_language))) {
182
            $manager_language = $install_language;
183
        } else {
184
            $manager_language = "english";
185
        }
186
        $langs = array();
187
        if ($handle = opendir(dirname(dirname(__DIR__)) . '/' . MGR_DIR . '/includes/lang')) {
188
            while (false !== ($file = readdir($handle))) {
189
                if (strpos($file, '.inc.') !== false) {
190
                    $langs[] = $file;
191
                }
192
            }
193
            closedir($handle);
194
        }
195
        sort($langs);
196
197
        $_ = array();
198
        foreach ($langs as $language) {
199
            $abrv_language = explode('.', $language);
200
            $selected = (strtolower($abrv_language[0]) == strtolower($manager_language)) ? ' selected' : '';
201
            $_[] = sprintf('<option value="%s" %s>%s</option>', $abrv_language[0], $selected,
202
                ucwords($abrv_language[0]));
203
        }
204
205
        return implode("\n", $_);
206
    }
207
}
208
209
if (!function_exists('sortItem')) {
210
    function sortItem($array = array(), $order = 'utf8mb4,utf8')
211
    {
212
        $rs = array('recommend' => '');
213
        $order = explode(',', $order);
214
        foreach ($order as $v) {
215
            foreach ($array as $name => $sel) {
216
                if (strpos($name, $v) !== false) {
217
                    $rs[$name] = $array[$name];
218
                    unset($array[$name]);
219
                }
220
            }
221
        }
222
        $rs['unrecommend'] = '';
223
224
        return $rs + $array;
225
    }
226
}
227
228
if (!function_exists('getTemplates')) {
229
    /**
230
     * @param array $presets
231
     * @return string
232
     */
233
    function getTemplates($presets = array())
234
    {
235
        if (empty($presets)) {
236
            return '';
237
        }
238
        $selectedTemplates = isset ($_POST['template']) ? $_POST['template'] : array();
239
        $tpl = '<label><input type="checkbox" name="template[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+desc+]</label><hr />';
240
        $_ = array();
241
        $i = 0;
242
        $ph = array();
243
        foreach ($presets as $preset) {
244
            $ph['i'] = $i;
245
            $ph['name'] = isset($preset[0]) ? $preset[0] : '';
246
            $ph['desc'] = isset($preset[1]) ? $preset[1] : '';
247
            $ph['class'] = !in_array('sample', $preset[6]) ? 'toggle' : 'toggle demo';
248
            $ph['checked'] = in_array($i, $selectedTemplates) || (!isset($_POST['options_selected'])) ? 'checked' : '';
249
            $_[] = parse($tpl, $ph);
250
            $i++;
251
        }
252
253
        return (0 < count($_)) ? '<h3>[%templates%]</h3>' . implode("\n", $_) : '';
254
    }
255
}
256
257
if (!function_exists('getTVs')) {
258
    /**
259
     * @param array $presets
260
     * @return string
261
     */
262
    function getTVs($presets = array())
263
    {
264
        if (empty($presets)) {
265
            return '';
266
        }
267
        $selectedTvs = isset ($_POST['tv']) ? $_POST['tv'] : array();
268
        $tpl = '<label><input type="checkbox" name="tv[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+alterName+] <span class="description">([+desc+])</span></label><hr />';
269
        $_ = array();
270
        $i = 0;
271
        $ph = array();
272
        foreach ($presets as $preset) {
273
            $ph['i'] = $i;
274
            $ph['name'] = $preset[0];
275
            $ph['alterName'] = $preset[1];
276
            $ph['desc'] = $preset[2];
277
            $ph['class'] = !in_array('sample', $preset[12]) ? 'toggle' : 'toggle demo';
278
            $ph['checked'] = in_array($i, $selectedTvs) || (!isset($_POST['options_selected'])) ? 'checked' : '';
279
            $_[] = parse($tpl, $ph);
280
            $i++;
281
        }
282
283
        return (0 < count($_)) ? '<h3>[%tvs%]</h3>' . implode("\n", $_) : '';
284
    }
285
}
286
287 View Code Duplication
if (!function_exists('getChunks')) {
288
    /**
289
     * display chunks
290
     *
291
     * @param array $presets
292
     * @return string
293
     */
294
    function getChunks($presets = array())
295
    {
296
        if (empty($presets)) {
297
            return '';
298
        }
299
        $selected = isset ($_POST['chunk']) ? $_POST['chunk'] : array();
300
        $tpl = '<label><input type="checkbox" name="chunk[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+desc+]</label><hr />';
301
        $_ = array();
302
        $i = 0;
303
        $ph = array();
304
        foreach ($presets as $preset) {
305
            $ph['i'] = $i;
306
            $ph['name'] = $preset[0];
307
            $ph['desc'] = $preset[1];
308
            $ph['class'] = !in_array('sample', $preset[5]) ? 'toggle' : 'toggle demo';
309
            $ph['checked'] = in_array($i, $selected) || (!isset($_POST['options_selected'])) ? 'checked' : '';
310
            $_[] = parse($tpl, $ph);
311
            $i++;
312
        }
313
314
        return (0 < count($_)) ? '<h3>[%chunks%]</h3>' . implode("\n", $_) : '';
315
    }
316
}
317
318 View Code Duplication
if (!function_exists('getModules')) {
319
    /**
320
     * display modules
321
     *
322
     * @param array $presets
323
     * @return string
324
     */
325
    function getModules($presets = array())
326
    {
327
        if (empty($presets)) {
328
            return '';
329
        }
330
        $selected = isset ($_POST['module']) ? $_POST['module'] : array();
331
        $tpl = '<label><input type="checkbox" name="module[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+desc+]</label><hr />';
332
        $_ = array();
333
        $i = 0;
334
        $ph = array();
335
        foreach ($presets as $preset) {
336
            $ph['i'] = $i;
337
            $ph['name'] = $preset[0];
338
            $ph['desc'] = $preset[1];
339
            $ph['class'] = !in_array('sample', $preset[7]) ? 'toggle' : 'toggle demo';
340
            $ph['checked'] = in_array($i, $selected) || (!isset($_POST['options_selected'])) ? 'checked' : '';
341
            $_[] = parse($tpl, $ph);
342
            $i++;
343
        }
344
345
        return (0 < count($_)) ? '<h3>[%modules%]</h3>' . implode("\n", $_) : '';
346
    }
347
}
348
349
if (!function_exists('getPlugins')) {
350
    /**
351
     * display plugins
352
     *
353
     * @param array $presets
354
     * @return string
355
     */
356
    function getPlugins($presets = array())
357
    {
358
        if (!count($presets)) {
359
            return '';
360
        }
361
        $selected = isset ($_POST['plugin']) ? $_POST['plugin'] : array();
362
        $tpl = '<label><input type="checkbox" name="plugin[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+desc+]</label><hr />';
363
        $_ = array();
364
        $i = 0;
365
        $ph = array();
366
        foreach ($presets as $preset) {
367
            $ph['i'] = $i;
368
            $ph['name'] = $preset[0];
369
            $ph['desc'] = $preset[1];
370
            if (is_array($preset[8])) {
371
                $ph['class'] = !in_array('sample', $preset[8]) ? 'toggle' : 'toggle demo';
372
            } else {
373
                $ph['class'] = 'toggle demo';
374
            }
375
            $ph['checked'] = in_array($i, $selected) || (!isset($_POST['options_selected'])) ? 'checked' : '';
376
            $_[] = parse($tpl, $ph);
377
            $i++;
378
        }
379
380
        return (0 < count($_)) ? '<h3>[%plugins%]</h3>' . implode("\n", $_) : '';
381
    }
382
}
383
384 View Code Duplication
if (!function_exists('getSnippets')) {
385
    /**
386
     * display snippets
387
     *
388
     * @param array $presets
389
     * @return string
390
     */
391
    function getSnippets($presets = array())
392
    {
393
        if (!count($presets)) {
394
            return '';
395
        }
396
        $selected = isset ($_POST['snippet']) ? $_POST['snippet'] : array();
397
        $tpl = '<label><input type="checkbox" name="snippet[]" value="[+i+]" class="[+class+]" [+checked+] />[%install_update%] <span class="comname">[+name+]</span> - [+desc+]</label><hr />';
398
        $_ = array();
399
        $i = 0;
400
        $ph = array();
401
        foreach ($presets as $preset) {
402
            $ph['i'] = $i;
403
            $ph['name'] = $preset[0];
404
            $ph['desc'] = $preset[1];
405
            $ph['class'] = !in_array('sample', $preset[5]) ? 'toggle' : 'toggle demo';
406
            $ph['checked'] = in_array($i, $selected) || (!isset($_POST['options_selected'])) ? 'checked' : '';
407
            $_[] = parse($tpl, $ph);
408
            $i++;
409
        }
410
411
        return (0 < count($_)) ? '<h3>[%snippets%]</h3>' . implode("\n", $_) : '';
412
    }
413
}
414
415
if (!function_exists('clean_up')) {
416
    function clean_up($sqlParser)
417
    {
418
        $ids = array();
419
420
        // secure web documents - privateweb
421
        mysqli_query($sqlParser->conn,
422
            "UPDATE `" . $sqlParser->prefix . "site_content` SET privateweb = 0 WHERE privateweb = 1");
423
        $sql = "SELECT DISTINCT sc.id
424
             FROM `" . $sqlParser->prefix . "site_content` sc
425
             LEFT JOIN `" . $sqlParser->prefix . "document_groups` dg ON dg.document = sc.id
426
             LEFT JOIN `" . $sqlParser->prefix . "webgroup_access` wga ON wga.documentgroup = dg.document_group
427
             WHERE wga.id>0";
428
        $ds = mysqli_query($sqlParser->conn, $sql);
429
        if (!$ds) {
430
            echo "An error occurred while executing a query: " . mysqli_error($sqlParser->conn);
431
        } else {
432
            while ($r = mysqli_fetch_assoc($ds)) {
433
                $ids[] = $r["id"];
434
            }
435
            if (count($ids) > 0) {
436
                mysqli_query($sqlParser->conn,
437
                    "UPDATE `" . $sqlParser->prefix . "site_content` SET privateweb = 1 WHERE id IN (" . implode(", ",
438
                        $ids) . ")");
439
                unset($ids);
440
            }
441
        }
442
443
        // secure manager documents privatemgr
444
        mysqli_query($sqlParser->conn,
445
            "UPDATE `" . $sqlParser->prefix . "site_content` SET privatemgr = 0 WHERE privatemgr = 1");
446
        $sql = "SELECT DISTINCT sc.id
447
             FROM `" . $sqlParser->prefix . "site_content` sc
448
             LEFT JOIN `" . $sqlParser->prefix . "document_groups` dg ON dg.document = sc.id
449
             LEFT JOIN `" . $sqlParser->prefix . "membergroup_access` mga ON mga.documentgroup = dg.document_group
450
             WHERE mga.id>0";
451
        $ds = mysqli_query($sqlParser->conn, $sql);
452
        if (!$ds) {
453
            echo "An error occurred while executing a query: " . mysqli_error($sqlParser->conn);
454
        } else {
455
            while ($r = mysqli_fetch_assoc($ds)) {
456
                $ids[] = $r["id"];
457
            }
458
            if (count($ids) > 0) {
459
                mysqli_query($sqlParser->conn,
460
                    "UPDATE `" . $sqlParser->prefix . "site_content` SET privatemgr = 1 WHERE id IN (" . implode(", ",
461
                        $ids) . ")");
462
                unset($ids);
463
            }
464
        }
465
    }
466
}
467
468
if (!function_exists('parse_docblock')) {
469
    function parse_docblock($element_dir, $filename)
470
    {
471
        $params = array();
472
        $fullpath = $element_dir . '/' . $filename;
473
        if (is_readable($fullpath)) {
474
            $tpl = @fopen($fullpath, "r");
475
            if ($tpl) {
476
                $params['filename'] = $filename;
477
                $docblock_start_found = false;
478
                $name_found = false;
479
                $description_found = false;
480
481
                while (!feof($tpl)) {
482
                    $line = fgets($tpl);
483
                    if (!$docblock_start_found) {
484
                        // find docblock start
485
                        if (strpos($line, '/**') !== false) {
486
                            $docblock_start_found = true;
487
                        }
488
                        continue;
489
                    } elseif (!$name_found) {
490
                        // find name
491
                        $ma = null;
492
                        if (preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
493
                            $params['name'] = trim($ma[1]);
494
                            $name_found = !empty($params['name']);
495
                        }
496
                        continue;
497
                    } elseif (!$description_found) {
498
                        // find description
499
                        $ma = null;
500
                        if (preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
501
                            $params['description'] = trim($ma[1]);
502
                            $description_found = !empty($params['description']);
503
                        }
504
                        continue;
505
                    } else {
506
                        $ma = null;
507
                        if (preg_match("/^\s+\*\s+\@([^\s]+)\s+(.+)/", $line, $ma)) {
508
                            $param = trim($ma[1]);
509
                            $val = trim($ma[2]);
510
                            if (!empty($param) && !empty($val)) {
511
                                if ($param == 'internal') {
512
                                    $ma = null;
513
                                    if (preg_match("/\@([^\s]+)\s+(.+)/", $val, $ma)) {
514
                                        $param = trim($ma[1]);
515
                                        $val = trim($ma[2]);
516
                                    }
517
                                    //if($val !== '0' && (empty($param) || empty($val))) {
518
                                    if (empty($param)) {
519
                                        continue;
520
                                    }
521
                                }
522
                                $params[$param] = $val;
523
                            }
524
                        } elseif (preg_match("/^\s*\*\/\s*$/", $line)) {
525
                            break;
526
                        }
527
                    }
528
                }
529
                @fclose($tpl);
530
            }
531
        }
532
533
        return $params;
534
    }
535
}
536
537 View Code Duplication
if (!function_exists('propertiesNameValue')) {
538
    /**
539
     * parses a resource property string and returns the result as an array
540
     * duplicate of method in documentParser class
541
     *
542
     * @param string $propertyString
543
     * @return array
544
     */
545
    function propertiesNameValue($propertyString)
0 ignored issues
show
Best Practice introduced by
The function propertiesNameValue() has been defined more than once; this definition is ignored, only the first definition in install/cli-install.php (L542-565) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
546
    {
547
        $parameter = array();
548
        if (!empty ($propertyString)) {
549
            $tmpParams = explode("&", $propertyString);
550
            $countParams = count($tmpParams);
551
            for ($x = 0; $x < $countParams; $x++) {
552
                if (strpos($tmpParams[$x], '=', 0)) {
553
                    $pTmp = explode("=", $tmpParams[$x]);
554
                    $pvTmp = explode(";", trim($pTmp[1]));
555
                    if ($pvTmp[1] == 'list' && $pvTmp[3] != "") {
556
                        $parameter[trim($pTmp[0])] = $pvTmp[3];
557
                    } //list default
558
                    else {
559
                        if ($pvTmp[1] != 'list' && $pvTmp[2] != "") {
560
                            $parameter[trim($pTmp[0])] = $pvTmp[2];
561
                        }
562
                    }
563
                }
564
            }
565
        }
566
567
        return $parameter;
568
    }
569
}
570
571
if (!function_exists('propUpdate')) {
572
    /**
573
     * Property Update function
574
     *
575
     * @param string $new
576
     * @param string $old
577
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|integer?

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...
578
     */
579
    function propUpdate($new, $old)
580
    {
581
        $newArr = parseProperties($new);
582
        $oldArr = parseProperties($old);
583
        foreach ($oldArr as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $oldArr of type string|array 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...
584
            if (isset($v['0']['options'])) {
585
                $oldArr[$k]['0']['options'] = $newArr[$k]['0']['options'];
586
            }
587
        }
588
        $return = $oldArr + $newArr;
589
        $return = json_encode($return, JSON_UNESCAPED_UNICODE);
0 ignored issues
show
Unused Code introduced by
The call to json_encode() has too many arguments starting with JSON_UNESCAPED_UNICODE.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
590
        $return = ($return !== '[]') ? $return : '';
591
592
        return $return;
593
    }
594
}
595
596
if (!function_exists('parseProperties')) {
597
    /**
598
     * @param string $propertyString
599
     * @param bool|mixed $json
600
     * @return string|array
601
     */
602
    function parseProperties($propertyString, $json = false)
603
    {
604
        $propertyString = str_replace('{}', '', $propertyString);
605
        $propertyString = str_replace('} {', ',', $propertyString);
606
607
        if (empty($propertyString) || $propertyString == '{}' || $propertyString == '[]') {
608
            $propertyString = '';
609
        }
610
611
        $jsonFormat = isJson($propertyString, true);
612
        $property = array();
613
        // old format
614
        if ($jsonFormat === false) {
615
            $props = explode('&', $propertyString);
616
            foreach ($props as $prop) {
617
                $prop = trim($prop);
618
                if ($prop === '') {
619
                    continue;
620
                }
621
622
                $arr = explode(';', $prop);
623
                if (!is_array($arr)) {
624
                    $arr = array();
625
                }
626
                $key = explode('=', isset($arr[0]) ? $arr[0] : '');
627
                if (!is_array($key) || empty($key[0])) {
628
                    continue;
629
                }
630
631
                $property[$key[0]]['0']['label'] = isset($key[1]) ? trim($key[1]) : '';
632
                $property[$key[0]]['0']['type'] = isset($arr[1]) ? trim($arr[1]) : '';
633
                switch ($property[$key[0]]['0']['type']) {
634
                    case 'list':
635
                    case 'list-multi':
636
                    case 'checkbox':
637
                    case 'radio':
638
                    case 'menu':
639
                        $property[$key[0]]['0']['value'] = isset($arr[3]) ? trim($arr[3]) : '';
640
                        $property[$key[0]]['0']['options'] = isset($arr[2]) ? trim($arr[2]) : '';
641
                        $property[$key[0]]['0']['default'] = isset($arr[3]) ? trim($arr[3]) : '';
642
                        break;
643
                    default:
644
                        $property[$key[0]]['0']['value'] = isset($arr[2]) ? trim($arr[2]) : '';
645
                        $property[$key[0]]['0']['default'] = isset($arr[2]) ? trim($arr[2]) : '';
646
                }
647
                $property[$key[0]]['0']['desc'] = '';
648
649
            }
650
            // new json-format
651
        } else {
652
            if (!empty($jsonFormat)) {
653
                $property = $jsonFormat;
654
            }
655
        }
656
657
        if ($json) {
658
            $property = json_encode($property, JSON_UNESCAPED_UNICODE);
0 ignored issues
show
Unused Code introduced by
The call to json_encode() has too many arguments starting with JSON_UNESCAPED_UNICODE.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
659
        }
660
        $property = ($property !== '[]') ? $property : '';
661
662
        return $property;
663
    }
664
}
665
666
if (!function_exists('isJson')) {
667
    /**
668
     * @param string $string
669
     * @param bool $returnData
670
     * @return bool|mixed
671
     */
672
    function isJson($string, $returnData = false)
673
    {
674
        $data = json_decode($string, true);
675
676
        return (json_last_error() == JSON_ERROR_NONE) ? ($returnData ? $data : true) : false;
677
    }
678
}
679
680
if (!function_exists('getCreateDbCategory')) {
681
    /**
682
     * @param string|int $category
683
     * @param SqlParser $sqlParser
684
     * @return int
685
     */
686
    function getCreateDbCategory($category, $sqlParser)
687
    {
688
        $dbase = $sqlParser->dbname;
689
        $dbase = '`' . trim($dbase, '`') . '`';
690
        $table_prefix = $sqlParser->prefix;
691
        $category_id = 0;
692
        if (!empty($category)) {
693
            $category = mysqli_real_escape_string($sqlParser->conn, $category);
694
            $rs = mysqli_query($sqlParser->conn,
695
                "SELECT id FROM $dbase.`" . $table_prefix . "categories` WHERE category = '" . $category . "'");
696
            if (mysqli_num_rows($rs) && ($row = mysqli_fetch_assoc($rs))) {
697
                $category_id = $row['id'];
698
            } else {
699
                $q = "INSERT INTO $dbase.`" . $table_prefix . "categories` (`category`) VALUES ('{$category}');";
700
                $rs = mysqli_query($sqlParser->conn, $q);
701
                if ($rs) {
702
                    $category_id = mysqli_insert_id($sqlParser->conn);
703
                }
704
            }
705
        }
706
707
        return $category_id;
708
    }
709
}
710
711
if (!function_exists('removeDocblock')) {
712
    /**
713
     * Remove installer Docblock only from components using plugin FileSource / fileBinding
714
     *
715
     * @param string $code
716
     * @param string $type
717
     * @return string
718
     */
719
    function removeDocblock($code, $type)
720
    {
721
722
        $cleaned = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', $code, 1);
723
724
        // Procedure taken from plugin.filesource.php
725
        switch ($type) {
726
            case 'snippet':
727
                $elm_name = 'snippets';
728
                $include = 'return require';
729
                $count = 47;
730
                break;
731
732
            case 'plugin':
733
                $elm_name = 'plugins';
734
                $include = 'require';
735
                $count = 39;
736
                break;
737
738
            default:
739
                return $cleaned;
740
        };
741
        if (substr(trim($cleaned), 0, $count) == $include . ' MODX_BASE_PATH.\'assets/' . $elm_name . '/') {
742
            return $cleaned;
743
        }
744
745
        // fileBinding not found - return code incl docblock
746
        return $code;
747
    }
748
}
749
750
if (!function_exists('removeFolder')) {
751
    /**
752
     * RemoveFolder
753
     *
754
     * @param string $path
755
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

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...
756
     */
757
    function removeFolder($path)
758
    {
759
        $dir = realpath($path);
760
        if (!is_dir($dir)) {
761
            return;
762
        }
763
764
        $it = new RecursiveDirectoryIterator($dir);
765
        $files = new RecursiveIteratorIterator($it,
766
            RecursiveIteratorIterator::CHILD_FIRST);
767
        foreach ($files as $file) {
768
            if ($file->getFilename() === "." || $file->getFilename() === "..") {
769
                continue;
770
            }
771
            if ($file->isDir()) {
772
                rmdir($file->getRealPath());
773
            } else {
774
                unlink($file->getRealPath());
775
            }
776
        }
777
        rmdir($dir);
778
    }
779
}
780