cli-install.php ➔ f_owc()   A
last analyzed

Complexity

Conditions 3
Paths 6

Size

Total Lines 16

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
nc 6
nop 3
dl 16
loc 16
rs 9.7333
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 . 'stubs/sql/setup.sql';
35
$moduleSQLDataFile = $path . 'stubs/sql/setup.data.sql';
36
$moduleSQLResetFile = $path . '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'] . ' [utf8mb4_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 = 'utf8mb4_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
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
$host = explode(':', $database_server, 2);
311
if (!$conn = mysqli_connect($host[0], $database_user, $database_password,'', isset($host[1]) ? $host[1] : null)) {
312
    $errors++;
313
    echo $_lang['database_connection_failed'] . PHP_EOL;
314
} else {
315
    echo $_lang['ok'] . PHP_EOL;
316
}
317
318
319
// make sure we can use the database
320
if ($installMode > 0 && !mysqli_query($conn, "USE {$dbase}")) {
321
    $errors++;
322
    echo $_lang['database_use_failed'] . PHP_EOL;
323
}
324
325
// check the database collation if not specified in the configuration
326 View Code Duplication
if (!isset ($database_connection_charset) || empty ($database_connection_charset)) {
327
    if (!$rs = mysqli_query($conn, "show session variables like 'collation_database'")) {
328
        $rs = mysqli_query($conn, "show session variables like 'collation_server'");
329
    }
330
    if ($rs && $collation = mysqli_fetch_row($rs)) {
331
        $database_collation = $collation[1];
332
    }
333
    if (empty ($database_collation)) {
334
        $database_collation = 'utf8_unicode_ci';
335
    }
336
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_') - 1);
337
    $database_connection_charset = $database_charset;
338
}
339
340
// determine the database connection method if not specified in the configuration
341
if (!isset($database_connection_method) || empty($database_connection_method)) {
342
    $database_connection_method = 'SET CHARACTER SET';
343
}
344
345
// check table prefix
346
if ($conn && $installMode == 0) {
347
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
348 View Code Duplication
    if ($rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
349
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
350
        $errors++;
351
352
    } else {
353
        echo $_lang['ok'] . PHP_EOL;
354
    }
355
} elseif ($conn && $installMode == 2) {
356
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
357 View Code Duplication
    if (!$rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
358
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_not_exist'] . PHP_EOL;
359
        $errors++;
360
361
    } else {
362
        echo $_lang['ok'] . PHP_EOL;
363
    }
364
}
365
366
// check mysql version
367
if ($conn) {
368
    echo $_lang['checking_mysql_version'];
369
    if (version_compare(mysqli_get_server_info($conn), '5.0.51', '=')) {
370
        echo $_lang['warning'] . ' ' . $_lang['mysql_5051'] . PHP_EOL;
371
        echo $_lang['mysql_5051_warning'] . PHP_EOL;
372 View Code Duplication
    } else {
373
        echo $_lang['ok'] . ' ' . $_lang['mysql_version_is'] . mysqli_get_server_info($conn) . PHP_EOL;
374
    }
375
}
376
377
// check for strict mode
378
if ($conn) {
379
    echo $_lang['checking_mysql_strict_mode'];
380
    $mysqlmode = mysqli_query($conn, "SELECT @@global.sql_mode");
381
    if (mysqli_num_rows($mysqlmode) > 0) {
382
        $modes = mysqli_fetch_array($mysqlmode, MYSQLI_NUM);
383
        //$modes = array("STRICT_TRANS_TABLES"); // for testing
384
        // print_r($modes);
385
        foreach ($modes as $mode) {
386
            if (stristr($mode, "STRICT_TRANS_TABLES") !== false || stristr($mode, "STRICT_ALL_TABLES") !== false) {
387
                echo $_lang['warning'] . ' ' . $_lang['strict_mode'] . PHP_EOL;
388
                echo $_lang['strict_mode_error'] . PHP_EOL;
389
            } else {
390
                echo $_lang['ok'] . PHP_EOL;
391
            }
392
        }
393
    } else {
394
        echo $_lang['ok'] . PHP_EOL;
395
    }
396
}
397
// Version and strict mode check end
398
399
// andrazk 20070416 - add install flag and disable manager login
400
// assets/cache writable?
401
if (is_writable($path . "../assets/cache")) {
402 View Code Duplication
    if (file_exists($path . '../assets/cache/installProc.inc.php')) {
403
        @chmod($path . '../assets/cache/installProc.inc.php', 0755);
404
        unlink($path . '../assets/cache/installProc.inc.php');
405
    }
406
407
    f_owc($path . "../assets/cache/installProc.inc.php", '<?php $installStartTime = ' . time() . '; ?>');
408
}
409
410 View Code Duplication
if ($installMode > 0 && $_POST['installdata'] == "1") {
411
    echo $_lang['sample_web_site'] . ': ' . $_lang['sample_web_site_note'] . PHP_EOL;
412
}
413
414
if ($errors > 0) {
415
    echo $_lang['setup_cannot_continue'] . ' ';
416
417 View Code Duplication
    if ($errors > 1) {
418
        echo $errors . " " . $_lang['errors'] . $_lang['please_correct_errors'] . $_lang['and_try_again_plural'];
419
    } else {
420
        echo $_lang['error'] . $_lang['please_correct_error'] . $_lang['and_try_again'] . PHP_EOL;
421
    }
422
423
    die();
424
}
425
426
427
//////////////////////////////////////////////////////////////////////////////////////
428
$create = false;
429
430
// set timout limit
431
@ set_time_limit(120); // used @ to prevent warning when using safe mode?
432
433
//echo $_lang['setup_database'].PHP_EOL;
434
435
436
if ($installMode == 1) {
437
    include $path . "../" . MGR_DIR . "/includes/config.inc.php";
438
} else {
439
    // get db info from post
440
    $database_server = $databasehost;
441
    $database_user = $databaseloginname;
442
    $database_password = $databaseloginpassword;
443
    $database_collation = $database_collation;
444
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_'));
445
    $database_connection_charset = $database_charset;
446
    $database_connection_method = $database_connection_method;
447
    $dbase = "`" . $database_name . "`";
448
    $table_prefix = $tableprefix;
449
    $adminname = $cmsadmin;
450
    $adminemail = $cmsadminemail;
451
    $adminpass = $cmspassword;
452
    $managerlanguage = $managerlanguage;
453
    $custom_placeholders = array();
454
}
455
456
// set session name variable
457
if (!isset ($site_sessionname)) {
458
    $site_sessionname = 'SN' . uniqid('');
459
}
460
461
// get base path and url
462
$a = explode("install", str_replace("\\", "/", dirname($_SERVER["PHP_SELF"])));
463
if (count($a) > 1) {
464
    array_pop($a);
465
}
466
$url = implode("install", $a);
467
reset($a);
468
$a = explode("install", str_replace("\\", "/", realpath(__DIR__)));
469
if (count($a) > 1) {
470
    array_pop($a);
471
}
472
$pth = implode("install", $a);
473
unset ($a);
474
$base_url = $url . (substr($url, -1) != "/" ? "/" : "");
475
$base_path = $pth . (substr($pth, -1) != "/" ? "/" : "");
476
477
// connect to the database
478
echo $_lang['setup_database_create_connection'] . ': ';
479
$host = explode(':', $database_server, 2);
480
if (!$conn = mysqli_connect($host[0], $database_user, $database_password,'', isset($host[1]) ? $host[1] : null)) {
481
    echo $_lang["setup_database_create_connection_failed"] . " " . $_lang['setup_database_create_connection_failed_note'] . PHP_EOL;
482
483
    return;
484
} else {
485
    echo $_lang['ok'] . PHP_EOL;
486
}
487
488
// select database
489
echo $_lang['setup_database_selection'] . str_replace("`", "", $dbase) . "`: ";
490
if (!mysqli_select_db($conn, str_replace("`", "", $dbase))) {
491
    echo $_lang['setup_database_selection_failed'] . " " . $_lang['setup_database_selection_failed_note'] . PHP_EOL;
492
    $create = true;
493
} else {
494
    if (function_exists('mysqli_set_charset')) {
495
        mysqli_set_charset($conn, $database_charset);
496
    }
497
    mysqli_query($conn, "{$database_connection_method} {$database_connection_charset}");
498
    echo $_lang['ok'] . PHP_EOL;
499
}
500
501
// try to create the database
502
if ($create) {
503
    echo $_lang['setup_database_creation'] . str_replace("`", "", $dbase) . "`: ";
504
    //  if(!@mysqli_create_db(str_replace("`","",$dbase), $conn)) {
505
    if (!mysqli_query($conn,
506
        "CREATE DATABASE $dbase DEFAULT CHARACTER SET $database_charset COLLATE $database_collation")) {
507
        echo $_lang['setup_database_creation_failed'] . " " . $_lang['setup_database_creation_failed_note'] . PHP_EOL;
508
        $errors += 1;
509
510
        echo 'database charset: ' . $database_charset . PHP_EOL;
511
        echo 'database collation: ' . $database_collation . PHP_EOL;
512
513
        echo $_lang['setup_database_creation_failed_note2'] . PHP_EOL;
514
515
        die();
516
517
    } else {
518
        echo $_lang['ok'] . PHP_EOL;
519
    }
520
}
521
522
// check table prefix
523
if ($installMode == 0) {
524
    echo $_lang['checking_table_prefix'] . $table_prefix . "`: ";
525
    if (@ $rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
526
        echo $_lang['failed'] . " " . $_lang['table_prefix_already_inuse'] . PHP_EOL;
527
        $errors += 1;
528
        echo $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
529
530
        return;
531
    } else {
532
        echo $_lang['ok'] . PHP_EOL;
533
    }
534
}
535
536 View Code Duplication
if (!function_exists('propertiesNameValue')) {
537
    /**
538
     * parses a resource property string and returns the result as an array
539
     * duplicate of method in documentParser class
540
     *
541
     * @param string $propertyString
542
     * @return array
543
     */
544
    function propertiesNameValue($propertyString)
545
    {
546
        $parameter = array();
547
        if (!empty ($propertyString)) {
548
            $tmpParams = explode("&", $propertyString);
549
            $countParams = count($tmpParams);
550
            for ($x = 0; $x < $countParams; $x++) {
551
                if (strpos($tmpParams[$x], '=', 0)) {
552
                    $pTmp = explode("=", $tmpParams[$x]);
553
                    $pvTmp = explode(";", trim($pTmp[1]));
554
                    if ($pvTmp[1] == 'list' && $pvTmp[3] != "") {
555
                        $parameter[trim($pTmp[0])] = $pvTmp[3];
556
                    } //list default
557
                    else {
558
                        if ($pvTmp[1] != 'list' && $pvTmp[2] != "") {
559
                            $parameter[trim($pTmp[0])] = $pvTmp[2];
560
                        }
561
                    }
562
                }
563
            }
564
        }
565
566
        return $parameter;
567
    }
568
}
569
570
// check status of Inherit Parent Template plugin
571
$auto_template_logic = 'parent';
572
if ($installMode != 0) {
573
    $rs = mysqli_query($conn,
574
        "SELECT properties, disabled FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='Inherit Parent Template'");
575
    $row = mysqli_fetch_row($rs);
576 View Code Duplication
    if (!$row) {
577
        // not installed
578
        $auto_template_logic = 'system';
579
    } else {
580
        if ($row[1] == 1) {
581
            // installed but disabled
582
            $auto_template_logic = 'system';
583
        } else {
584
            // installed, enabled .. see how it's configured
585
            $properties = parseProperties($row[0]);
586
            if (isset($properties['inheritTemplate'])) {
587
                if ($properties['inheritTemplate'] == 'From First Sibling') {
588
                    $auto_template_logic = 'sibling';
589
                }
590
            }
591
        }
592
    }
593
}
594
595
596
// open db connection
597
$setupPath = realpath(__DIR__);
598
$chunkPath = $path . 'assets/chunks';
599
$snippetPath = $path . 'assets/snippets';
600
$pluginPath = $path . 'assets/plugins';
601
$modulePath = $path . 'assets/modules';
602
$templatePath = $path . 'assets/templates';
603
$tvPath = $path . 'assets/tvs';
604
605
// setup Template template files - array : name, description, type - 0:file or 1:content, parameters, category
606
$mt = &$moduleTemplates;
607 View Code Duplication
if (is_dir($templatePath) && is_readable($templatePath)) {
608
    $d = dir($templatePath);
609
    while (false !== ($tplfile = $d->read())) {
610
        if (substr($tplfile, -4) != '.tpl') {
611
            continue;
612
        }
613
        $params = parse_docblock($templatePath, $tplfile);
614
        if (is_array($params) && (count($params) > 0)) {
615
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
616
            $mt[] = array
617
            (
618
                $params['name'],
619
                $description,
620
                // Don't think this is gonna be used ... but adding it just in case 'type'
621
                $params['type'],
622
                "$templatePath/{$params['filename']}",
623
                $params['modx_category'],
624
                $params['lock_template'],
625
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
626
                isset($params['save_sql_id_as']) ? $params['save_sql_id_as'] : null
627
                // Nessecary to fix template-ID for demo-site
628
            );
629
        }
630
    }
631
    $d->close();
632
}
633
634
// setup Template Variable template files
635
$mtv = &$moduleTVs;
636 View Code Duplication
if (is_dir($tvPath) && is_readable($tvPath)) {
637
    $d = dir($tvPath);
638
    while (false !== ($tplfile = $d->read())) {
639
        if (substr($tplfile, -4) != '.tpl') {
640
            continue;
641
        }
642
        $params = parse_docblock($tvPath, $tplfile);
643
        if (is_array($params) && (count($params) > 0)) {
644
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
645
            $mtv[] = array(
646
                $params['name'],
647
                $params['caption'],
648
                $description,
649
                $params['input_type'],
650
                $params['input_options'],
651
                $params['input_default'],
652
                $params['output_widget'],
653
                $params['output_widget_params'],
654
                "$templatePath/{$params['filename']}",
655
                /* not currently used */
656
                $params['template_assignments'] != "*" ?
657
                    $params['template_assignments'] :
658
                    implode(',', array_map(function($value){return isset($value[0]) && is_scalar($value[0]);},$mt)),
659
                /* comma-separated list of template names */
660
                $params['modx_category'],
661
                $params['lock_tv'],
662
                /* value should be 1 or 0 */
663
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
664
            );
665
        }
666
    }
667
    $d->close();
668
}
669
670
// setup chunks template files - array : name, description, type - 0:file or 1:content, file or content
671
$mc = &$moduleChunks;
672 View Code Duplication
if (is_dir($chunkPath) && is_readable($chunkPath)) {
673
    $d = dir($chunkPath);
674
    while (false !== ($tplfile = $d->read())) {
675
        if (substr($tplfile, -4) != '.tpl') {
676
            continue;
677
        }
678
        $params = parse_docblock($chunkPath, $tplfile);
679
        if (is_array($params) && count($params) > 0) {
680
            $mc[] = array(
681
                $params['name'],
682
                $params['description'],
683
                "$chunkPath/{$params['filename']}",
684
                $params['modx_category'],
685
                array_key_exists('overwrite', $params) ? $params['overwrite'] : 'true',
686
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
687
            );
688
        }
689
    }
690
    $d->close();
691
}
692
693
// setup snippets template files - array : name, description, type - 0:file or 1:content, file or content,properties
694
$ms = &$moduleSnippets;
695 View Code Duplication
if (is_dir($snippetPath) && is_readable($snippetPath)) {
696
    $d = dir($snippetPath);
697
    while (false !== ($tplfile = $d->read())) {
698
        if (substr($tplfile, -4) != '.tpl') {
699
            continue;
700
        }
701
        $params = parse_docblock($snippetPath, $tplfile);
702
        if (is_array($params) && count($params) > 0) {
703
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
704
            $ms[] = array(
705
                $params['name'],
706
                $description,
707
                "$snippetPath/{$params['filename']}",
708
                $params['properties'],
709
                $params['modx_category'],
710
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
711
            );
712
        }
713
    }
714
    $d->close();
715
}
716
717
// setup plugins template files - array : name, description, type - 0:file or 1:content, file or content,properties
718
$mp = &$modulePlugins;
719 View Code Duplication
if (is_dir($pluginPath) && is_readable($pluginPath)) {
720
    $d = dir($pluginPath);
721
    while (false !== ($tplfile = $d->read())) {
722
        if (substr($tplfile, -4) != '.tpl') {
723
            continue;
724
        }
725
        $params = parse_docblock($pluginPath, $tplfile);
726
        if (is_array($params) && count($params) > 0) {
727
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
728
            $mp[] = array(
729
                $params['name'],
730
                $description,
731
                "$pluginPath/{$params['filename']}",
732
                $params['properties'],
733
                $params['events'],
734
                $params['guid'],
735
                $params['modx_category'],
736
                $params['legacy_names'],
737
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
738
                (int)$params['disabled']
739
            );
740
        }
741
    }
742
    $d->close();
743
}
744
745
// setup modules - array : name, description, type - 0:file or 1:content, file or content,properties, guid,enable_sharedparams
746
$mm = &$moduleModules;
747
$mdp = &$moduleDependencies;
748 View Code Duplication
if (is_dir($modulePath) && is_readable($modulePath)) {
749
    $d = dir($modulePath);
750
    while (false !== ($tplfile = $d->read())) {
751
        if (substr($tplfile, -4) != '.tpl') {
752
            continue;
753
        }
754
        $params = parse_docblock($modulePath, $tplfile);
755
        if (is_array($params) && count($params) > 0) {
756
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
757
            $mm[] = array(
758
                $params['name'],
759
                $description,
760
                "$modulePath/{$params['filename']}",
761
                $params['properties'],
762
                $params['guid'],
763
                (int)$params['shareparams'],
764
                $params['modx_category'],
765
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
766
            );
767
        }
768
        if ((int)$params['shareparams'] || !empty($params['dependencies'])) {
769
            $dependencies = explode(',', $params['dependencies']);
770
            foreach ($dependencies as $dependency) {
771
                $dependency = explode(':', $dependency);
772
                switch (trim($dependency[0])) {
773
                    case 'template':
774
                        $mdp[] = array(
775
                            'module' => $params['name'],
776
                            'table'  => 'templates',
777
                            'column' => 'templatename',
778
                            'type'   => 50,
779
                            'name'   => trim($dependency[1])
780
                        );
781
                        break;
782
                    case 'tv':
783
                    case 'tmplvar':
784
                        $mdp[] = array(
785
                            'module' => $params['name'],
786
                            'table'  => 'tmplvars',
787
                            'column' => 'name',
788
                            'type'   => 60,
789
                            'name'   => trim($dependency[1])
790
                        );
791
                        break;
792
                    case 'chunk':
793
                    case 'htmlsnippet':
794
                        $mdp[] = array(
795
                            'module' => $params['name'],
796
                            'table'  => 'htmlsnippets',
797
                            'column' => 'name',
798
                            'type'   => 10,
799
                            'name'   => trim($dependency[1])
800
                        );
801
                        break;
802
                    case 'snippet':
803
                        $mdp[] = array(
804
                            'module' => $params['name'],
805
                            'table'  => 'snippets',
806
                            'column' => 'name',
807
                            'type'   => 40,
808
                            'name'   => trim($dependency[1])
809
                        );
810
                        break;
811
                    case 'plugin':
812
                        $mdp[] = array(
813
                            'module' => $params['name'],
814
                            'table'  => 'plugins',
815
                            'column' => 'name',
816
                            'type'   => 30,
817
                            'name'   => trim($dependency[1])
818
                        );
819
                        break;
820
                    case 'resource':
821
                        $mdp[] = array(
822
                            'module' => $params['name'],
823
                            'table'  => 'content',
824
                            'column' => 'pagetitle',
825
                            'type'   => 20,
826
                            'name'   => trim($dependency[1])
827
                        );
828
                        break;
829
                }
830
            }
831
        }
832
    }
833
    $d->close();
834
}
835
836
// setup callback function
837
$callBackFnc = "clean_up";
838
839
include $path . "src/sqlParser.class.php";
840
$sqlParser = new SqlParser($database_server, $database_user, $database_password, str_replace("`", "", $dbase),
841
    $table_prefix, $adminname, $adminemail, $adminpass, $database_connection_charset, $managerlanguage,
842
    $database_connection_method, $auto_template_logic);
