Completed
Push — develop ( acc675...3313cf )
by Dmytro
12:18
created

cli-install.php ➔ f_owc()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 14
Ratio 87.5 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 6
nop 3
dl 14
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * EVO Cli Installer
4
 * php cli-install.php --database_server=localhost --database=db --database_user=dbuser --database_password=dbpass
5
 * --table_prefix=evo_ --cmsadmin=admin [email protected] --cmspassword=123456 --language=ru --mode=new
6
 * --installData=n --removeInstall=y
7
 */
8
9
$self = 'install/cli-install.php';
10
$path = __DIR__ . '/';
11
$base_path = dirname(__DIR__) . '/';
12
define('MODX_API_MODE', true);
13
define('MODX_BASE_PATH', $base_path);
14
define('MODX_SITE_URL', '/');
15
16
require_once 'src/functions.php';
17
18
// set error reporting
19
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
20
21
if (is_file($base_path . "assets/cache/siteManager.php")) {
22
    include_once($base_path . "assets/cache/siteManager.php");
23
}
24
if (!defined('MGR_DIR') && is_dir($base_path . "manager")) {
25
    define('MGR_DIR', 'manager');
26
}
27
28
require_once 'src/lang.php';
29
require_once($base_path . MGR_DIR . '/includes/version.inc.php');
30
31
$moduleName = "EVO";
32
$moduleVersion = $modx_branch . ' ' . $modx_version;
33
$moduleRelease = $modx_release_date;
34
$moduleSQLBaseFile = $path . '/src/stubs/sql/setup.sql';
35
$moduleSQLDataFile = $path . 'src/stubs/sql/setup.data.sql';
36
$moduleSQLResetFile = $path . 'src/stubs/sql/setup.data.reset.sql';
37
38
$moduleChunks = array(); // chunks - array : name, description, type - 0:file or 1:content, file or content
39
$moduleTemplates = array(); // templates - array : name, description, type - 0:file or 1:content, file or content
40
$moduleSnippets = array(); // snippets - array : name, description, type - 0:file or 1:content, file or content,properties
41
$modulePlugins = array(); // plugins - array : name, description, type - 0:file or 1:content, file or content,properties, events,guid
42
$moduleModules = array(); // modules - array : name, description, type - 0:file or 1:content, file or content,properties, guid
43
$moduleTemplates = array(); // templates - array : name, description, type - 0:file or 1:content, file or content,properties
44
$moduleTVs = array(); // template variables - array : name, description, type - 0:file or 1:content, file or content,properties
45
$moduleDependencies = array(); // module depedencies - array : module, table, column, type, name
46
$errors = 0;
47
48
49
$installMode = 0;
50
$installData = 0;
51
$tableprefixauto = base_convert(rand(10, 20), 10, 36) . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'),
52
        rand(0, 33), 3) . '_';
53
54
$args = array_slice($argv, 1);
55
56
if (empty($args)) {
57
    echo 'Install Evolution CMS' . PHP_EOL;
58
    //$installYes = readline("Type 'y' to continue: ");
59
    //if ($installYes != 'y') return;
60
61
    //set param manual
62
    $databasehost = readline($_lang['connection_screen_database_host'] . ' [localhost] ');
63
    $databaseloginname = readline($_lang['connection_screen_database_login'] . ' ');
64
    $databaseloginpassword = readline($_lang['connection_screen_database_pass'] . ' ');
65
    $database_name = readline($_lang['connection_screen_database_name'] . ' ');
66
    $tableprefix = readline($_lang['connection_screen_table_prefix'] . ' [' . $tableprefixauto . '] ');
67
    $database_connection_method = readline($_lang['connection_screen_connection_method'] . ' [SET CHARACTER SET] ');
68
    $database_collation = readline($_lang['connection_screen_collation'] . ' [utf8_general_ci] ');
69
    $cmsadmin = readline($_lang['connection_screen_default_admin_login'] . ' [admin] ');
70
    $cmsadminemail = readline($_lang['connection_screen_default_admin_email'] . ' ');
71
    $cmspassword = readline($_lang['connection_screen_default_admin_password'] . ' ');
72
    $managerlanguage = readline('Мanager language:' . ' [en] ');
73
    $installData = readline('Instal demo-site (y/n):' . ' [n] ');
74
75
} else {
76
77
    $cli_variables = [];
78
    foreach ($args as $arg) {
79
        $tmp = array_map('trim', explode('=', $arg));
80
        if (count($tmp) === 2) {
81
            $k = ltrim($tmp[0], '-');
82
83
            $cli_variables[$k] = $tmp[1];
84
85
        }
86
    }
87
88
    $databasehost = $cli_variables['database_server'];
89
    $databaseloginname = $cli_variables['database_user'];
90
    $databaseloginpassword = $cli_variables['database_password'];
91
    $database_name = $cli_variables['database'];
92
    $tableprefix = $cli_variables['table_prefix'];
93
94
    $cmsadmin = $cli_variables['cmsadmin'];
95
    $cmsadminemail = $cli_variables['cmsadminemail'];
96
    $cmspassword = $cli_variables['cmspassword'];
97
98
    $managerlanguage = $cli_variables['language'];
99
    $installData = $cli_variables['installData'];
100
    $mode = $cli_variables['mode'];
101
    $removeInstall = $cli_variables['removeInstall'];
102
103
}
104
105
106
if ($databasehost == '') {
107
    $databasehost = 'localhost';
108
}
109
if ($tableprefix == '') {
110
    $tableprefix = $tableprefixauto;
111
}
112
if ($database_connection_method == '') {
113
    $database_connection_method = 'SET CHARACTER SET';
114
}
115
if ($database_collation == '') {
116
    $database_collation = 'utf8_general_ci';
117
}
118
if ($cmsadmin == '') {
119
    $cmsadmin = 'admin';
120
}
121
if ($managerlanguage == '') {
122
    $managerlanguage = 'en';
123
}
124
if ($installData == 'y') {
125
    $installData = 1;
126
}
127
if ($mode == 'upgrade') {
128
    $installMode = 1;
129
}
130
131
//добавить обработку языка
132
133
switch ($managerlanguage) {
134
    case 'ru':
135
        $managerlanguage = 'russian-UTF8';
136
        break;
137
138
    case 'en':
139
    default:
140
        $managerlanguage = 'english';
141
        break;
142
}
143
144
//////////////////////////////////////////////////////////////////////////////////////
145 View Code Duplication
if (!function_exists('f_owc')) {
146
    /**
147
     * @param $path
148
     * @param $data
149
     * @param null|int $mode
150
     */
151
    function f_owc($path, $data, $mode = null)
152
    {
153
        try {
154
            // make an attempt to create the file
155
            $hnd = fopen($path, 'w');
156
            fwrite($hnd, $data);
157
            fclose($hnd);
158
159
            if (null !== $mode) {
160
                chmod($path, $mode);
161
            }
162
        } catch (Exception $e) {
163
            // Nothing, this is NOT normal
164
            unset($e);
165
        }
166
    }
167
}
168
169
// check PHP version
170
define('PHP_MIN_VERSION', '5.4.0');
171
$phpMinVersion = PHP_MIN_VERSION; // Maybe not necessary. For backward compatibility
172
echo PHP_EOL . $_lang['checking_php_version'];
173
// -1 if left is less, 0 if equal, +1 if left is higher
174
if (version_compare(phpversion(), PHP_MIN_VERSION) < 0) {
175
    $errors++;
176
    $tmp = $_lang['you_running_php'] . phpversion() . str_replace('[+min_version+]', PHP_MIN_VERSION,
177
            $_lang["modx_requires_php"]);
178
    echo $_lang['failed'] . ' ' . $tmp . PHP_EOL;
179
} else {
180
    echo $_lang['ok'] . PHP_EOL;
181
}
182
183
// check directories
184
// cache exists?
185
echo strip_tags($_lang['checking_if_cache_exist']);
186 View Code Duplication
if (!file_exists($path . "../assets/cache") || !file_exists($path . "../assets/cache/rss")) {
187
    echo $_lang['failed'] . PHP_EOL;
188
    $errors++;
189
} else {
190
    echo $_lang['ok'] . PHP_EOL;
191
}
192
193
194
// cache writable?
195
echo strip_tags($_lang['checking_if_cache_writable']);
196 View Code Duplication
if (!is_writable($path . "../assets/cache")) {
197
    $errors++;
198
    echo $_lang['failed'] . PHP_EOL;
199
} else {
200
    echo $_lang['ok'] . PHP_EOL;
201
}
202
203
204
// cache files writable?
205
echo strip_tags($_lang['checking_if_cache_file_writable']);
206
$tmp = $path . "../assets/cache/siteCache.idx.php";
207
if (!file_exists($tmp)) {
208
    f_owc($tmp, "<?php //EVO site cache file ?>");
209
}
210 View Code Duplication
if (!is_writable($tmp)) {
211
    $errors++;
212
    echo $_lang['failed'] . PHP_EOL;
213
} else {
214
    echo $_lang['ok'] . PHP_EOL;
215
}
216
217
218
echo strip_tags($_lang['checking_if_cache_file2_writable']);
219 View Code Duplication
if (!is_writable($path . "../assets/cache/sitePublishing.idx.php")) {
220
    $errors++;
221
    echo $_lang['failed'] . PHP_EOL;
222
} else {
223
    echo $_lang['ok'] . PHP_EOL;
224
}
225
226
227
// File Browser directories exists?
228
echo strip_tags($_lang['checking_if_images_exist']);
229 View Code Duplication
switch (true) {
230
    case !file_exists($path . "../assets/images"):
231
    case !file_exists($path . "../assets/files"):
232
    case !file_exists($path . "../assets/backup"):
233
        //case !file_exists("../assets/.thumbs"):
234
        $errors++;
235
        echo $_lang['failed'] . PHP_EOL;
236
        break;
237
    default:
238
        echo $_lang['ok'] . PHP_EOL;
239
}
240
241
242
// File Browser directories writable?
243
echo strip_tags($_lang['checking_if_images_writable']);
244 View Code Duplication
switch (true) {
245
    case !is_writable($path . "../assets/images"):
246
    case !is_writable($path . "../assets/files"):
247
    case !is_writable($path . "../assets/backup"):
248
        //case !is_writable("../assets/.thumbs"):
249
        $errors++;
250
        echo $_lang['failed'] . PHP_EOL;
251
        break;
252
    default:
253
        echo $_lang['ok'] . PHP_EOL;
254
}
255
256
257
// export exists?
258
echo strip_tags($_lang['checking_if_export_exists']);
259 View Code Duplication
if (!file_exists($path . "../assets/export")) {
260
    echo $_lang['failed'] . PHP_EOL;
261
    $errors++;
262
} else {
263
    echo $_lang['ok'] . PHP_EOL;
264
}
265
266
267
// export writable?
268
echo strip_tags($_lang['checking_if_export_writable']);
269 View Code Duplication
if (!is_writable($path . "../assets/export")) {
270
    echo $_lang['failed'] . PHP_EOL;
271
    $errors++;
272
} else {
273
    echo $_lang['ok'] . PHP_EOL;
274
}
275
276
277
// config.inc.php writable?
278
echo strip_tags($_lang['checking_if_config_exist_and_writable']);
279
$tmp = $path . "../" . MGR_DIR . "/includes/config.inc.php";
280 View Code Duplication
if (!is_file($tmp)) {
281
    f_owc($tmp, "<?php //EVO configuration file ?>", 0666);
282
} else {
283
    @chmod($tmp, 0666);
284
}
285
$isWriteable = is_writable($tmp);
286 View Code Duplication
if (!$isWriteable) {
287
    $errors++;
288
    echo $_lang['failed'] . PHP_EOL;
289
} else {
290
    echo $_lang['ok'] . PHP_EOL;
291
}
292
293
294
// connect to the database
295
if ($installMode == 1) {
296
    include $path . "../" . MGR_DIR . "/includes/config.inc.php";
297
} else {
298
    // get db info from post
299
    $database_server = $databasehost;
300
    $database_user = $databaseloginname;
301
    $database_password = $databaseloginpassword;
302
    $database_collation = $database_collation;
303
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_') - 1);
304
    $database_connection_charset = $database_collation;
305
    $database_connection_method = $database_connection_method;
306
    $dbase = '`' . $database_name . '`';
307
    $table_prefix = $tableprefix;
308
}
309
echo $_lang['creating_database_connection'];
310
if (!$conn = mysqli_connect($database_server, $database_user, $database_password)) {
311
    $errors++;
312
    echo $_lang['database_connection_failed'] . PHP_EOL;
313
} else {
314
    echo $_lang['ok'] . PHP_EOL;
315
}
316
317
318
// make sure we can use the database
319
if ($installMode > 0 && !mysqli_query($conn, "USE {$dbase}")) {
320
    $errors++;
321
    echo $_lang['database_use_failed'] . PHP_EOL;
322
}
323
324
// check the database collation if not specified in the configuration
325 View Code Duplication
if (!isset ($database_connection_charset) || empty ($database_connection_charset)) {
326
    if (!$rs = mysqli_query($conn, "show session variables like 'collation_database'")) {
327
        $rs = mysqli_query($conn, "show session variables like 'collation_server'");
328
    }
329
    if ($rs && $collation = mysqli_fetch_row($rs)) {
330
        $database_collation = $collation[1];
331
    }
332
    if (empty ($database_collation)) {
333
        $database_collation = 'utf8_unicode_ci';
334
    }
335
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_') - 1);
336
    $database_connection_charset = $database_charset;
337
}
338
339
// determine the database connection method if not specified in the configuration
340
if (!isset($database_connection_method) || empty($database_connection_method)) {
341
    $database_connection_method = 'SET CHARACTER SET';
342
}
343
344
// check table prefix
345
if ($conn && $installMode == 0) {
346
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
347 View Code Duplication
    if ($rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
348
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
349
        $errors++;
350
351
    } else {
352
        echo $_lang['ok'] . PHP_EOL;
353
    }
354
} elseif ($conn && $installMode == 2) {
355
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
356 View Code Duplication
    if (!$rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
357
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_not_exist'] . PHP_EOL;
358
        $errors++;
359
360
    } else {
361
        echo $_lang['ok'] . PHP_EOL;
362
    }
363
}
364
365
// check mysql version
366
if ($conn) {
367
    echo $_lang['checking_mysql_version'];
368
    if (version_compare(mysqli_get_server_info($conn), '5.0.51', '=')) {
369
        echo $_lang['warning'] . ' ' . $_lang['mysql_5051'] . PHP_EOL;
370
        echo $_lang['mysql_5051_warning'] . PHP_EOL;
371 View Code Duplication
    } else {
372
        echo $_lang['ok'] . ' ' . $_lang['mysql_version_is'] . mysqli_get_server_info($conn) . PHP_EOL;
373
    }
374
}
375
376
// check for strict mode
377
if ($conn) {
378
    echo $_lang['checking_mysql_strict_mode'];
379
    $mysqlmode = mysqli_query($conn, "SELECT @@global.sql_mode");
380
    if (mysqli_num_rows($mysqlmode) > 0) {
381
        $modes = mysqli_fetch_array($mysqlmode, MYSQLI_NUM);
382
        //$modes = array("STRICT_TRANS_TABLES"); // for testing
383
        // print_r($modes);
384
        foreach ($modes as $mode) {
385
            if (stristr($mode, "STRICT_TRANS_TABLES") !== false || stristr($mode, "STRICT_ALL_TABLES") !== false) {
386
                echo $_lang['warning'] . ' ' . $_lang['strict_mode'] . PHP_EOL;
387
                echo $_lang['strict_mode_error'] . PHP_EOL;
388
            } else {
389
                echo $_lang['ok'] . PHP_EOL;
390
            }
391
        }
392
    } else {
393
        echo $_lang['ok'] . PHP_EOL;
394
    }
395
}
396
// Version and strict mode check end
397
398
// andrazk 20070416 - add install flag and disable manager login
399
// assets/cache writable?
400
if (is_writable($path . "../assets/cache")) {
401 View Code Duplication
    if (file_exists($path . '../assets/cache/installProc.inc.php')) {
402
        @chmod($path . '../assets/cache/installProc.inc.php', 0755);
403
        unlink($path . '../assets/cache/installProc.inc.php');
404
    }
405
406
    f_owc($path . "../assets/cache/installProc.inc.php", '<?php $installStartTime = ' . time() . '; ?>');
407
}
408
409 View Code Duplication
if ($installMode > 0 && $_POST['installdata'] == "1") {
410
    echo $_lang['sample_web_site'] . ': ' . $_lang['sample_web_site_note'] . PHP_EOL;
411
}
412
413
if ($errors > 0) {
414
    echo $_lang['setup_cannot_continue'] . ' ';
415
416 View Code Duplication
    if ($errors > 1) {
417
        echo $errors . " " . $_lang['errors'] . $_lang['please_correct_errors'] . $_lang['and_try_again_plural'];
418
    } else {
419
        echo $_lang['error'] . $_lang['please_correct_error'] . $_lang['and_try_again'] . PHP_EOL;
420
    }
421
422
    die();
423
}
424
425
426
//////////////////////////////////////////////////////////////////////////////////////
427
$create = false;
428
429
// set timout limit
430
@ set_time_limit(120); // used @ to prevent warning when using safe mode?
431
432
//echo $_lang['setup_database'].PHP_EOL;
433
434
435
if ($installMode == 1) {
436
    include $path . "../" . MGR_DIR . "/includes/config.inc.php";
437
} else {
438
    // get db info from post
439
    $database_server = $databasehost;
440
    $database_user = $databaseloginname;
441
    $database_password = $databaseloginpassword;
442
    $database_collation = $database_collation;
443
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_'));
444
    $database_connection_charset = $database_charset;
445
    $database_connection_method = $database_connection_method;
446
    $dbase = "`" . $database_name . "`";
447
    $table_prefix = $tableprefix;
448
    $adminname = $cmsadmin;
449
    $adminemail = $cmsadminemail;
450
    $adminpass = $cmspassword;
451
    $managerlanguage = $managerlanguage;
452
    $custom_placeholders = array();
453
}
454
455
// set session name variable
456
if (!isset ($site_sessionname)) {
457
    $site_sessionname = 'SN' . uniqid('');
458
}
459
460
// get base path and url
461
$a = explode("install", str_replace("\\", "/", dirname($_SERVER["PHP_SELF"])));
462
if (count($a) > 1) {
463
    array_pop($a);
464
}
465
$url = implode("install", $a);
466
reset($a);
467
$a = explode("install", str_replace("\\", "/", realpath(__DIR__)));
468
if (count($a) > 1) {
469
    array_pop($a);
470
}
471
$pth = implode("install", $a);
472
unset ($a);
473
$base_url = $url . (substr($url, -1) != "/" ? "/" : "");
474
$base_path = $pth . (substr($pth, -1) != "/" ? "/" : "");
475
476
// connect to the database
477
echo $_lang['setup_database_create_connection'] . ': ';
478
if (!$conn = mysqli_connect($database_server, $database_user, $database_password)) {
479
    echo $_lang["setup_database_create_connection_failed"] . " " . $_lang['setup_database_create_connection_failed_note'] . PHP_EOL;
480
481
    return;
482
} else {
483
    echo $_lang['ok'] . PHP_EOL;
484
}
485
486
// select database
487
echo $_lang['setup_database_selection'] . str_replace("`", "", $dbase) . "`: ";
488
if (!mysqli_select_db($conn, str_replace("`", "", $dbase))) {
489
    echo $_lang['setup_database_selection_failed'] . " " . $_lang['setup_database_selection_failed_note'] . PHP_EOL;
490
    $create = true;
491 View Code Duplication
} else {
492
    if (function_exists('mysqli_set_charset')) {
493
        mysqli_set_charset($conn, $database_charset);
494
    }
495
    mysqli_query($conn, "{$database_connection_method} {$database_connection_charset}");
496
    echo $_lang['ok'] . PHP_EOL;
497
}
498
499
// try to create the database
500
if ($create) {
501
    echo $_lang['setup_database_creation'] . str_replace("`", "", $dbase) . "`: ";
502
    //  if(!@mysqli_create_db(str_replace("`","",$dbase), $conn)) {
503
    if (!mysqli_query($conn,
504
        "CREATE DATABASE $dbase DEFAULT CHARACTER SET $database_charset COLLATE $database_collation")) {
505
        echo $_lang['setup_database_creation_failed'] . " " . $_lang['setup_database_creation_failed_note'] . PHP_EOL;
506
        $errors += 1;
507
508
        echo 'database charset: ' . $database_charset . PHP_EOL;
509
        echo 'database collation: ' . $database_collation . PHP_EOL;
510
511
        echo $_lang['setup_database_creation_failed_note2'] . PHP_EOL;
512
513
        die();
514
515
    } else {
516
        echo $_lang['ok'] . PHP_EOL;
517
    }
518
}
519
520
// check table prefix
521
if ($installMode == 0) {
522
    echo $_lang['checking_table_prefix'] . $table_prefix . "`: ";
523
    if (@ $rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
524
        echo $_lang['failed'] . " " . $_lang['table_prefix_already_inuse'] . PHP_EOL;
525
        $errors += 1;
526
        echo $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
527
528
        return;
529
    } else {
530
        echo $_lang['ok'] . PHP_EOL;
531
    }
532
}
533
534 View Code Duplication
if (!function_exists('parseProperties')) {
535
    /**
536
     * parses a resource property string and returns the result as an array
537
     * duplicate of method in documentParser class
538
     *
539
     * @param string $propertyString
540
     * @return array
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...
541
     */
542
    function parseProperties($propertyString)
543
    {
544
        $parameter = array();
545
        if (!empty ($propertyString)) {
546
            $tmpParams = explode("&", $propertyString);
547
            $countParams = count($tmpParams);
548
            for ($x = 0; $x < $countParams; $x++) {
549
                if (strpos($tmpParams[$x], '=', 0)) {
550
                    $pTmp = explode("=", $tmpParams[$x]);
551
                    $pvTmp = explode(";", trim($pTmp[1]));
552
                    if ($pvTmp[1] == 'list' && $pvTmp[3] != "") {
553
                        $parameter[trim($pTmp[0])] = $pvTmp[3];
554
                    } //list default
555
                    else {
556
                        if ($pvTmp[1] != 'list' && $pvTmp[2] != "") {
557
                            $parameter[trim($pTmp[0])] = $pvTmp[2];
558
                        }
559
                    }
560
                }
561
            }
562
        }
563
564
        return $parameter;
565
    }
566
}
567
568
// check status of Inherit Parent Template plugin
569
$auto_template_logic = 'parent';
570 View Code Duplication
if ($installMode != 0) {
571
    $rs = mysqli_query($conn,
572
        "SELECT properties, disabled FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='Inherit Parent Template'");
573
    $row = mysqli_fetch_row($rs);
574
    if (!$row) {
575
        // not installed
576
        $auto_template_logic = 'system';
577
    } else {
578
        if ($row[1] == 1) {
579
            // installed but disabled
580
            $auto_template_logic = 'system';
581
        } else {
582
            // installed, enabled .. see how it's configured
583
            $properties = parseProperties($row[0]);
584
            if (isset($properties['inheritTemplate'])) {
585
                if ($properties['inheritTemplate'] == 'From First Sibling') {
586
                    $auto_template_logic = 'sibling';
587
                }
588
            }
589
        }
590
    }
591
}
592
593
594
// open db connection
595
$setupPath = realpath(__DIR__);
596
$chunkPath = $path . 'assets/chunks';
597
$snippetPath = $path . 'assets/snippets';
598
$pluginPath = $path . 'assets/plugins';
599
$modulePath = $path . 'assets/modules';
600
$templatePath = $path . 'assets/templates';
601
$tvPath = $path . 'assets/tvs';
602
603
// setup Template template files - array : name, description, type - 0:file or 1:content, parameters, category
604
$mt = &$moduleTemplates;
605 View Code Duplication
if (is_dir($templatePath) && is_readable($templatePath)) {
606
    $d = dir($templatePath);
607
    while (false !== ($tplfile = $d->read())) {
608
        if (substr($tplfile, -4) != '.tpl') {
609
            continue;
610
        }
611
        $params = parse_docblock($templatePath, $tplfile);
612
        if (is_array($params) && (count($params) > 0)) {
613
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
614
            $mt[] = array
615
            (
616
                $params['name'],
617
                $description,
618
                // Don't think this is gonna be used ... but adding it just in case 'type'
619
                $params['type'],
620
                "$templatePath/{$params['filename']}",
621
                $params['modx_category'],
622
                $params['lock_template'],
623
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
624
                isset($params['save_sql_id_as']) ? $params['save_sql_id_as'] : null
625
                // Nessecary to fix template-ID for demo-site
626
            );
627
        }
628
    }
629
    $d->close();
630
}
631
632
// setup Template Variable template files
633
$mtv = &$moduleTVs;
634
if (is_dir($tvPath) && is_readable($tvPath)) {
635
    $d = dir($tvPath);
636 View Code Duplication
    while (false !== ($tplfile = $d->read())) {
637
        if (substr($tplfile, -4) != '.tpl') {
638
            continue;
639
        }
640
        $params = parse_docblock($tvPath, $tplfile);
641
        if (is_array($params) && (count($params) > 0)) {
642
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
643
            $mtv[] = array(
644
                $params['name'],
645
                $params['caption'],
646
                $description,
647
                $params['input_type'],
648
                $params['input_options'],
649
                $params['input_default'],
650
                $params['output_widget'],
651
                $params['output_widget_params'],
652
                "$templatePath/{$params['filename']}",
653
                /* not currently used */
654
                $params['template_assignments'] != "*" ? $params['template_assignments'] : implode(",",
655
                    array_map(create_function('$v', 'return $v[0];'), $mt)),
656
                /* comma-separated list of template names */
657
                $params['modx_category'],
658
                $params['lock_tv'],
659
                /* value should be 1 or 0 */
660
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
661
            );
662
        }
663
    }
664
    $d->close();
665
}
666
667
// setup chunks template files - array : name, description, type - 0:file or 1:content, file or content
668
$mc = &$moduleChunks;
669 View Code Duplication
if (is_dir($chunkPath) && is_readable($chunkPath)) {
670
    $d = dir($chunkPath);
671
    while (false !== ($tplfile = $d->read())) {
672
        if (substr($tplfile, -4) != '.tpl') {
673
            continue;
674
        }
675
        $params = parse_docblock($chunkPath, $tplfile);
676
        if (is_array($params) && count($params) > 0) {
677
            $mc[] = array(
678
                $params['name'],
679
                $params['description'],
680
                "$chunkPath/{$params['filename']}",
681
                $params['modx_category'],
682
                array_key_exists('overwrite', $params) ? $params['overwrite'] : 'true',
683
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
684
            );
685
        }
686
    }
687
    $d->close();
688
}
689
690
// setup snippets template files - array : name, description, type - 0:file or 1:content, file or content,properties
691
$ms = &$moduleSnippets;
692 View Code Duplication
if (is_dir($snippetPath) && is_readable($snippetPath)) {
693
    $d = dir($snippetPath);
694
    while (false !== ($tplfile = $d->read())) {
695
        if (substr($tplfile, -4) != '.tpl') {
696
            continue;
697
        }
698
        $params = parse_docblock($snippetPath, $tplfile);
699
        if (is_array($params) && count($params) > 0) {
700
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
701
            $ms[] = array(
702
                $params['name'],
703
                $description,
704
                "$snippetPath/{$params['filename']}",
705
                $params['properties'],
706
                $params['modx_category'],
707
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
708
            );
709
        }
710
    }
711
    $d->close();
712
}
713
714
// setup plugins template files - array : name, description, type - 0:file or 1:content, file or content,properties
715
$mp = &$modulePlugins;
716 View Code Duplication
if (is_dir($pluginPath) && is_readable($pluginPath)) {
717
    $d = dir($pluginPath);
718
    while (false !== ($tplfile = $d->read())) {
719
        if (substr($tplfile, -4) != '.tpl') {
720
            continue;
721
        }
722
        $params = parse_docblock($pluginPath, $tplfile);
723
        if (is_array($params) && count($params) > 0) {
724
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
725
            $mp[] = array(
726
                $params['name'],
727
                $description,
728
                "$pluginPath/{$params['filename']}",
729
                $params['properties'],
730
                $params['events'],
731
                $params['guid'],
732
                $params['modx_category'],
733
                $params['legacy_names'],
734
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
735
                (int)$params['disabled']
736
            );
737
        }
738
    }
739
    $d->close();
740
}
741
742
// setup modules - array : name, description, type - 0:file or 1:content, file or content,properties, guid,enable_sharedparams
743
$mm = &$moduleModules;
744
$mdp = &$moduleDependencies;
745 View Code Duplication
if (is_dir($modulePath) && is_readable($modulePath)) {
746
    $d = dir($modulePath);
747
    while (false !== ($tplfile = $d->read())) {
748
        if (substr($tplfile, -4) != '.tpl') {
749
            continue;
750
        }
751
        $params = parse_docblock($modulePath, $tplfile);
752
        if (is_array($params) && count($params) > 0) {
753
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
754
            $mm[] = array(
755
                $params['name'],
756
                $description,
757
                "$modulePath/{$params['filename']}",
758
                $params['properties'],
759
                $params['guid'],
760
                (int)$params['shareparams'],
761
                $params['modx_category'],
762
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
763
            );
764
        }
765
        if ((int)$params['shareparams'] || !empty($params['dependencies'])) {
766
            $dependencies = explode(',', $params['dependencies']);
767
            foreach ($dependencies as $dependency) {
768
                $dependency = explode(':', $dependency);
769
                switch (trim($dependency[0])) {
770
                    case 'template':
771
                        $mdp[] = array(
772
                            'module' => $params['name'],
773
                            'table'  => 'templates',
774
                            'column' => 'templatename',
775
                            'type'   => 50,
776
                            'name'   => trim($dependency[1])
777
                        );
778
                        break;
779
                    case 'tv':
780
                    case 'tmplvar':
781
                        $mdp[] = array(
782
                            'module' => $params['name'],
783
                            'table'  => 'tmplvars',
784
                            'column' => 'name',
785
                            'type'   => 60,
786
                            'name'   => trim($dependency[1])
787
                        );
788
                        break;
789
                    case 'chunk':
790
                    case 'htmlsnippet':
791
                        $mdp[] = array(
792
                            'module' => $params['name'],
793
                            'table'  => 'htmlsnippets',
794
                            'column' => 'name',
795
                            'type'   => 10,
796
                            'name'   => trim($dependency[1])
797
                        );
798
                        break;
799
                    case 'snippet':
800
                        $mdp[] = array(
801
                            'module' => $params['name'],
802
                            'table'  => 'snippets',
803
                            'column' => 'name',
804
                            'type'   => 40,
805
                            'name'   => trim($dependency[1])
806
                        );
807
                        break;
808
                    case 'plugin':
809
                        $mdp[] = array(
810
                            'module' => $params['name'],
811
                            'table'  => 'plugins',
812
                            'column' => 'name',
813
                            'type'   => 30,
814
                            'name'   => trim($dependency[1])
815
                        );
816
                        break;
817
                    case 'resource':
818
                        $mdp[] = array(
819
                            'module' => $params['name'],
820
                            'table'  => 'content',
821
                            'column' => 'pagetitle',
822
                            'type'   => 20,
823
                            'name'   => trim($dependency[1])
824
                        );
825
                        break;
826
                }
827
            }
828
        }
829
    }
830
    $d->close();
831
}
832
833
// setup callback function
834
$callBackFnc = "clean_up";
835
836 View Code Duplication
if (!function_exists('clean_up')) {
837
    function clean_up($sqlParser)
838
    {
839
        $ids = array();
840
841
        // secure web documents - privateweb
842
        mysqli_query($sqlParser->conn,
843
            "UPDATE `" . $sqlParser->prefix . "site_content` SET privateweb = 0 WHERE privateweb = 1");
844
        $sql = "SELECT DISTINCT sc.id
845
             FROM `" . $sqlParser->prefix . "site_content` sc
846
             LEFT JOIN `" . $sqlParser->prefix . "document_groups` dg ON dg.document = sc.id
847
             LEFT JOIN `" . $sqlParser->prefix . "webgroup_access` wga ON wga.documentgroup = dg.document_group
848
             WHERE wga.id>0";
849
        $ds = mysqli_query($sqlParser->conn, $sql);
850
        if (!$ds) {
851
            echo "An error occurred while executing a query: " . mysqli_error($sqlParser->conn);
852
        } else {
853
            while ($r = mysqli_fetch_assoc($ds)) {
854
                $ids[] = $r["id"];
855
            }
856
            if (count($ids) > 0) {
857
                mysqli_query($sqlParser->conn,
858
                    "UPDATE `" . $sqlParser->prefix . "site_content` SET privateweb = 1 WHERE id IN (" . implode(", ",
859
                        $ids) . ")");
860
                unset($ids);
861
            }
862
        }
863
864
        // secure manager documents privatemgr
865
        mysqli_query($sqlParser->conn,
866
            "UPDATE `" . $sqlParser->prefix . "site_content` SET privatemgr = 0 WHERE privatemgr = 1");
867
        $sql = "SELECT DISTINCT sc.id
868
             FROM `" . $sqlParser->prefix . "site_content` sc
869
             LEFT JOIN `" . $sqlParser->prefix . "document_groups` dg ON dg.document = sc.id
870
             LEFT JOIN `" . $sqlParser->prefix . "membergroup_access` mga ON mga.documentgroup = dg.document_group
871
             WHERE mga.id>0";
872
        $ds = mysqli_query($sqlParser->conn, $sql);
873
        if (!$ds) {
874
            echo "An error occurred while executing a query: " . mysqli_error($sqlParser->conn);
875
        } else {
876
            while ($r = mysqli_fetch_assoc($ds)) {
877
                $ids[] = $r["id"];
878
            }
879
            if (count($ids) > 0) {
880
                mysqli_query($sqlParser->conn,
881
                    "UPDATE `" . $sqlParser->prefix . "site_content` SET privatemgr = 1 WHERE id IN (" . implode(", ",
882
                        $ids) . ")");
883
                unset($ids);
884
            }
885
        }
886
    }
887
}
888
889 View Code Duplication
if (!function_exists('parse_docblock')) {
890
    function parse_docblock($element_dir, $filename)
891
    {
892
        $params = array();
893
        $fullpath = $element_dir . '/' . $filename;
894
        if (is_readable($fullpath)) {
895
            $tpl = @fopen($fullpath, "r");
896
            if ($tpl) {
897
                $params['filename'] = $filename;
898
                $docblock_start_found = false;
899
                $name_found = false;
900
                $description_found = false;
901
902
                while (!feof($tpl)) {
903
                    $line = fgets($tpl);
904
                    if (!$docblock_start_found) {
905
                        // find docblock start
906
                        if (strpos($line, '/**') !== false) {
907
                            $docblock_start_found = true;
908
                        }
909
                        continue;
910
                    } elseif (!$name_found) {
911
                        // find name
912
                        $ma = null;
913
                        if (preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
914
                            $params['name'] = trim($ma[1]);
915
                            $name_found = !empty($params['name']);
916
                        }
917
                        continue;
918
                    } elseif (!$description_found) {
919
                        // find description
920
                        $ma = null;
921
                        if (preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
922
                            $params['description'] = trim($ma[1]);
923
                            $description_found = !empty($params['description']);
924
                        }
925
                        continue;
926
                    } else {
927
                        $ma = null;
928
                        if (preg_match("/^\s+\*\s+\@([^\s]+)\s+(.+)/", $line, $ma)) {
929
                            $param = trim($ma[1]);
930
                            $val = trim($ma[2]);
931
                            if (!empty($param) && !empty($val)) {
932
                                if ($param == 'internal') {
933
                                    $ma = null;
934
                                    if (preg_match("/\@([^\s]+)\s+(.+)/", $val, $ma)) {
935
                                        $param = trim($ma[1]);
936
                                        $val = trim($ma[2]);
937
                                    }
938
                                    //if($val !== '0' && (empty($param) || empty($val))) {
939
                                    if (empty($param)) {
940
                                        continue;
941
                                    }
942
                                }
943
                                $params[$param] = $val;
944
                            }
945
                        } elseif (preg_match("/^\s*\*\/\s*$/", $line)) {
946
                            break;
947
                        }
948
                    }
949
                }
950
                @fclose($tpl);
951
            }
952
        }
953
954
        return $params;
955
    }
956
}
957
958
include $path . "src/sqlParser.class.php";
959
$sqlParser = new SqlParser($database_server, $database_user, $database_password, str_replace("`", "", $dbase),
960
    $table_prefix, $adminname, $adminemail, $adminpass, $database_connection_charset, $managerlanguage,
961
    $database_connection_method, $auto_template_logic);