843
$sqlParser->mode = ($installMode < 1) ? "new" : "upd";
844
/* image and file manager paths now handled via settings screen in Manager
845
$sqlParser->imageUrl = 'http://' . $_SERVER['SERVER_NAME'] . $base_url . "assets/";
846
$sqlParser->imageUrl = "assets/";
847
$sqlParser->imagePath = $base_path . "assets/";
848
$sqlParser->fileManagerPath = $base_path;
849
*/
850
$sqlParser->ignoreDuplicateErrors = true;
851
$sqlParser->connect();
852
853
// install/update database
854
echo $_lang['setup_database_creating_tables'];
855
if ($moduleSQLBaseFile) {
856
    $sqlParser->process($moduleSQLBaseFile);
857
    // display database results
858
    if ($sqlParser->installFailed == true) {
859
        $errors += 1;
860
        echo $_lang['database_alerts'] . PHP_EOL;
861
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
862
        echo $_lang['installation_error_occured'] . PHP_EOL;
863 View Code Duplication
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
864
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
865
        }
866
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
867
        die();
868
    } else {
869
        echo $_lang['ok'] . PHP_EOL;
870
    }
871
}
872
873
// custom or not
874
if (file_exists($path . "../assets/cache/siteManager.php")) {
875
    $mgrdir = 'include_once(__DIR__."/../../assets/cache/siteManager.php");';
876
} else {
877
    $mgrdir = 'define(\'MGR_DIR\', \'manager\');';
878
}
879
880
// write the config.inc.php file if new installation
881
echo $_lang['writing_config_file'];
882
883
$confph = array();
884
$confph['database_server'] = $database_server;
885
$confph['user_name'] = mysqli_real_escape_string($conn, $database_user);
886
$confph['password'] = mysqli_real_escape_string($conn, $database_password);
887
$confph['connection_charset'] = $database_connection_charset;
888
$confph['connection_method'] = $database_connection_method;
889
$confph['dbase'] = str_replace('`', '', $dbase);
890
$confph['table_prefix'] = $table_prefix;
891
$confph['lastInstallTime'] = time();
892
$confph['site_sessionname'] = $site_sessionname;
893
894
$configString = file_get_contents($path . 'stubs/config.tpl');
895
$configString = parse($configString, $confph);
896
897
$filename = $base_path . MGR_DIR . '/includes/config.inc.php';
898
$configFileFailed = false;
899
if (@ !$handle = fopen($filename, 'w')) {
900
    $configFileFailed = true;
901
}
902
903
// write $somecontent to our opened file.
904
if (@ fwrite($handle, $configString) === false) {
905
    $configFileFailed = true;
906
}
907
@ fclose($handle);
908
909
// try to chmod the config file go-rwx (for suexeced php)
910
$chmodSuccess = @chmod($filename, 0404);
911
912
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...
913
    echo $_lang['failed'] . PHP_EOL;