962
$sqlParser->mode = ($installMode < 1) ? "new" : "upd";
963
/* image and file manager paths now handled via settings screen in Manager
964
$sqlParser->imageUrl = 'http://' . $_SERVER['SERVER_NAME'] . $base_url . "assets/";
965
$sqlParser->imageUrl = "assets/";
966
$sqlParser->imagePath = $base_path . "assets/";
967
$sqlParser->fileManagerPath = $base_path;
968
*/
969
$sqlParser->ignoreDuplicateErrors = true;
970
$sqlParser->connect();
971
972
// install/update database
973
echo $_lang['setup_database_creating_tables'];
974
if ($moduleSQLBaseFile) {
975
    $sqlParser->process($moduleSQLBaseFile);
976
    // display database results
977
    if ($sqlParser->installFailed == true) {
978
        $errors += 1;
979
        echo $_lang['database_alerts'] . PHP_EOL;
980
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
981
        echo $_lang['installation_error_occured'] . PHP_EOL;
982
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
983
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
984
        }
985
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
986
        die();
987
    } else {
988
        echo $_lang['ok'] . PHP_EOL;
989
    }
990
}
991
992
// custom or not
993
if (file_exists($path . "../assets/cache/siteManager.php")) {
994
    $mgrdir = 'include_once(__DIR__."/../../assets/cache/siteManager.php");';
995
} else {
996
    $mgrdir = 'define(\'MGR_DIR\', \'manager\');';
997
}
998
999
// write the config.inc.php file if new installation
1000
echo $_lang['writing_config_file'];
1001
1002
$confph = array();
1003
$confph['database_server'] = $database_server;
1004
$confph['user_name'] = mysqli_real_escape_string($conn, $database_user);
1005
$confph['password'] = mysqli_real_escape_string($conn, $database_password);
1006
$confph['connection_charset'] = $database_connection_charset;
1007
$confph['connection_method'] = $database_connection_method;
1008
$confph['dbase'] = str_replace('`', '', $dbase);
1009
$confph['table_prefix'] = $table_prefix;
1010
$confph['lastInstallTime'] = time();
1011
$confph['site_sessionname'] = $site_sessionname;
1012
1013
$configString = file_get_contents($path . 'src/stubs/config.tpl');
1014
$configString = parse($configString, $confph);
1015
1016
$filename = $base_path . MGR_DIR . '/includes/config.inc.php';
1017
$configFileFailed = false;
1018
if (@ !$handle = fopen($filename, 'w')) {
1019
    $configFileFailed = true;
1020
}
1021
1022
// write $somecontent to our opened file.
1023
if (@ fwrite($handle, $configString) === false) {
1024
    $configFileFailed = true;
1025
}
1026
@ fclose($handle);
1027
1028
// try to chmod the config file go-rwx (for suexeced php)
1029
$chmodSuccess = @chmod($filename, 0404);
1030
1031
if ($configFileFailed == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1032
    echo $_lang['failed'] . PHP_EOL;
1033
    $errors += 1;
1034
1035
    echo $_lang['cant_write_config_file'] . ' ' . MGR_DIR . '/includes/config.inc.php' . PHP_EOL;
1036
    echo ' ' . PHP_EOL;
1037
    echo ' ' . PHP_EOL;
1038
    echo $configString;
1039
    echo ' ' . PHP_EOL;
1040
    echo ' ' . PHP_EOL;
1041
    echo $_lang['cant_write_config_file_note'] . PHP_EOL;
1042
    die();
1043
1044
} else {
1045
    echo $_lang['ok'] . PHP_EOL;
1046
}
1047
1048
// generate new site_id and set manager theme to default
1049 View Code Duplication
if ($installMode == 0) {
1050
    $siteid = uniqid('');
1051
    mysqli_query($sqlParser->conn,
1052
        "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid'),('manager_theme','default')");
1053
} else {
1054
    // update site_id if missing
1055
    $ds = mysqli_query($sqlParser->conn,
1056
        "SELECT setting_name,setting_value FROM $dbase.`" . $table_prefix . "system_settings` WHERE setting_name='site_id'");
1057
    if ($ds) {
1058
        $r = mysqli_fetch_assoc($ds);
1059
        $siteid = $r['setting_value'];
1060
        if ($siteid == '' || $siteid = 'MzGeQ2faT4Dw06+U49x3') {
1061
            $siteid = uniqid('');
1062
            mysqli_query($sqlParser->conn,
1063
                "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid')");
1064
        }
1065
    }
1066
}
1067
1068
// Reset database for installation of demo-site
1069
if ($installData && $moduleSQLDataFile && $moduleSQLResetFile) {
1070
    echo $_lang['resetting_database'];
1071
    $sqlParser->process($moduleSQLResetFile);
1072
    // display database results
1073
    if ($sqlParser->installFailed == true) {
1074
        $errors += 1;
1075
        echo $_lang['database_alerts'] . PHP_EOL;
1076
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
1077
        echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
1078
        /*
1079
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
1080
            echo "<em>" . $sqlParser->mysqlErrors[$i]["error"] . "</em>" . $_lang['during_execution_of_sql'] . "<span class='mono'>" . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . "</span>.<hr />";
1081
        }
1082
        echo "</p>";*/
1083
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
1084
        die();
1085
    } else {
1086
        echo $_lang['ok'] . PHP_EOL;
1087
    }
1088
}
1089
1090
// Install Templates
1091
$moduleTemplate = $mt;
1092
if (!empty($moduleTemplate) || $installData) {
1093
    echo PHP_EOL . $_lang['templates'] . ":" . PHP_EOL;
1094
    //$selTemplates = $_POST['template'];
1095
    foreach ($moduleTemplates as $k => $moduleTemplate) {
1096
        $installSample = in_array('sample', $moduleTemplate[6]) && $installData == 1;
1097
        if ($installSample || is_array($moduleTemplate)) {
1098
            $name = mysqli_real_escape_string($conn, $moduleTemplate[0]);
1099
            $desc = mysqli_real_escape_string($conn, $moduleTemplate[1]);
1100
            $category = mysqli_real_escape_string($conn, $moduleTemplate[4]);
1101
            $locked = mysqli_real_escape_string($conn, $moduleTemplate[5]);
1102
            $filecontent = $moduleTemplate[3];
1103
            $save_sql_id_as = $moduleTemplate[7]; // Nessecary for demo-site
1104
            if (!file_exists($filecontent)) {
1105
                echo "  $name: " . $_lang['unable_install_template'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1106
            } else {
1107
                // Create the category if it does not already exist
1108
                $category_id = getCreateDbCategory($category, $sqlParser);
1109
1110
                // Strip the first comment up top
1111
                $template = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
1112
                $template = mysqli_real_escape_string($conn, $template);
1113
1114
                // See if the template already exists
1115
                $rs = mysqli_query($sqlParser->conn,
1116
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name'");
1117
1118
                if (mysqli_num_rows($rs)) {
1119
                    if (!mysqli_query($sqlParser->conn,
1120
                        "UPDATE $dbase.`" . $table_prefix . "site_templates` SET content='$template', description='$desc', category=$category_id, locked='$locked'  WHERE templatename='$name' LIMIT 1;")) {
1121
                        $errors += 1;
1122
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1123
1124
                        return;
1125
                    }
1126 View Code Duplication
                    if (!is_null($save_sql_id_as)) {
1127
                        $sql_id = @mysqli_insert_id($sqlParser->conn);
1128
                        if (!$sql_id) {
1129
                            $idQuery = mysqli_fetch_assoc(mysqli_query($sqlParser->conn,
1130
                                "SELECT id FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name' LIMIT 1;"));
1131
                            $sql_id = $idQuery['id'];
1132
                        }
1133
                        $custom_placeholders[$save_sql_id_as] = $sql_id;
1134
                    }
1135
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1136
                } else {
1137
                    if (!@ mysqli_query($sqlParser->conn,
1138
                        "INSERT INTO $dbase.`" . $table_prefix . "site_templates` (templatename,description,content,category,locked) VALUES('$name','$desc','$template',$category_id,'$locked');")) {
1139
                        $errors += 1;
1140
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1141
                        die();
1142
                    }
1143
                    if (!is_null($save_sql_id_as)) {
1144
                        $custom_placeholders[$save_sql_id_as] = @mysqli_insert_id($sqlParser->conn);
1145
                    }
1146
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1147
                }
1148
            }
1149
        }
1150
    }
1151
}
1152
1153
// Install Template Variables
1154
$moduleTVs = $mtv;
1155
if (is_array($moduleTVs) || $installData) {
1156
    echo PHP_EOL . $_lang['tvs'] . ': ' . PHP_EOL;
1157
    //$selTVs = $_POST['tv'];
1158
    foreach ($moduleTVs as $k => $moduleTV) {
1159
        $installSample = in_array('sample', $moduleTV[12]) && $installData == 1;
1160
        if ($installSample || is_array($moduleTVs)) {
1161
            $name = mysqli_real_escape_string($conn, $moduleTV[0]);
1162
            $caption = mysqli_real_escape_string($conn, $moduleTV[1]);
1163
            $desc = mysqli_real_escape_string($conn, $moduleTV[2]);
1164
            $input_type = mysqli_real_escape_string($conn, $moduleTV[3]);
1165
            $input_options = mysqli_real_escape_string($conn, $moduleTV[4]);
1166
            $input_default = mysqli_real_escape_string($conn, $moduleTV[5]);
1167
            $output_widget = mysqli_real_escape_string($conn, $moduleTV[6]);
1168
            $output_widget_params = mysqli_real_escape_string($conn, $moduleTV[7]);
1169
            $filecontent = $moduleTV[8];
1170
            $assignments = $moduleTV[9];
1171
            $category = mysqli_real_escape_string($conn, $moduleTV[10]);
1172
            $locked = mysqli_real_escape_string($conn, $moduleTV[11]);
1173
1174
1175
            // Create the category if it does not already exist
1176
            $category = getCreateDbCategory($category, $sqlParser);
1177
1178
            $rs = mysqli_query($sqlParser->conn,
1179
                "SELECT * FROM $dbase.`" . $table_prefix . "site_tmplvars` WHERE name='$name'");
1180
            if (mysqli_num_rows($rs)) {
1181
                $insert = true;
1182 View Code Duplication
                while ($row = mysqli_fetch_assoc($rs)) {
1183
                    if (!mysqli_query($sqlParser->conn,
1184
                        "UPDATE $dbase.`" . $table_prefix . "site_tmplvars` SET type='$input_type', caption='$caption', description='$desc', category=$category, locked=$locked, elements='$input_options', display='$output_widget', display_params='$output_widget_params', default_text='$input_default' WHERE id={$row['id']};")) {
1185
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1186
1187
                        return;
1188
                    }
1189
                    $insert = false;
1190
                }
1191
                echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1192
            } else {
1193
                $q = "INSERT INTO $dbase.`" . $table_prefix . "site_tmplvars` (type,name,caption,description,category,locked,elements,display,display_params,default_text) VALUES('$input_type','$name','$caption','$desc',$category,$locked,'$input_options','$output_widget','$output_widget_params','$input_default');";
1194 View Code Duplication
                if (!mysqli_query($sqlParser->conn, $q)) {
1195
                    echo mysqli_error($sqlParser->conn) . PHP_EOL;
1196
1197
                    return;
1198
                }
1199
                echo "  $name: " . $_lang['installed'] . PHP_EOL;
1200
            }
1201
1202
            // add template assignments
1203
            $assignments = explode(',', $assignments);
1204
1205 View Code Duplication
            if (count($assignments) > 0) {
1206
1207
                // remove existing tv -> template assignments
1208
                $ds = mysqli_query($sqlParser->conn,
1209
                    "SELECT id FROM $dbase.`" . $table_prefix . "site_tmplvars` WHERE name='$name' AND description='$desc';");
1210
                $row = mysqli_fetch_assoc($ds);
1211
                $id = $row["id"];
1212
                mysqli_query($sqlParser->conn,
1213
                    'DELETE FROM ' . $dbase . '.`' . $table_prefix . 'site_tmplvar_templates` WHERE tmplvarid = \'' . $id . '\'');
1214
1215
                // add tv -> template assignments
1216
                foreach ($assignments as $assignment) {
1217
                    $template = mysqli_real_escape_string($conn, $assignment);
1218
                    $ts = mysqli_query($sqlParser->conn,
1219
                        "SELECT id FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$template';");
1220
                    if ($ds && $ts) {
1221
                        $tRow = mysqli_fetch_assoc($ts);
1222
                        $templateId = $tRow['id'];
1223
                        mysqli_query($sqlParser->conn,
1224
                            "INSERT INTO $dbase.`" . $table_prefix . "site_tmplvar_templates` (tmplvarid, templateid) VALUES($id, $templateId)");
1225
                    }
1226
                }
1227
            }
1228
        }
1229
    }
1230
}
1231
1232
1233
$moduleChunks = $mc;
1234
// Install Chunks
1235
if (is_array($moduleChunks) || $installData) {
1236
    echo PHP_EOL . $_lang['chunks'] . ": " . PHP_EOL;
1237
    foreach ($moduleChunks as $k => $moduleChunk) {
1238
        $installSample = in_array('sample', $moduleChunk[5]) && $installData == 1;
1239
        $count_new_name = 0;
1240
        if ($installSample || is_array($moduleChunks)) {
1241
1242
            $name = mysqli_real_escape_string($conn, $moduleChunk[0]);
1243
            $desc = mysqli_real_escape_string($conn, $moduleChunk[1]);
1244
            $category = mysqli_real_escape_string($conn, $moduleChunk[3]);
1245
            $overwrite = mysqli_real_escape_string($conn, $moduleChunk[4]);
1246
            $filecontent = $moduleChunk[2];
1247
1248
            if (!file_exists($filecontent)) {
1249
                echo "  $name: " . $_lang['unable_install_chunk'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1250
            } else {
1251
1252
                // Create the category if it does not already exist
1253
                $category_id = getCreateDbCategory($category, $sqlParser);
1254
1255
                $chunk = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
1256
                $chunk = mysqli_real_escape_string($conn, $chunk);
1257
                $rs = mysqli_query($sqlParser->conn,
1258
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$name'");
1259
                $count_original_name = mysqli_num_rows($rs);
1260 View Code Duplication
                if ($overwrite == 'false') {
1261
                    $newname = $name . '-' . str_replace('.', '_', $modx_version);
1262
                    $rs = mysqli_query($sqlParser->conn,
1263
                        "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$newname'");
1264
                    $count_new_name = mysqli_num_rows($rs);
1265
                }
1266
                $update = $count_original_name > 0 && $overwrite == 'true';
1267
                if ($update) {
1268
                    if (!mysqli_query($sqlParser->conn,
1269
                        "UPDATE $dbase.`" . $table_prefix . "site_htmlsnippets` SET snippet='$chunk', description='$desc', category=$category_id WHERE name='$name';")) {
1270
                        $errors += 1;
1271
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1272
1273
                        return;
1274
                    }
1275
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1276
                } elseif ($count_new_name == 0) {
1277
                    if ($count_original_name > 0 && $overwrite == 'false') {
1278
                        $name = $newname;
1279
                    }
1280
                    if (!mysqli_query($sqlParser->conn,
1281
                        "INSERT INTO $dbase.`" . $table_prefix . "site_htmlsnippets` (name,description,snippet,category) VALUES('$name','$desc','$chunk',$category_id);")) {
1282
                        $errors += 1;
1283
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1284
1285
                        return;
1286
                    }
1287
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1288
                }
1289
            }
1290
        }
1291
    }
1292
}
1293
1294
// Install Modules
1295
$moduleModules = $mm;
1296
if (is_array($moduleModules) || $installData) {
1297
    echo PHP_EOL . $_lang['modules'] . ":" . PHP_EOL;
1298
    //$selModules = $_POST['module'];
1299
    foreach ($moduleModules as $k => $moduleModule) {
1300
        $installSample = in_array('sample', $moduleModule[7]) && $installData == 1;
1301
        if ($installSample || is_array($moduleModules)) {
1302
            $name = mysqli_real_escape_string($conn, $moduleModule[0]);
1303
            $desc = mysqli_real_escape_string($conn, $moduleModule[1]);
1304
            $filecontent = $moduleModule[2];
1305
            $properties = $moduleModule[3];
1306
            $guid = mysqli_real_escape_string($conn, $moduleModule[4]);
1307
            $shared = mysqli_real_escape_string($conn, $moduleModule[5]);
1308
            $category = mysqli_real_escape_string($conn, $moduleModule[6]);
1309
            if (!file_exists($filecontent)) {
1310
                echo "  $name: " . $_lang['unable_install_module'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1311
            } else {
1312
1313
                // Create the category if it does not already exist
1314
                $category = getCreateDbCategory($category, $sqlParser);
1315
1316
                $module = end(preg_split("/(\/\/)?\s*\<\?php/", file_get_contents($filecontent), 2));
0 ignored issues
show
Bug introduced by
preg_split('/(\\/\\/)?\\...tents($filecontent), 2) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
1317
                // $module = removeDocblock($module, 'module'); // Modules have no fileBinding, keep docblock for info-tab
1318
                $module = mysqli_real_escape_string($conn, $module);
1319
                $rs = mysqli_query($sqlParser->conn,
1320
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_modules` WHERE name='$name'");
1321
                if (mysqli_num_rows($rs)) {
1322
                    $row = mysqli_fetch_assoc($rs);
1323
                    $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1324
                    if (!mysqli_query($sqlParser->conn,
1325
                        "UPDATE $dbase.`" . $table_prefix . "site_modules` SET modulecode='$module', description='$desc', properties='$props', enable_sharedparams='$shared' WHERE name='$name';")) {
1326
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1327
1328
                        return;
1329
                    }
1330
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1331
                } else {
1332
                    if ($properties != null) {
1333
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
0 ignored issues
show
Unused Code introduced by
The call to parseProperties() has too many arguments starting with true.

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...
1334
                    }
1335
                    if (!mysqli_query($sqlParser->conn,
1336
                        "INSERT INTO $dbase.`" . $table_prefix . "site_modules` (name,description,modulecode,properties,guid,enable_sharedparams,category) VALUES('$name','$desc','$module','$properties','$guid','$shared', $category);")) {
1337
                        echo "<p>" . mysqli_error($sqlParser->conn) . "</p>";
1338
1339
                        return;
1340
                    }
1341
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1342
                }
1343
            }
1344
        }
1345
    }
1346
}
1347
1348
// Install Plugins
1349
$modulePlugins = $mp;
1350
if (is_array($modulePlugins) || $installData) {
1351
    echo PHP_EOL . $_lang['plugins'] . ":" . PHP_EOL;
1352
    $selPlugs = $_POST['plugin'];
1353
    foreach ($modulePlugins as $k => $modulePlugin) {
1354
        //$installSample = in_array('sample', $modulePlugin[8]) && $installData == 1;
1355
        if ($installSample || is_array($modulePlugins)) {
1356
            $name = mysqli_real_escape_string($conn, $modulePlugin[0]);
1357
            $desc = mysqli_real_escape_string($conn, $modulePlugin[1]);
1358
            $filecontent = $modulePlugin[2];
1359
            $properties = $modulePlugin[3];
1360
            $events = explode(",", $modulePlugin[4]);
1361
            $guid = mysqli_real_escape_string($conn, $modulePlugin[5]);
1362
            $category = mysqli_real_escape_string($conn, $modulePlugin[6]);
1363
            $leg_names = '';
1364
            $disabled = $modulePlugin[9];
1365 View Code Duplication
            if (array_key_exists(7, $modulePlugin)) {
1366
                // parse comma-separated legacy names and prepare them for sql IN clause
1367
                $leg_names = "'" . implode("','",
1368
                        preg_split('/\s*,\s*/', mysqli_real_escape_string($conn, $modulePlugin[7]))) . "'";
1369
            }
1370
            if (!file_exists($filecontent)) {
1371
                echo "  $name: " . $_lang['unable_install_plugin'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1372
            } else {
1373
1374
                // disable legacy versions based on legacy_names provided
1375 View Code Duplication
                if (!empty($leg_names)) {
1376
                    $update_query = "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE name IN ($leg_names);";
1377
                    $rs = mysqli_query($sqlParser->conn, $update_query);
1378
                }
1379
1380
                // Create the category if it does not already exist
1381
                $category = getCreateDbCategory($category, $sqlParser);
1382
1383
                $plugin = end(preg_split("/(\/\/)?\s*\<\?php/", file_get_contents($filecontent), 2));
0 ignored issues
show
Bug introduced by
preg_split('/(\\/\\/)?\\...tents($filecontent), 2) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
1384
                $plugin = removeDocblock($plugin, 'plugin');
1385
                $plugin = mysqli_real_escape_string($conn, $plugin);
1386
                $rs = mysqli_query($sqlParser->conn,
1387
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='$name'");
1388
                if (mysqli_num_rows($rs)) {
1389
                    $insert = true;
1390
                    while ($row = mysqli_fetch_assoc($rs)) {
1391
                        $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1392
                        if ($row['description'] == $desc) {
1393
                            if (!mysqli_query($sqlParser->conn,
1394
                                "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET plugincode='$plugin', description='$desc', properties='$props' WHERE id={$row['id']};")) {
1395
                                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1396
1397
                                return;
1398
                            }
1399
                            $insert = false;
1400 View Code Duplication
                        } else {
1401
                            if (!mysqli_query($sqlParser->conn,
1402
                                "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE id={$row['id']};")) {
1403
                                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1404
1405
                                return;
1406
                            }
1407
                        }
1408
                    }
1409 View Code Duplication
                    if ($insert === true) {
1410
                        $properties = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1411
                        if (!mysqli_query($sqlParser->conn,
1412
                            "INSERT INTO $dbase.`" . $table_prefix . "site_plugins` (name,description,plugincode,properties,moduleguid,disabled,category) VALUES('$name','$desc','$plugin','$properties','$guid','0',$category);")) {
1413
                            echo mysqli_error($sqlParser->conn) . PHP_EOL;
1414
1415
                            return;
1416
                        }
1417
                    }
1418
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1419 View Code Duplication
                } else {
1420
                    if ($properties != null) {
1421
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
0 ignored issues
show
Unused Code introduced by
The call to parseProperties() has too many arguments starting with true.

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...
1422
                    }
1423
                    if (!mysqli_query($sqlParser->conn,
1424
                        "INSERT INTO $dbase.`" . $table_prefix . "site_plugins` (name,description,plugincode,properties,moduleguid,category,disabled) VALUES('$name','$desc','$plugin','$properties','$guid',$category,$disabled);")) {
1425
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1426
1427
                        return;
1428
                    }
1429
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1430
                }
1431
                // add system events
1432 View Code Duplication
                if (count($events) > 0) {
1433
                    $ds = mysqli_query($sqlParser->conn,
1434
                        "SELECT id FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='$name' AND description='$desc';");
1435
                    if ($ds) {
1436
                        $row = mysqli_fetch_assoc($ds);
1437
                        $id = $row["id"];
1438
                        // remove existing events
1439
                        mysqli_query($sqlParser->conn,
1440
                            'DELETE FROM ' . $dbase . '.`' . $table_prefix . 'site_plugin_events` WHERE pluginid = \'' . $id . '\'');
1441
                        // add new events
1442
                        mysqli_query($sqlParser->conn,
1443
                            "INSERT INTO $dbase.`" . $table_prefix . "site_plugin_events` (pluginid, evtid) SELECT '$id' as 'pluginid',se.id as 'evtid' FROM $dbase.`" . $table_prefix . "system_eventnames` se WHERE name IN ('" . implode("','",
1444
                                $events) . "')");
1445
                    }
1446
                }
1447
            }
1448
        }
1449
    }
1450
}
1451
1452
// Install Snippets
1453
$moduleSnippet = $ms;
1454
if (is_array($moduleSnippet) || $installData) {
1455
    echo PHP_EOL . $_lang['snippets'] . ":" . PHP_EOL;
1456
    //$selSnips = $_POST['snippet'];
1457
    foreach ($moduleSnippets as $k => $moduleSnippet) {
1458
        $installSample = in_array('sample', $moduleSnippet[5]) && $installData == 1;
1459
        if ($installSample || is_array($moduleSnippet)) {
1460
            $name = mysqli_real_escape_string($conn, $moduleSnippet[0]);
1461
            $desc = mysqli_real_escape_string($conn, $moduleSnippet[1]);
1462
            $filecontent = $moduleSnippet[2];
1463
            $properties = $moduleSnippet[3];
1464
            $category = mysqli_real_escape_string($conn, $moduleSnippet[4]);
1465
            if (!file_exists($filecontent)) {
1466
                echo "  $name: " . $_lang['unable_install_snippet'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1467
            } else {
1468
1469
                // Create the category if it does not already exist
1470
                $category = getCreateDbCategory($category, $sqlParser);
1471
1472
                $snippet = end(preg_split("/(\/\/)?\s*\<\?php/", file_get_contents($filecontent)));
0 ignored issues
show
Bug introduced by
preg_split('/(\\/\\/)?\\...contents($filecontent)) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
1473
                $snippet = removeDocblock($snippet, 'snippet');
1474
                $snippet = mysqli_real_escape_string($conn, $snippet);
1475
                $rs = mysqli_query($sqlParser->conn,
1476
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_snippets` WHERE name='$name'");
1477
                if (mysqli_num_rows($rs)) {
1478
                    $row = mysqli_fetch_assoc($rs);
1479
                    $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1480
                    if (!mysqli_query($sqlParser->conn,
1481
                        "UPDATE $dbase.`" . $table_prefix . "site_snippets` SET snippet='$snippet', description='$desc', properties='$props' WHERE name='$name';")) {
1482
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1483
1484
                        return;
1485
                    }
1486
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1487 View Code Duplication
                } else {
1488
                    if ($properties != null) {
1489
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
0 ignored issues
show
Unused Code introduced by
The call to parseProperties() has too many arguments starting with true.

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...
1490
                    }
1491
                    if (!mysqli_query($sqlParser->conn,
1492
                        "INSERT INTO $dbase.`" . $table_prefix . "site_snippets` (name,description,snippet,properties,category) VALUES('$name','$desc','$snippet','$properties',$category);")) {
1493
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1494
1495
                        return;
1496
                    }
1497
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1498
                }
1499
            }
1500
        }
1501
    }
1502
}
1503
1504
// Install demo-site
1505
if ($installData && $moduleSQLDataFile) {
1506
    echo PHP_EOL . $_lang['installing_demo_site'];
1507
    $sqlParser->process($moduleSQLDataFile);
1508
    // display database results
1509
    if ($sqlParser->installFailed == true) {
1510
        $errors += 1;
1511
        echo $_lang['database_alerts'] . PHP_EOL;
1512
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
1513
        echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
1514
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
1515
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
1516
        }
1517
1518
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
1519
1520
        return;
1521 View Code Duplication
    } else {
1522
        $sql = sprintf("SELECT id FROM `%ssite_templates` WHERE templatename='EVO startup - Bootstrap'",
1523
            $sqlParser->prefix);
1524
        $rs = mysqli_query($sqlParser->conn, $sql);
1525
        if (mysqli_num_rows($rs)) {
1526
            $row = mysqli_fetch_assoc($rs);
1527
            $sql = sprintf('UPDATE `%ssite_content` SET template=%s WHERE template=4', $sqlParser->prefix, $row['id']);
1528
            mysqli_query($sqlParser->conn, $sql);
1529
        }
1530
        echo $_lang['ok'] . PHP_EOL;
1531
    }
1532
}
1533
1534
// Install Dependencies
1535
$moduleDependencies = $mdp;
1536
foreach ($moduleDependencies as $dependency) {
1537
    $ds = mysqli_query($sqlParser->conn,
1538
        'SELECT id, guid FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_modules` WHERE name="' . $dependency['module'] . '"');
1539 View Code Duplication
    if (!$ds) {
1540
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1541
1542
        return;
1543
    } else {
1544
        $row = mysqli_fetch_assoc($ds);
1545
        $moduleId = $row["id"];
1546
        $moduleGuid = $row["guid"];
1547
    }
1548
    // get extra id
1549
    $ds = mysqli_query($sqlParser->conn,
1550
        'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE ' . $dependency['column'] . '="' . $dependency['name'] . '"');
1551 View Code Duplication
    if (!$ds) {
1552
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1553
1554
        return;
1555
    } else {
1556
        $row = mysqli_fetch_assoc($ds);
1557
        $extraId = $row["id"];
1558
    }
1559
    // setup extra as module dependency
1560
    $ds = mysqli_query($sqlParser->conn,
1561
        'SELECT module FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` WHERE module=' . $moduleId . ' AND resource=' . $extraId . ' AND type=' . $dependency['type'] . ' LIMIT 1');
1562
    if (!$ds) {
1563
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1564
1565
        return;
1566
    } else {
1567
        if (mysqli_num_rows($ds) === 0) {
1568
            mysqli_query($sqlParser->conn,
1569
                'INSERT INTO ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` (module, resource, type) VALUES(' . $moduleId . ',' . $extraId . ',' . $dependency['type'] . ')');
1570
            echo $dependency['module'] . ' Module: ' . $_lang['depedency_create'] . PHP_EOL;
1571 View Code Duplication
        } else {
1572
            mysqli_query($sqlParser->conn,
1573
                'UPDATE ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` SET module = ' . $moduleId . ', resource = ' . $extraId . ', type = ' . $dependency['type'] . ' WHERE module=' . $moduleId . ' AND resource=' . $extraId . ' AND type=' . $dependency['type']);
1574
            echo $dependency['module'] . ' Module: ' . $_lang['depedency_update'] . PHP_EOL;
1575
        }
1576
        if ($dependency['type'] == 30 || $dependency['type'] == 40) {
1577
            // set extra guid for plugins and snippets
1578
            $ds = mysqli_query($sqlParser->conn,
1579
                'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE id=' . $extraId . ' LIMIT 1');
1580
            if (!$ds) {
1581
                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1582
1583
                return;
1584 View Code Duplication
            } else {
1585
                if (mysqli_num_rows($ds) != 0) {
1586
                    mysqli_query($sqlParser->conn,
1587
                        'UPDATE ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` SET moduleguid = ' . $moduleGuid . ' WHERE id=' . $extraId);
1588
                    echo $dependency['name'] . ': ' . $_lang['guid_set'] . PHP_EOL;
1589
                }
1590
            }
1591
        }
1592
    }
1593
}
1594
1595
// call back function
1596
if ($callBackFnc != "") {
1597
    $callBackFnc ($sqlParser);
1598
}
1599
1600
// Setup the MODX API -- needed for the cache processor
1601
if (!defined('MODX_MANAGER_PATH')) {
1602
    define('MODX_MANAGER_PATH', $base_path . MGR_DIR . '/');
1603
}
1604
$database_type = 'mysqli';
1605
// initiate a new document parser
1606
include_once($path . '../' . MGR_DIR . '/includes/document.parser.class.inc.php');
1607
$modx = new DocumentParser;
1608
$modx->db->connect();
1609
// always empty cache after install
1610
$sync = new EvolutionCMS\Cache();
1611
$sync->setCachepath($path . "../assets/cache/");
1612
$sync->setReport(false);
1613
$sync->emptyCache(); // first empty the cache
1614
1615
// try to chmod the cache go-rwx (for suexeced php)
1616
$chmodSuccess = @chmod($path . '../assets/cache/siteCache.idx.php', 0600);
1617
$chmodSuccess = @chmod($path . '../assets/cache/sitePublishing.idx.php', 0600);
1618
1619
// remove any locks on the manager functions so initial manager login is not blocked
1620
mysqli_query($conn, "TRUNCATE TABLE `" . $table_prefix . "active_users`");
1621
1622
// close db connection
1623
$sqlParser->close();
1624
1625
// andrazk 20070416 - release manager access
1626 View Code Duplication
if (file_exists($path . '../assets/cache/installProc.inc.php')) {
1627
    @chmod($path . '../assets/cache/installProc.inc.php', 0755);
1628
    unlink($path . '../assets/cache/installProc.inc.php');
1629
}
1630
1631
// setup completed!
1632
echo PHP_EOL . $_lang['installation_successful'] . PHP_EOL . PHP_EOL;
1633
//echo "<p>" . $_lang['to_log_into_content_manager'] . "</p>";
1634
if ($installMode == 0) {
1635
    echo strip_tags($_lang['installation_note']) . PHP_EOL;
1636
} else {
1637
    echo strip_tags($_lang['upgrade_note']) . PHP_EOL;
1638
}
1639
1640
1641
if (empty($args)) {
1642
    echo PHP_EOL . 'Remove install folder?' . PHP_EOL;
1643
    $removeInstall = readline("Type 'y' or 'n' to continue: ");
1644
}
1645
//remove installFolder
1646
if ($removeInstall == 'y') {
1647
    removeFolder($path);
1648
    removeFolder($base_path . '.tx');
1649
    unlink($base_path . 'README.md');
1650
    echo 'Install folder deleted!' . PHP_EOL . PHP_EOL;
1651
}
1652
1653
if (!function_exists('removeFolder')) {
1654
    /**
1655
     * RemoveFolder
1656
     *
1657
     * @param string $path
1658
     * @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...
1659
     */
1660
    function removeFolder($path)
1661
    {
1662
        $dir = realpath($path);
1663
        if (!is_dir($dir)) {
1664
            return;
1665
        }
1666
1667
        $it = new RecursiveDirectoryIterator($dir);
1668
        $files = new RecursiveIteratorIterator($it,
1669
            RecursiveIteratorIterator::CHILD_FIRST);
1670
        foreach ($files as $file) {
1671
            if ($file->getFilename() === "." || $file->getFilename() === "..") {
1672
                continue;
1673
            }
1674
            if ($file->isDir()) {
1675
                rmdir($file->getRealPath());
1676
            } else {
1677
                unlink($file->getRealPath());
1678
            }
1679
        }
1680
        rmdir($dir);
1681
    }
1682
}
1683
1684 View Code Duplication
if (!function_exists('propUpdate')) {
1685
    /**
1686
     * Property Update function
1687
     *
1688
     * @param string $new
1689
     * @param string $old
1690
     * @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...
1691
     */
1692
    function propUpdate($new, $old)
1693
    {
1694
        $newArr = parseProperties($new);
1695
        $oldArr = parseProperties($old);
1696
        foreach ($oldArr as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $oldArr of type string is not traversable.
Loading history...
1697
            if (isset($v['0']['options'])) {
1698
                $oldArr[$k]['0']['options'] = $newArr[$k]['0']['options'];
1699
            }
1700
        }
1701
        $return = $oldArr + $newArr;
1702
        $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...
1703
        $return = ($return !== '[]') ? $return : '';
1704
1705
        return $return;
1706
    }
1707
}
1708
1709 View Code Duplication
if (!function_exists('parseProperties')) {
1710
    /**
1711
     * @param string $propertyString
1712
     * @param bool|mixed $json
1713
     * @return string
1714
     */
1715
    function parseProperties($propertyString, $json = false)
0 ignored issues
show
Best Practice introduced by
The function parseProperties() has been defined more than once; this definition is ignored, only the first definition in this file (L542-565) is considered.

This check looks for functions that have already been defined in the same file.

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...
1716
    {
1717
        $propertyString = str_replace('{}', '', $propertyString);
1718
        $propertyString = str_replace('} {', ',', $propertyString);
1719
1720
        if (empty($propertyString)) {
1721
            return array();
1722
        }
1723
        if ($propertyString == '{}' || $propertyString == '[]') {
1724
            return array();
1725
        }
1726
1727
        $jsonFormat = isJson($propertyString, true);
1728
        $property = array();
1729
        // old format
1730
        if ($jsonFormat === false) {
1731
            $props = explode('&', $propertyString);
1732
            foreach ($props as $prop) {
1733
                $prop = trim($prop);
1734
                if ($prop === '') {
1735
                    continue;
1736
                }
1737
1738
                $arr = explode(';', $prop);
1739
                if (!is_array($arr)) {
1740
                    $arr = array();
1741
                }
1742
                $key = explode('=', isset($arr[0]) ? $arr[0] : '');
1743
                if (!is_array($key) || empty($key[0])) {
1744
                    continue;
1745
                }
1746
1747
                $property[$key[0]]['0']['label'] = isset($key[1]) ? trim($key[1]) : '';
1748
                $property[$key[0]]['0']['type'] = isset($arr[1]) ? trim($arr[1]) : '';
1749
                switch ($property[$key[0]]['0']['type']) {
1750
                    case 'list':
1751
                    case 'list-multi':
1752
                    case 'checkbox':
1753
                    case 'radio':
1754
                    case 'menu':
1755
                        $property[$key[0]]['0']['value'] = isset($arr[3]) ? trim($arr[3]) : '';
1756
                        $property[$key[0]]['0']['options'] = isset($arr[2]) ? trim($arr[2]) : '';
1757
                        $property[$key[0]]['0']['default'] = isset($arr[3]) ? trim($arr[3]) : '';
1758
                        break;
1759
                    default:
1760
                        $property[$key[0]]['0']['value'] = isset($arr[2]) ? trim($arr[2]) : '';
1761
                        $property[$key[0]]['0']['default'] = isset($arr[2]) ? trim($arr[2]) : '';
1762
                }
1763
                $property[$key[0]]['0']['desc'] = '';
1764
1765
            }
1766
            // new json-format
1767
        } else {
1768
            if (!empty($jsonFormat)) {
1769
                $property = $jsonFormat;
1770
            }
1771
        }
1772
        if ($json) {
1773
            $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...
1774
        }
1775
        $property = ($property !== '[]') ? $property : '';
1776
1777
        return $property;
1778
    }
1779
}
1780
1781 View Code Duplication
if (!function_exists('isJson')) {
1782
    /**
1783
     * @param string $string
1784
     * @param bool $returnData
1785
     * @return bool|mixed
1786
     */
1787
    function isJson($string, $returnData = false)
1788
    {
1789
        $data = json_decode($string, true);
1790
1791
        return (json_last_error() == JSON_ERROR_NONE) ? ($returnData ? $data : true) : false;
1792
    }
1793
}
1794
1795 View Code Duplication
if (!function_exists('getCreateDbCategory')) {
1796
    /**
1797
     * @param string|int $category
1798
     * @param SqlParser $sqlParser
1799
     * @return int
1800
     */
1801
    function getCreateDbCategory($category, $sqlParser)
1802
    {
1803
        $dbase = $sqlParser->dbname;
1804
        $dbase = '`' . trim($dbase, '`') . '`';
1805
        $table_prefix = $sqlParser->prefix;
1806
        $category_id = 0;
1807
        if (!empty($category)) {
1808
            $category = mysqli_real_escape_string($sqlParser->conn, $category);
1809
            $rs = mysqli_query($sqlParser->conn,
1810
                "SELECT id FROM $dbase.`" . $table_prefix . "categories` WHERE category = '" . $category . "'");
1811
            if (mysqli_num_rows($rs) && ($row = mysqli_fetch_assoc($rs))) {
1812
                $category_id = $row['id'];
1813
            } else {
1814
                $q = "INSERT INTO $dbase.`" . $table_prefix . "categories` (`category`) VALUES ('{$category}');";
1815
                $rs = mysqli_query($sqlParser->conn, $q);
1816
                if ($rs) {
1817
                    $category_id = mysqli_insert_id($sqlParser->conn);
1818
                }
1819
            }
1820
        }
1821
1822
        return $category_id;
1823
    }
1824
}
1825
1826 View Code Duplication
if (!function_exists('removeDocblock')) {
1827
    /**
1828
     * Remove installer Docblock only from components using plugin FileSource / fileBinding
1829
     *
1830
     * @param string $code
1831
     * @param string $type
1832
     * @return string
1833
     */
1834
    function removeDocblock($code, $type)
1835
    {
1836
1837
        $cleaned = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', $code, 1);
1838
1839
        // Procedure taken from plugin.filesource.php
1840
        switch ($type) {
1841
            case 'snippet':
1842
                $elm_name = 'snippets';
1843
                $include = 'return require';
1844
                $count = 47;
1845
                break;
1846
1847
            case 'plugin':
1848
                $elm_name = 'plugins';
1849
                $include = 'require';
1850
                $count = 39;
1851
                break;
1852
1853
            default:
1854
                return $cleaned;
1855
        };
1856
        if (substr(trim($cleaned), 0, $count) == $include . ' MODX_BASE_PATH.\'assets/' . $elm_name . '/') {
1857
            return $cleaned;
1858
        }
1859
1860
        // fileBinding not found - return code incl docblock
1861
        return $code;
1862
    }
1863
}
1864