914
    $errors += 1;
915
916
    echo $_lang['cant_write_config_file'] . ' ' . MGR_DIR . '/includes/config.inc.php' . PHP_EOL;
917
    echo ' ' . PHP_EOL;
918
    echo ' ' . PHP_EOL;
919
    echo $configString;
920
    echo ' ' . PHP_EOL;
921
    echo ' ' . PHP_EOL;
922
    echo $_lang['cant_write_config_file_note'] . PHP_EOL;
923
    die();
924
925
} else {
926
    echo $_lang['ok'] . PHP_EOL;
927
}
928
929
// generate new site_id and set manager theme to default
930 View Code Duplication
if ($installMode == 0) {
931
    $siteid = uniqid('');
932
    mysqli_query($sqlParser->conn,
933
        "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid'),('manager_theme','default')");
934
} else {
935
    // update site_id if missing
936
    $ds = mysqli_query($sqlParser->conn,
937
        "SELECT setting_name,setting_value FROM $dbase.`" . $table_prefix . "system_settings` WHERE setting_name='site_id'");
938
    if ($ds) {
939
        $r = mysqli_fetch_assoc($ds);
940
        $siteid = $r['setting_value'];
941
        if ($siteid == '' || $siteid = 'MzGeQ2faT4Dw06+U49x3') {
942
            $siteid = uniqid('');
943
            mysqli_query($sqlParser->conn,
944
                "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid')");
945
        }
946
    }
947
}
948
949
// Reset database for installation of demo-site
950
if ($installData && $moduleSQLDataFile && $moduleSQLResetFile) {
951
    echo $_lang['resetting_database'];
952
    $sqlParser->process($moduleSQLResetFile);
953
    // display database results
954
    if ($sqlParser->installFailed == true) {
955
        $errors += 1;
956
        echo $_lang['database_alerts'] . PHP_EOL;
957
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
958
        echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
959
        /*
960
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
961
            echo "<em>" . $sqlParser->mysqlErrors[$i]["error"] . "</em>" . $_lang['during_execution_of_sql'] . "<span class='mono'>" . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . "</span>.<hr />";
962
        }
963
        echo "</p>";*/
964
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
965
        die();
966
    } else {
967
        echo $_lang['ok'] . PHP_EOL;
968
    }
969
}
970
971
// Install Templates
972
$moduleTemplate = $mt;
973
if (!empty($moduleTemplate) || $installData) {
974
    echo PHP_EOL . $_lang['templates'] . ":" . PHP_EOL;
975
    //$selTemplates = $_POST['template'];
976
    foreach ($moduleTemplates as $k => $moduleTemplate) {
977
        $installSample = in_array('sample', $moduleTemplate[6]) && $installData == 1;
978
        if ($installSample || is_array($moduleTemplate)) {
979
            $name = mysqli_real_escape_string($conn, $moduleTemplate[0]);
980
            $desc = mysqli_real_escape_string($conn, $moduleTemplate[1]);
981
            $category = mysqli_real_escape_string($conn, $moduleTemplate[4]);
982
            $locked = mysqli_real_escape_string($conn, $moduleTemplate[5]);
983
            $filecontent = $moduleTemplate[3];
984
            $save_sql_id_as = $moduleTemplate[7]; // Nessecary for demo-site
985
            if (!file_exists($filecontent)) {
986
                echo "  $name: " . $_lang['unable_install_template'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
987
            } else {
988
                // Create the category if it does not already exist
989
                $category_id = getCreateDbCategory($category, $sqlParser);
990
991
                // Strip the first comment up top
992
                $template = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
993
                $template = mysqli_real_escape_string($conn, $template);
994
995
                // See if the template already exists
996
                $rs = mysqli_query($sqlParser->conn,
997
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name'");
998
999
                if (mysqli_num_rows($rs)) {
1000
                    if (!mysqli_query($sqlParser->conn,
1001
                        "UPDATE $dbase.`" . $table_prefix . "site_templates` SET content='$template', description='$desc', category=$category_id, locked='$locked'  WHERE templatename='$name' LIMIT 1;")) {
1002
                        $errors += 1;
1003
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1004
1005
                        return;
1006
                    }
1007
                    if (!is_null($save_sql_id_as)) {
1008
                        $sql_id = @mysqli_insert_id($sqlParser->conn);
1009
                        if (!$sql_id) {
1010
                            $idQuery = mysqli_fetch_assoc(mysqli_query($sqlParser->conn,
1011
                                "SELECT id FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name' LIMIT 1;"));
1012
                            $sql_id = $idQuery['id'];
1013
                        }
1014
                        $custom_placeholders[$save_sql_id_as] = $sql_id;
1015
                    }
1016
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1017
                } else {
1018
                    if (!@ mysqli_query($sqlParser->conn,
1019
                        "INSERT INTO $dbase.`" . $table_prefix . "site_templates` (templatename,description,content,category,locked) VALUES('$name','$desc','$template',$category_id,'$locked');")) {
1020
                        $errors += 1;
1021
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1022
                        die();
1023
                    }
1024
                    if (!is_null($save_sql_id_as)) {
1025
                        $custom_placeholders[$save_sql_id_as] = @mysqli_insert_id($sqlParser->conn);
1026
                    }
1027
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1028
                }
1029
            }
1030
        }
1031
    }
1032
}
1033
1034
// Install Template Variables
1035
$moduleTVs = $mtv;
1036
if (is_array($moduleTVs) || $installData) {
1037
    echo PHP_EOL . $_lang['tvs'] . ': ' . PHP_EOL;
1038
    //$selTVs = $_POST['tv'];
1039
    foreach ($moduleTVs as $k => $moduleTV) {
1040
        $installSample = in_array('sample', $moduleTV[12]) && $installData == 1;
1041
        if ($installSample || is_array($moduleTVs)) {
1042
            $name = mysqli_real_escape_string($conn, $moduleTV[0]);
1043
            $caption = mysqli_real_escape_string($conn, $moduleTV[1]);
1044
            $desc = mysqli_real_escape_string($conn, $moduleTV[2]);
1045
            $input_type = mysqli_real_escape_string($conn, $moduleTV[3]);
1046
            $input_options = mysqli_real_escape_string($conn, $moduleTV[4]);
1047
            $input_default = mysqli_real_escape_string($conn, $moduleTV[5]);
1048
            $output_widget = mysqli_real_escape_string($conn, $moduleTV[6]);
1049
            $output_widget_params = mysqli_real_escape_string($conn, $moduleTV[7]);
1050
            $filecontent = $moduleTV[8];
1051
            $assignments = $moduleTV[9];
1052
            $category = mysqli_real_escape_string($conn, $moduleTV[10]);
1053
            $locked = mysqli_real_escape_string($conn, $moduleTV[11]);
1054
1055
1056
            // Create the category if it does not already exist
1057
            $category = getCreateDbCategory($category, $sqlParser);
1058
1059
            $rs = mysqli_query($sqlParser->conn,
1060
                "SELECT * FROM $dbase.`" . $table_prefix . "site_tmplvars` WHERE name='$name'");
1061
            if (mysqli_num_rows($rs)) {
1062
                $insert = true;
1063
                while ($row = mysqli_fetch_assoc($rs)) {
1064
                    if (!mysqli_query($sqlParser->conn,
1065
                        "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']};")) {
1066
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1067
1068
                        return;
1069
                    }
1070
                    $insert = false;
1071
                }
1072
                echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1073
            } else {
1074
                $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');";
1075
                if (!mysqli_query($sqlParser->conn, $q)) {
1076
                    echo mysqli_error($sqlParser->conn) . PHP_EOL;
1077
1078
                    return;
1079
                }
1080
                echo "  $name: " . $_lang['installed'] . PHP_EOL;
1081
            }
1082
1083
            // add template assignments
1084
            $assignments = explode(',', $assignments);
1085
1086
            if (count($assignments) > 0) {
1087
1088
                // remove existing tv -> template assignments
1089
                $ds = mysqli_query($sqlParser->conn,
1090
                    "SELECT id FROM $dbase.`" . $table_prefix . "site_tmplvars` WHERE name='$name' AND description='$desc';");
1091
                $row = mysqli_fetch_assoc($ds);
1092
                $id = $row["id"];
1093
                mysqli_query($sqlParser->conn,
1094
                    'DELETE FROM ' . $dbase . '.`' . $table_prefix . 'site_tmplvar_templates` WHERE tmplvarid = \'' . $id . '\'');
1095
1096
                // add tv -> template assignments
1097
                foreach ($assignments as $assignment) {
1098
                    $template = mysqli_real_escape_string($conn, $assignment);
1099
                    $ts = mysqli_query($sqlParser->conn,
1100
                        "SELECT id FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$template';");
1101
                    if ($ds && $ts) {
1102
                        $tRow = mysqli_fetch_assoc($ts);
1103
                        $templateId = $tRow['id'];
1104
                        mysqli_query($sqlParser->conn,
1105
                            "INSERT INTO $dbase.`" . $table_prefix . "site_tmplvar_templates` (tmplvarid, templateid) VALUES($id, $templateId)");
1106
                    }
1107
                }
1108
            }
1109
        }
1110
    }
1111
}
1112
1113
1114
$moduleChunks = $mc;
1115
// Install Chunks
1116
if (is_array($moduleChunks) || $installData) {
1117
    echo PHP_EOL . $_lang['chunks'] . ": " . PHP_EOL;
1118
    foreach ($moduleChunks as $k => $moduleChunk) {
1119
        $installSample = in_array('sample', $moduleChunk[5]) && $installData == 1;
1120
        $count_new_name = 0;
1121
        if ($installSample || is_array($moduleChunks)) {
1122
1123
            $name = mysqli_real_escape_string($conn, $moduleChunk[0]);
1124
            $desc = mysqli_real_escape_string($conn, $moduleChunk[1]);
1125
            $category = mysqli_real_escape_string($conn, $moduleChunk[3]);
1126
            $overwrite = mysqli_real_escape_string($conn, $moduleChunk[4]);
1127
            $filecontent = $moduleChunk[2];
1128
1129
            if (!file_exists($filecontent)) {
1130
                echo "  $name: " . $_lang['unable_install_chunk'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1131
            } else {
1132
1133
                // Create the category if it does not already exist
1134
                $category_id = getCreateDbCategory($category, $sqlParser);
1135
1136
                $chunk = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
1137
                $chunk = mysqli_real_escape_string($conn, $chunk);
1138
                $rs = mysqli_query($sqlParser->conn,
1139
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$name'");
1140
                $count_original_name = mysqli_num_rows($rs);
1141 View Code Duplication
                if ($overwrite == 'false') {
1142
                    $newname = $name . '-' . str_replace('.', '_', $modx_version);
1143
                    $rs = mysqli_query($sqlParser->conn,
1144
                        "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$newname'");
1145
                    $count_new_name = mysqli_num_rows($rs);
1146
                }
1147
                $update = $count_original_name > 0 && $overwrite == 'true';
1148
                if ($update) {
1149
                    if (!mysqli_query($sqlParser->conn,
1150
                        "UPDATE $dbase.`" . $table_prefix . "site_htmlsnippets` SET snippet='$chunk', description='$desc', category=$category_id WHERE name='$name';")) {
1151
                        $errors += 1;
1152
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1153
1154
                        return;
1155
                    }
1156
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1157
                } elseif ($count_new_name == 0) {
1158
                    if ($count_original_name > 0 && $overwrite == 'false') {
1159
                        $name = $newname;
1160
                    }
1161
                    if (!mysqli_query($sqlParser->conn,
1162
                        "INSERT INTO $dbase.`" . $table_prefix . "site_htmlsnippets` (name,description,snippet,category) VALUES('$name','$desc','$chunk',$category_id);")) {
1163
                        $errors += 1;
1164
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1165
1166
                        return;
1167
                    }
1168
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1169
                }
1170
            }
1171
        }
1172
    }
1173
}
1174
1175
// Install Modules
1176
$moduleModules = $mm;
1177
if (is_array($moduleModules) || $installData) {
1178
    echo PHP_EOL . $_lang['modules'] . ":" . PHP_EOL;
1179
    //$selModules = $_POST['module'];
1180
    foreach ($moduleModules as $k => $moduleModule) {
1181
        $installSample = in_array('sample', $moduleModule[7]) && $installData == 1;
1182
        if ($installSample || is_array($moduleModules)) {
1183
            $name = mysqli_real_escape_string($conn, $moduleModule[0]);
1184
            $desc = mysqli_real_escape_string($conn, $moduleModule[1]);
1185
            $filecontent = $moduleModule[2];
1186
            $properties = $moduleModule[3];
1187
            $guid = mysqli_real_escape_string($conn, $moduleModule[4]);
1188
            $shared = mysqli_real_escape_string($conn, $moduleModule[5]);
1189
            $category = mysqli_real_escape_string($conn, $moduleModule[6]);
1190
            if (!file_exists($filecontent)) {
1191
                echo "  $name: " . $_lang['unable_install_module'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1192
            } else {
1193
1194
                // Create the category if it does not already exist
1195
                $category = getCreateDbCategory($category, $sqlParser);
1196
1197
                $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...
1198
                // $module = removeDocblock($module, 'module'); // Modules have no fileBinding, keep docblock for info-tab
1199
                $module = mysqli_real_escape_string($conn, $module);
1200
                $rs = mysqli_query($sqlParser->conn,
1201
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_modules` WHERE name='$name'");
1202
                if (mysqli_num_rows($rs)) {
1203
                    $row = mysqli_fetch_assoc($rs);
1204
                    $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1205
                    if (!mysqli_query($sqlParser->conn,
1206
                        "UPDATE $dbase.`" . $table_prefix . "site_modules` SET modulecode='$module', description='$desc', properties='$props', enable_sharedparams='$shared' WHERE name='$name';")) {
1207
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1208
1209
                        return;
1210
                    }
1211
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1212
                } else {
1213
                    if ($properties != null) {
1214
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
1215
                    }
1216
                    if (!mysqli_query($sqlParser->conn,
1217
                        "INSERT INTO $dbase.`" . $table_prefix . "site_modules` (name,description,modulecode,properties,guid,enable_sharedparams,category) VALUES('$name','$desc','$module','$properties','$guid','$shared', $category);")) {
1218
                        echo "<p>" . mysqli_error($sqlParser->conn) . "</p>";
1219
1220
                        return;
1221
                    }
1222
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1223
                }
1224
            }
1225
        }
1226
    }
1227
}
1228
1229
// Install Plugins
1230
$modulePlugins = $mp;
1231
if (is_array($modulePlugins) || $installData) {
1232
    echo PHP_EOL . $_lang['plugins'] . ":" . PHP_EOL;
1233
    $selPlugs = $_POST['plugin'];
1234
    foreach ($modulePlugins as $k => $modulePlugin) {
1235
        //$installSample = in_array('sample', $modulePlugin[8]) && $installData == 1;
1236
        if ($installSample || is_array($modulePlugins)) {
1237
            $name = mysqli_real_escape_string($conn, $modulePlugin[0]);
1238
            $desc = mysqli_real_escape_string($conn, $modulePlugin[1]);
1239
            $filecontent = $modulePlugin[2];
1240
            $properties = $modulePlugin[3];
1241
            $events = explode(",", $modulePlugin[4]);
1242
            $guid = mysqli_real_escape_string($conn, $modulePlugin[5]);
1243
            $category = mysqli_real_escape_string($conn, $modulePlugin[6]);
1244
            $leg_names = '';
1245
            $disabled = $modulePlugin[9];
1246 View Code Duplication
            if (array_key_exists(7, $modulePlugin)) {
1247
                // parse comma-separated legacy names and prepare them for sql IN clause
1248
                $leg_names = "'" . implode("','",
1249
                        preg_split('/\s*,\s*/', mysqli_real_escape_string($conn, $modulePlugin[7]))) . "'";
1250
            }
1251
            if (!file_exists($filecontent)) {
1252
                echo "  $name: " . $_lang['unable_install_plugin'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1253
            } else {
1254
1255
                // disable legacy versions based on legacy_names provided
1256 View Code Duplication
                if (!empty($leg_names)) {
1257
                    $update_query = "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE name IN ($leg_names);";
1258
                    $rs = mysqli_query($sqlParser->conn, $update_query);
1259
                }
1260
1261
                // Create the category if it does not already exist
1262
                $category = getCreateDbCategory($category, $sqlParser);
1263
1264
                $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...
1265
                $plugin = removeDocblock($plugin, 'plugin');
1266
                $plugin = mysqli_real_escape_string($conn, $plugin);
1267
                $rs = mysqli_query($sqlParser->conn,
1268
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='$name'");
1269
                if (mysqli_num_rows($rs)) {
1270
                    $insert = true;
1271
                    while ($row = mysqli_fetch_assoc($rs)) {
1272
                        $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1273
                        if ($row['description'] == $desc) {
1274 View Code Duplication
                            if (!mysqli_query($sqlParser->conn,
1275
                                "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET plugincode='$plugin', description='$desc', properties='$props' WHERE id={$row['id']};")) {
1276
                                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1277
1278
                                return;
1279
                            }
1280
                            $insert = false;
1281 View Code Duplication
                        } else {
1282
                            if (!mysqli_query($sqlParser->conn,
1283
                                "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE id={$row['id']};")) {
1284
                                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1285
1286
                                return;
1287
                            }
1288
                        }
1289
                    }
1290
                    if ($insert === true) {
1291
                        if(!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`".$table_prefix."site_plugins` (name,description,plugincode,properties,moduleguid,disabled,category) VALUES('$name','$desc','$plugin','$props','$guid','0',$category);")) {
1292
                            echo mysqli_error($sqlParser->conn) . PHP_EOL;
1293
1294
                            return;
1295
                        }
1296
                    }
1297
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1298 View Code Duplication
                } else {
1299
                    if ($properties != null) {
1300
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
1301
                    }
1302
                    if (!mysqli_query($sqlParser->conn,
1303
                        "INSERT INTO $dbase.`" . $table_prefix . "site_plugins` (name,description,plugincode,properties,moduleguid,category,disabled) VALUES('$name','$desc','$plugin','$properties','$guid',$category,$disabled);")) {
1304
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1305
1306
                        return;
1307
                    }
1308
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1309
                }
1310
                // add system events
1311 View Code Duplication
                if (count($events) > 0) {
1312
                    $ds = mysqli_query($sqlParser->conn,
1313
                        "SELECT id FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='$name' AND description='$desc';");
1314
                    if ($ds) {
1315
                        $row = mysqli_fetch_assoc($ds);
1316
                        $id = $row["id"];
1317
                        $_events = implode("','", $events);
1318
                        // add new events
1319
                        $sql = "INSERT IGNORE 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 ('{$_events}')";
1320
                        mysqli_query($sqlParser->conn, $sql);
1321
                        // remove absent events
1322
                        $sql = "DELETE `pe` FROM {$dbase}.`{$table_prefix}site_plugin_events` `pe` LEFT JOIN {$dbase}.`{$table_prefix}system_eventnames` `se` ON `pe`.`evtid`=`se`.`id` AND `name` IN ('{$_events}') WHERE ISNULL(`name`) AND `pluginid` = {$id}";
1323
                        mysqli_query($sqlParser->conn, $sql);
1324
                    }
1325
                }
1326
            }
1327
        }
1328
    }
1329
}
1330
1331
// Install Snippets
1332
$moduleSnippet = $ms;
1333
if (is_array($moduleSnippet) || $installData) {
1334
    echo PHP_EOL . $_lang['snippets'] . ":" . PHP_EOL;
1335
    //$selSnips = $_POST['snippet'];
1336
    foreach ($moduleSnippets as $k => $moduleSnippet) {
1337
        $installSample = in_array('sample', $moduleSnippet[5]) && $installData == 1;
1338
        if ($installSample || is_array($moduleSnippet)) {
1339
            $name = mysqli_real_escape_string($conn, $moduleSnippet[0]);
1340
            $desc = mysqli_real_escape_string($conn, $moduleSnippet[1]);
1341
            $filecontent = $moduleSnippet[2];
1342
            $properties = $moduleSnippet[3];
1343
            $category = mysqli_real_escape_string($conn, $moduleSnippet[4]);
1344
            if (!file_exists($filecontent)) {
1345
                echo "  $name: " . $_lang['unable_install_snippet'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1346
            } else {
1347
1348
                // Create the category if it does not already exist
1349
                $category = getCreateDbCategory($category, $sqlParser);
1350
1351
                $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...
1352
                $snippet = removeDocblock($snippet, 'snippet');
1353
                $snippet = mysqli_real_escape_string($conn, $snippet);
1354
                $rs = mysqli_query($sqlParser->conn,
1355
                    "SELECT * FROM $dbase.`" . $table_prefix . "site_snippets` WHERE name='$name'");
1356
                if (mysqli_num_rows($rs)) {
1357
                    $row = mysqli_fetch_assoc($rs);
1358
                    $props = mysqli_real_escape_string($conn, propUpdate($properties, $row['properties']));
1359
                    if (!mysqli_query($sqlParser->conn,
1360
                        "UPDATE $dbase.`" . $table_prefix . "site_snippets` SET snippet='$snippet', description='$desc', properties='$props' WHERE name='$name';")) {
1361
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1362
1363
                        return;
1364
                    }
1365
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1366 View Code Duplication
                } else {
1367
                    if ($properties != null) {
1368
                        $properties = mysqli_real_escape_string($conn, parseProperties($properties, true));
1369
                    }
1370
                    if (!mysqli_query($sqlParser->conn,
1371
                        "INSERT INTO $dbase.`" . $table_prefix . "site_snippets` (name,description,snippet,properties,category) VALUES('$name','$desc','$snippet','$properties',$category);")) {
1372
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1373
1374
                        return;
1375
                    }
1376
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1377
                }
1378
            }
1379
        }
1380
    }
1381
}
1382
1383
// Install demo-site
1384
if ($installData && $moduleSQLDataFile) {
1385
    echo PHP_EOL . $_lang['installing_demo_site'];
1386
    $sqlParser->process($moduleSQLDataFile);
1387
    // display database results
1388
    if ($sqlParser->installFailed == true) {
1389
        $errors += 1;
1390
        echo $_lang['database_alerts'] . PHP_EOL;
1391
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
1392
        echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
1393 View Code Duplication
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
1394
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
1395
        }
1396
1397
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
1398
1399
        return;
1400 View Code Duplication
    } else {
1401
        $sql = sprintf("SELECT id FROM `%ssite_templates` WHERE templatename='EVO startup - Bootstrap'",
1402
            $sqlParser->prefix);
1403
        $rs = mysqli_query($sqlParser->conn, $sql);
1404
        if (mysqli_num_rows($rs)) {
1405
            $row = mysqli_fetch_assoc($rs);
1406
            $sql = sprintf('UPDATE `%ssite_content` SET template=%s WHERE template=4', $sqlParser->prefix, $row['id']);
1407
            mysqli_query($sqlParser->conn, $sql);
1408
        }
1409
        echo $_lang['ok'] . PHP_EOL;
1410
    }
1411
}
1412
1413
// Install Dependencies
1414
$moduleDependencies = $mdp;
1415
foreach ($moduleDependencies as $dependency) {
1416
    $ds = mysqli_query($sqlParser->conn,
1417
        'SELECT id, guid FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_modules` WHERE name="' . $dependency['module'] . '"');
1418 View Code Duplication
    if (!$ds) {
1419
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1420
1421
        return;
1422
    } else {
1423
        $row = mysqli_fetch_assoc($ds);
1424
        $moduleId = $row["id"];
1425
        $moduleGuid = $row["guid"];
1426
    }
1427
    // get extra id
1428
    $ds = mysqli_query($sqlParser->conn,
1429
        'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE ' . $dependency['column'] . '="' . $dependency['name'] . '"');
1430 View Code Duplication
    if (!$ds) {
1431
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1432
1433
        return;
1434
    } else {
1435
        $row = mysqli_fetch_assoc($ds);
1436
        $extraId = $row["id"];
1437
    }
1438
    // setup extra as module dependency
1439
    $ds = mysqli_query($sqlParser->conn,
1440
        'SELECT module FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` WHERE module=' . $moduleId . ' AND resource=' . $extraId . ' AND type=' . $dependency['type'] . ' LIMIT 1');
1441
    if (!$ds) {
1442
        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1443
1444
        return;
1445
    } else {
1446
        if (mysqli_num_rows($ds) === 0) {
1447
            mysqli_query($sqlParser->conn,
1448
                'INSERT INTO ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` (module, resource, type) VALUES(' . $moduleId . ',' . $extraId . ',' . $dependency['type'] . ')');
1449
            echo $dependency['module'] . ' Module: ' . $_lang['depedency_create'] . PHP_EOL;
1450
        } else {
1451
            mysqli_query($sqlParser->conn,
1452
                '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']);
1453
            echo $dependency['module'] . ' Module: ' . $_lang['depedency_update'] . PHP_EOL;
1454
        }
1455
        if ($dependency['type'] == 30 || $dependency['type'] == 40) {
1456
            // set extra guid for plugins and snippets
1457
            $ds = mysqli_query($sqlParser->conn,
1458
                'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE id=' . $extraId . ' LIMIT 1');
1459
            if (!$ds) {
1460
                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1461
1462
                return;
1463
            } else {
1464
                if (mysqli_num_rows($ds) != 0) {
1465
                    mysqli_query($sqlParser->conn,
1466
                        'UPDATE ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` SET moduleguid = ' . $moduleGuid . ' WHERE id=' . $extraId);
1467
                    echo $dependency['name'] . ': ' . $_lang['guid_set'] . PHP_EOL;
1468
                }
1469
            }
1470
        }
1471
    }
1472
}
1473
1474
// call back function
1475
if ($callBackFnc != "") {
1476
    $callBackFnc ($sqlParser);
1477
}
1478
1479
// Setup the MODX API -- needed for the cache processor
1480
if (!defined('MODX_MANAGER_PATH')) {
1481
    define('MODX_MANAGER_PATH', $base_path . MGR_DIR . '/');
1482
}
1483
$database_type = 'mysqli';
1484
// initiate a new document parser
1485
include_once($path . '../' . MGR_DIR . '/includes/document.parser.class.inc.php');
1486
$modx = new DocumentParser;
1487
$modx->db->connect();
1488
// always empty cache after install
1489
$sync = new EvolutionCMS\Cache();
1490
$sync->setCachepath($path . "../assets/cache/");
1491
$sync->setReport(false);
1492
$sync->emptyCache(); // first empty the cache
1493
1494
// try to chmod the cache go-rwx (for suexeced php)
1495
$chmodSuccess = @chmod($path . '../assets/cache/siteCache.idx.php', 0600);
1496
$chmodSuccess = @chmod($path . '../assets/cache/sitePublishing.idx.php', 0600);
1497
1498
// remove any locks on the manager functions so initial manager login is not blocked
1499
mysqli_query($conn, "TRUNCATE TABLE `" . $table_prefix . "active_users`");
1500
1501
// close db connection
1502
$sqlParser->close();
1503
1504
// andrazk 20070416 - release manager access
1505 View Code Duplication
if (file_exists($path . '../assets/cache/installProc.inc.php')) {
1506
    @chmod($path . '../assets/cache/installProc.inc.php', 0755);
1507
    unlink($path . '../assets/cache/installProc.inc.php');
1508
}
1509
1510
// setup completed!
1511
echo PHP_EOL . $_lang['installation_successful'] . PHP_EOL . PHP_EOL;
1512
//echo "<p>" . $_lang['to_log_into_content_manager'] . "</p>";
1513
if ($installMode == 0) {
1514
    echo strip_tags($_lang['installation_note']) . PHP_EOL;
1515
} else {
1516
    echo strip_tags($_lang['upgrade_note']) . PHP_EOL;
1517
}
1518
1519
1520
if (empty($args)) {
1521
    echo PHP_EOL . 'Remove install folder?' . PHP_EOL;
1522
    $removeInstall = readline("Type 'y' or 'n' to continue: ");
1523
}
1524
//remove installFolder
1525
if ($removeInstall === 'y') {
1526
    removeFolder($path);
1527
    removeFolder($base_path . '.tx');
1528
    unlink($base_path . 'README.md');
1529
    echo 'Install folder deleted!' . PHP_EOL . PHP_EOL;
1530
}
1531