Completed
Push — develop ( 4f7877...1baf28 )
by Dmytro
05:50
created

cli-install.php ➔ parseProperties()   B

Complexity

Conditions 26
Paths 14

Size

Total Lines 19
Code Lines 41

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 26
eloc 41
nc 14
nop 1
dl 19
loc 19
rs 7.0696
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * EVO Cli Installer
4
 */
5
echo 'Install Evolution CMS?'.PHP_EOL;
6
$installYes = readline("Type 'y' to continue: ");
7
if ($installYes != 'y') return;
8
9
10
$autoloader = realpath(__DIR__.'/../vendor/autoload.php');
11
if (file_exists($autoloader) && is_readable($autoloader)) {
12
    include_once($autoloader);
13
}
14
15
$self = 'install/index.php';
16
$base_path = str_replace($self,'',str_replace('\\','/', __FILE__));
17
define('MODX_API_MODE', true);
18
define('MODX_BASE_PATH', $base_path);
19
define('MODX_SITE_URL', '/');
20
21
require_once("functions.php");
22
23
// set error reporting
24
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
25
26
if (is_file("../assets/cache/siteManager.php")) {
27
	include_once("../assets/cache/siteManager.php");
28
}
29
if(!defined('MGR_DIR') && is_dir("../manager")) {
30
	define('MGR_DIR', 'manager');
31
}
32
33
require_once("lang.php");
34
require_once('../'.MGR_DIR.'/includes/version.inc.php');
35
36
$moduleName = "EVO";
37
$moduleVersion = $modx_branch.' '.$modx_version;
38
$moduleRelease = $modx_release_date;
39
$moduleSQLBaseFile = "setup.sql";
40
$moduleSQLDataFile = "setup.data.sql";
41
$moduleSQLResetFile = "setup.data.reset.sql";
42
43
$moduleChunks = array (); // chunks - array : name, description, type - 0:file or 1:content, file or content
44
$moduleTemplates = array (); // templates - array : name, description, type - 0:file or 1:content, file or content
45
$moduleSnippets = array (); // snippets - array : name, description, type - 0:file or 1:content, file or content,properties
46
$modulePlugins = array (); // plugins - array : name, description, type - 0:file or 1:content, file or content,properties, events,guid
47
$moduleModules = array (); // modules - array : name, description, type - 0:file or 1:content, file or content,properties, guid
48
$moduleTemplates = array (); // templates - array : name, description, type - 0:file or 1:content, file or content,properties
49
$moduleTVs = array (); // template variables - array : name, description, type - 0:file or 1:content, file or content,properties
50
$moduleDependencies = array(); // module depedencies - array : module, table, column, type, name
51
$errors= 0;
52
53
54
55
$tableprefixauto = base_convert(rand(10, 20), 10, 36).substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), rand(0, 33), 3).'_';
56
57
58
//set param manual
59
$installMode= 0;
60
$installData = 0;
61
62
63
$databasehost = readline($_lang['connection_screen_database_host']. ' [localhost] ');
64
if ($databasehost == '') { $databasehost= 'localhost'; } 
65
66
$databaseloginname = readline($_lang['connection_screen_database_login']. ' ');
67
68
$databaseloginpassword = readline($_lang['connection_screen_database_pass']. ' ');
69
70
$database_name = readline($_lang['connection_screen_database_name']. ' ');
71
72
$tableprefix = readline($_lang['connection_screen_table_prefix']. ' ['.$tableprefixauto.'] ');
73
if ($tableprefix == ''){ $tableprefix = $tableprefixauto; }
74
75
$database_connection_method = readline($_lang['connection_screen_connection_method']. ' [SET CHARACTER SET] ');
76
if ($database_connection_method == '') { $database_connection_method = 'SET CHARACTER SET'; } 
77
78
$database_collation = readline($_lang['connection_screen_collation']. ' [utf8_general_ci] ');
79
if ($database_collation == '') { $database_collation = 'utf8_general_ci'; } 
80
81
$cmsadmin = readline($_lang['connection_screen_default_admin_login']. ' [admin] ');
82
if ($cmsadmin == ''){ $cmsadmin = 'admin'; }
83
84
$cmsadminemail = readline($_lang['connection_screen_default_admin_email']. ' ');
85
86
$cmspassword = readline($_lang['connection_screen_default_admin_password']. ' ');
87
88
$managerlanguage = readline('Мanager language:' . ' [english] ');
89
if ($managerlanguage == '') { $managerlanguage = 'english'; } 
90
91
$installData = readline('Instal demo-site (y/n):' . ' [n] ');
92
if ($installData == 'y') { $installData = 1;}
93
//cms login 
94
//////
95
96
//getLangs($install_language);
97
//////
98
99
# load setup information file
100
//include('setup.info.php');
101
//////////////////////////////////////////////////////////////////////////////////////
102 View Code Duplication
if( ! function_exists('f_owc')){
103
    /**
104
     * @param $path
105
     * @param $data
106
     * @param null|int $mode
107
     */
108
    function f_owc($path, $data, $mode = null){
0 ignored issues
show
Best Practice introduced by
The function f_owc() has been defined more than once; this definition is ignored, only the first definition in install/actions/action_summary.php (L8-20) is considered.

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

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

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

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
109
        try {
110
            // make an attempt to create the file
111
            $hnd = fopen($path, 'w');
112
            fwrite($hnd, $data);
113
            fclose($hnd);
114
115
            if(null !== $mode) chmod($path, $mode);
116
        }catch(Exception $e){
117
            // Nothing, this is NOT normal
118
            unset($e);
119
        }
120
    }
121
}
122
123
// check PHP version
124
define('PHP_MIN_VERSION', '5.4.0');
125
$phpMinVersion = PHP_MIN_VERSION; // Maybe not necessary. For backward compatibility
126
echo PHP_EOL . $_lang['checking_php_version'];
127
// -1 if left is less, 0 if equal, +1 if left is higher
128
if (version_compare(phpversion(), PHP_MIN_VERSION) < 0) {
129
    $errors++;
130
    $tmp = $_lang['you_running_php'] . phpversion() . str_replace('[+min_version+]', PHP_MIN_VERSION, $_lang["modx_requires_php"]);
131
    echo $_lang['failed'] . ' ' . $tmp . PHP_EOL;
132
} else {
133
    echo $_lang['ok'] . PHP_EOL;
134
}
135
136
// check directories
137
// cache exists?
138
echo strip_tags($_lang['checking_if_cache_exist']);
139
if (!file_exists("../assets/cache") || !file_exists("../assets/cache/rss")) {
140
    echo $_lang['failed'] . PHP_EOL;
141
    $errors++;
142
} else {
143
    echo $_lang['ok'] . PHP_EOL;
144
}
145
146
147
// cache writable?
148
echo strip_tags($_lang['checking_if_cache_writable']);
149 View Code Duplication
if (!is_writable("../assets/cache")) {
150
    $errors++;
151
    echo $_lang['failed'] . PHP_EOL;
152
} else {
153
    echo $_lang['ok'] . PHP_EOL;
154
}
155
156
157
// cache files writable?
158
echo strip_tags($_lang['checking_if_cache_file_writable']);
159
$tmp = "../assets/cache/siteCache.idx.php";
160
if ( ! file_exists($tmp)) {
161
    f_owc($tmp, "<?php //EVO site cache file ?>");
162
}
163 View Code Duplication
if ( ! is_writable($tmp)) {
164
    $errors++;
165
    echo $_lang['failed'] . PHP_EOL;
166
} else {
167
    echo $_lang['ok'] . PHP_EOL;
168
}
169
170
171
echo strip_tags($_lang['checking_if_cache_file2_writable']);
172 View Code Duplication
if ( ! is_writable("../assets/cache/sitePublishing.idx.php")) {
173
    $errors++;
174
    echo $_lang['failed'] . PHP_EOL;
175
} else {
176
    echo $_lang['ok'] . PHP_EOL;
177
}
178
179
180
// File Browser directories exists?
181
echo strip_tags($_lang['checking_if_images_exist']);
182 View Code Duplication
switch(true){
183
    case !file_exists("../assets/images"):
184
    case !file_exists("../assets/files"):
185
    case !file_exists("../assets/backup"):
186
    //case !file_exists("../assets/.thumbs"):
187
        $errors++;
188
        echo $_lang['failed'] . PHP_EOL;
189
        break;
190
    default:
191
        echo $_lang['ok'] . PHP_EOL;
192
}
193
194
195
// File Browser directories writable?
196
echo strip_tags($_lang['checking_if_images_writable']);
197 View Code Duplication
switch(true){
198
    case !is_writable("../assets/images"):
199
    case !is_writable("../assets/files"):
200
    case !is_writable("../assets/backup"):
201
    //case !is_writable("../assets/.thumbs"):
202
        $errors++;
203
        echo $_lang['failed'] . PHP_EOL;
204
        break;
205
    default:
206
        echo $_lang['ok'] . PHP_EOL;
207
}
208
209
210
// export exists?
211
echo strip_tags($_lang['checking_if_export_exists']);
212 View Code Duplication
if (!file_exists("../assets/export")) {
213
    echo $_lang['failed'] . PHP_EOL;
214
    $errors++;
215
} else {
216
    echo $_lang['ok'] . PHP_EOL;
217
}
218
219
220
// export writable?
221
echo strip_tags($_lang['checking_if_export_writable']);
222 View Code Duplication
if (!is_writable("../assets/export")) {
223
    echo $_lang['failed'] . PHP_EOL;
224
    $errors++;
225
} else {
226
    echo $_lang['ok'] . PHP_EOL;
227
}
228
229
230
// config.inc.php writable?
231
echo strip_tags($_lang['checking_if_config_exist_and_writable']);
232
$tmp = "../".MGR_DIR."/includes/config.inc.php";
233 View Code Duplication
if (!is_file($tmp)) {
234
    f_owc($tmp, "<?php //EVO configuration file ?>", 0666);
235
} else {
236
    @chmod($tmp, 0666);
237
}
238
$isWriteable = is_writable($tmp);
239 View Code Duplication
if (!$isWriteable) {
240
    $errors++;
241
    echo $_lang['failed'] . PHP_EOL;
242
} else {
243
    echo $_lang['ok'] . PHP_EOL;
244
}
245
246
247
// connect to the database
248
if ($installMode == 1) {
249
    include "../".MGR_DIR."/includes/config.inc.php";
250
} else {
251
    // get db info from post
252
    $database_server = $databasehost;
253
    $database_user = $databaseloginname;
254
    $database_password = $databaseloginpassword;
255
    $database_collation = $database_collation;
256
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_') - 1);
257
    $database_connection_charset = $database_collation;
258
    $database_connection_method = $database_connection_method;
259
    $dbase = '`' . $database_name . '`';
260
    $table_prefix = $tableprefix;
261
}
262
echo $_lang['creating_database_connection'];
263
if (!$conn = mysqli_connect($database_server, $database_user, $database_password)) {
264
    $errors++;
265
    echo $_lang['database_connection_failed'].PHP_EOL;
266
} else {
267
    echo $_lang['ok'].PHP_EOL;
268
}
269
270
271
// make sure we can use the database
272
if ($installMode > 0 && !mysqli_query($conn, "USE {$dbase}")) {
273
    $errors++;
274
    echo $_lang['database_use_failed'].PHP_EOL;
275
}
276
277
// check the database collation if not specified in the configuration
278 View Code Duplication
if (!isset ($database_connection_charset) || empty ($database_connection_charset)) {
279
    if (!$rs = mysqli_query($conn, "show session variables like 'collation_database'")) {
280
        $rs = mysqli_query($conn, "show session variables like 'collation_server'");
281
    }
282
    if ($rs && $collation = mysqli_fetch_row($rs)) {
283
        $database_collation = $collation[1];
284
    }
285
    if (empty ($database_collation)) {
286
        $database_collation = 'utf8_unicode_ci';
287
    }
288
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_') - 1);
289
    $database_connection_charset = $database_charset;
290
}
291
292
// determine the database connection method if not specified in the configuration
293
if (!isset($database_connection_method) || empty($database_connection_method)) {
294
    $database_connection_method = 'SET CHARACTER SET';
295
}
296
297
// check table prefix
298
if ($conn && $installMode == 0) {
299
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
300 View Code Duplication
    if ($rs= mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
301
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
302
        $errors++;
303
304
    } else {
305
        echo $_lang['ok'] . PHP_EOL;
306
    }
307
} elseif ($conn && $installMode == 2) {
308
    echo $_lang['checking_table_prefix'] . $table_prefix . '`: ';
309 View Code Duplication
    if (!$rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
310
        echo $_lang['failed'] . ' ' . $_lang['table_prefix_not_exist'] . PHP_EOL;
311
        $errors++;
312
313
  } else {
314
        echo $_lang['ok'] . PHP_EOL;
315
  }
316
}
317
318
// check mysql version
319
if ($conn) {
320
    echo $_lang['checking_mysql_version'];
321
    if ( version_compare(mysqli_get_server_info($conn), '5.0.51', '=') ) {
322
        echo $_lang['warning'] . ' ' . $_lang['mysql_5051'] . PHP_EOL;
323
        echo $_lang['mysql_5051_warning'] . PHP_EOL;
324 View Code Duplication
    } else {
325
        echo $_lang['ok'] . ' ' . $_lang['mysql_version_is'] . mysqli_get_server_info($conn) . PHP_EOL;
326
    }
327
}
328
329
// check for strict mode
330
if ($conn) {
331
    echo $_lang['checking_mysql_strict_mode'];
332
    $mysqlmode = mysqli_query($conn, "SELECT @@global.sql_mode");
333
    if (mysqli_num_rows($mysqlmode) > 0){
334
        $modes = mysqli_fetch_array($mysqlmode, MYSQLI_NUM);
335
        //$modes = array("STRICT_TRANS_TABLES"); // for testing
336
        // print_r($modes);
337
        foreach ($modes as $mode) {
338
            if (stristr($mode, "STRICT_TRANS_TABLES") !== false || stristr($mode, "STRICT_ALL_TABLES") !== false) {
339
                echo $_lang['warning'] . ' ' . $_lang['strict_mode'] . PHP_EOL;
340
                echo $_lang['strict_mode_error'] . PHP_EOL;
341
            } else {
342
                echo $_lang['ok'] . PHP_EOL;
343
            }
344
        }
345
    } else {
346
        echo $_lang['ok'] . PHP_EOL;
347
    }
348
}
349
// Version and strict mode check end
350
351
// andrazk 20070416 - add install flag and disable manager login
352
// assets/cache writable?
353 View Code Duplication
if (is_writable("../assets/cache")) {
354
    if (file_exists('../assets/cache/installProc.inc.php')) {
355
        @chmod('../assets/cache/installProc.inc.php', 0755);
356
        unlink('../assets/cache/installProc.inc.php');
357
    }
358
359
    f_owc("../assets/cache/installProc.inc.php", '<?php $installStartTime = '.time().'; ?>');
360
}
361
362 View Code Duplication
if($installMode > 0 && $_POST['installdata'] == "1") {
363
    echo $_lang['sample_web_site'] . ': ' . $_lang['sample_web_site_note'] . PHP_EOL;
364
}
365
366
if ($errors > 0) {
367
    echo $_lang['setup_cannot_continue'] . ' ';
368
369 View Code Duplication
    if($errors > 1){
370
        echo $errors . " " . $_lang['errors'] . $_lang['please_correct_errors'] . $_lang['and_try_again_plural'];
371
    }else{
372
        echo $_lang['error'] . $_lang['please_correct_error'] . $_lang['and_try_again']. PHP_EOL;
373
    }
374
375
    die();
376
}
377
378
379
380
//////////////////////////////////////////////////////////////////////////////////////
381
382 View Code Duplication
if (file_exists(dirname(__FILE__)."/../assets/cache/siteManager.php")) {
383
    include_once(dirname(__FILE__)."/../assets/cache/siteManager.php");
384
}else{
385
    define('MGR_DIR', 'manager');
386
}
387
388
389
$create = false;
390
391
// set timout limit
392
@ set_time_limit(120); // used @ to prevent warning when using safe mode?
393
394
//echo $_lang['setup_database'].PHP_EOL;
395
396
397
398
if ($installMode == 1) {
399
	include "../".MGR_DIR."/includes/config.inc.php";
400
} else {
401
    // get db info from post
402
    $database_server = $databasehost;
403
    $database_user = $databaseloginname;
404
    $database_password = $databaseloginpassword;
405
    $database_collation = $database_collation;
406
    $database_charset = substr($database_collation, 0, strpos($database_collation, '_'));
407
    $database_connection_charset = $database_charset;
408
    $database_connection_method = $database_connection_method;
409
    $dbase = "`" .$database_name. "`";
410
    $table_prefix = $tableprefix;
411
    $adminname = $cmsadmin;
412
    $adminemail = $cmsadminemail;
413
    $adminpass = $cmspassword;
414
    $managerlanguage = $managerlanguage;
415
    $custom_placeholders = array();
416
}
417
418
// set session name variable
419
if (!isset ($site_sessionname)) {
420
    $site_sessionname = 'SN' . uniqid('');
421
}
422
423
// get base path and url
424
$a = explode("install", str_replace("\\", "/", dirname($_SERVER["PHP_SELF"])));
425
if (count($a) > 1)
426
    array_pop($a);
427
$url = implode("install", $a);
428
reset($a);
429
$a = explode("install", str_replace("\\", "/", realpath(dirname(__FILE__))));
430
if (count($a) > 1)
431
    array_pop($a);
432
$pth = implode("install", $a);
433
unset ($a);
434
$base_url = $url . (substr($url, -1) != "/" ? "/" : "");
435
$base_path = $pth . (substr($pth, -1) != "/" ? "/" : "");
436
437
// connect to the database
438
echo $_lang['setup_database_create_connection'].': ';
439
if (!$conn = mysqli_connect($database_server, $database_user, $database_password)) {
440
    echo $_lang["setup_database_create_connection_failed"]." ".$_lang['setup_database_create_connection_failed_note'].PHP_EOL;
441
    return;
442
} else {
443
    echo $_lang['ok'].PHP_EOL;
444
}
445
446
// select database
447
echo $_lang['setup_database_selection']. str_replace("`", "", $dbase) . "`: ";
448
if (!mysqli_select_db($conn, str_replace("`", "", $dbase))) {
449
    echo $_lang['setup_database_selection_failed']." ".$_lang['setup_database_selection_failed_note'].PHP_EOL;
450
    $create = true;
451 View Code Duplication
} else {
452
	if (function_exists('mysqli_set_charset')) mysqli_set_charset($conn, $database_charset);
453
    mysqli_query($conn, "{$database_connection_method} {$database_connection_charset}");
454
    echo $_lang['ok'].PHP_EOL;
455
}
456
457
// try to create the database
458
if ($create) {
459
    echo $_lang['setup_database_creation']. str_replace("`", "", $dbase) . "`: ";
460
    //	if(!@mysqli_create_db(str_replace("`","",$dbase), $conn)) {
461
    if (! mysqli_query($conn, "CREATE DATABASE $dbase DEFAULT CHARACTER SET $database_charset COLLATE $database_collation")) {
462
        echo $_lang['setup_database_creation_failed']." ".$_lang['setup_database_creation_failed_note'].PHP_EOL;
463
        $errors += 1;
464
        
465
        echo 'database charset: ' . $database_charset . PHP_EOL;
466
        echo 'database collation: ' . $database_collation . PHP_EOL;
467
468
        echo $_lang['setup_database_creation_failed_note2'] . PHP_EOL;
469
470
        die();
471
472
    } else {
473
        echo $_lang['ok'].PHP_EOL;
474
    }
475
}
476
477
// check table prefix
478
if ($installMode == 0) {
479
    echo $_lang['checking_table_prefix'] . $table_prefix . "`: ";
480
    if (@ $rs = mysqli_query($conn, "SELECT COUNT(*) FROM $dbase.`" . $table_prefix . "site_content`")) {
481
        echo $_lang['failed'] . " " . $_lang['table_prefix_already_inuse'] . PHP_EOL;
482
        $errors += 1;
483
        echo $_lang['table_prefix_already_inuse_note'] . PHP_EOL;
484
        return;
485
    } else {
486
        echo $_lang['ok'].PHP_EOL;
487
    }
488
}
489
490 View Code Duplication
if(!function_exists('parseProperties')) {
491
    /**
492
     * parses a resource property string and returns the result as an array
493
     * duplicate of method in documentParser class
494
     *
495
     * @param string $propertyString
496
     * @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...
497
     */
498
    function parseProperties($propertyString) {
499
        $parameter= array ();
500
        if (!empty ($propertyString)) {
501
            $tmpParams= explode("&", $propertyString);
502
            $countParams = count($tmpParams);
503
            for ($x= 0; $x < $countParams; $x++) {
504
                if (strpos($tmpParams[$x], '=', 0)) {
505
                    $pTmp= explode("=", $tmpParams[$x]);
506
                    $pvTmp= explode(";", trim($pTmp[1]));
507
                    if ($pvTmp[1] == 'list' && $pvTmp[3] != "")
508
                        $parameter[trim($pTmp[0])]= $pvTmp[3]; //list default
509
                    else
510
                        if ($pvTmp[1] != 'list' && $pvTmp[2] != "")
511
                            $parameter[trim($pTmp[0])]= $pvTmp[2];
512
                }
513
            }
514
        }
515
        return $parameter;
516
    }
517
}
518
519
// check status of Inherit Parent Template plugin
520
$auto_template_logic = 'parent';
521 View Code Duplication
if ($installMode != 0) {
522
    $rs = mysqli_query($conn, "SELECT properties, disabled FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='Inherit Parent Template'");
523
    $row = mysqli_fetch_row($rs);
524
    if(!$row) {
525
        // not installed
526
        $auto_template_logic = 'system';
527
    } else {
528
        if($row[1] == 1) {
529
            // installed but disabled
530
            $auto_template_logic = 'system';
531
        } else {
532
            // installed, enabled .. see how it's configured
533
            $properties = parseProperties($row[0]);
534
            if(isset($properties['inheritTemplate'])) {
535
                if($properties['inheritTemplate'] == 'From First Sibling') {
536
                    $auto_template_logic = 'sibling';
537
                }
538
            }
539
        }
540
    }
541
}
542
543
544
545
546
// open db connection
547
$setupPath = realpath(dirname(__FILE__));
548
$chunkPath    = 'assets/chunks';
549
$snippetPath  = 'assets/snippets';
550
$pluginPath   = 'assets/plugins';
551
$modulePath   = 'assets/modules';
552
$templatePath = 'assets/templates';
553
$tvPath       = 'assets/tvs';
554
555
// setup Template template files - array : name, description, type - 0:file or 1:content, parameters, category
556
$mt = &$moduleTemplates;
557 View Code Duplication
if(is_dir($templatePath) && is_readable($templatePath)) {
558
    $d = dir($templatePath);
559
    while (false !== ($tplfile = $d->read()))
560
    {
561
        if(substr($tplfile, -4) != '.tpl') continue;
562
        $params = parse_docblock($templatePath, $tplfile);
563
        if(is_array($params) && (count($params)>0))
564
        {
565
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
566
            $mt[] = array
567
            (
568
                $params['name'],
569
                $description,
570
                // Don't think this is gonna be used ... but adding it just in case 'type'
571
                $params['type'],
572
                "$templatePath/{$params['filename']}",
573
                $params['modx_category'],
574
                $params['lock_template'],
575
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
576
                isset($params['save_sql_id_as']) ? $params['save_sql_id_as'] : NULL // Nessecary to fix template-ID for demo-site
577
            );
578
        }
579
    }
580
    $d->close();
581
}
582
583
// setup Template Variable template files
584
$mtv = &$moduleTVs;
585 View Code Duplication
if(is_dir($tvPath) && is_readable($tvPath)) {
586
    $d = dir($tvPath);
587
    while (false !== ($tplfile = $d->read())) {
588
        if(substr($tplfile, -4) != '.tpl') continue;
589
        $params = parse_docblock($tvPath, $tplfile);
590
        if(is_array($params) && (count($params)>0)) {
591
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
592
            $mtv[] = array(
593
                $params['name'],
594
                $params['caption'],
595
                $description,
596
                $params['input_type'],
597
                $params['input_options'],
598
                $params['input_default'],
599
                $params['output_widget'],
600
                $params['output_widget_params'],
601
                "$templatePath/{$params['filename']}", /* not currently used */
602
                $params['template_assignments']!="*"?$params['template_assignments']:implode(",",array_map(create_function('$v','return $v[0];'),$mt)), /* comma-separated list of template names */
603
                $params['modx_category'],
604
                $params['lock_tv'],  /* value should be 1 or 0 */
605
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
606
            );
607
        }
608
    }
609
    $d->close();
610
}
611
612
// setup chunks template files - array : name, description, type - 0:file or 1:content, file or content
613
$mc = &$moduleChunks;
614 View Code Duplication
if(is_dir($chunkPath) && is_readable($chunkPath)) {
615
    $d = dir($chunkPath);
616
    while (false !== ($tplfile = $d->read())) {
617
        if(substr($tplfile, -4) != '.tpl') {
618
            continue;
619
        }
620
        $params = parse_docblock($chunkPath, $tplfile);
621
        if(is_array($params) && count($params) > 0) {
622
            $mc[] = array(
623
                $params['name'],
624
                $params['description'],
625
                "$chunkPath/{$params['filename']}",
626
                $params['modx_category'],
627
                array_key_exists('overwrite', $params) ? $params['overwrite'] : 'true',
628
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
629
            );
630
        }
631
    }
632
    $d->close();
633
}
634
635
// setup snippets template files - array : name, description, type - 0:file or 1:content, file or content,properties
636
$ms = &$moduleSnippets;
637 View Code Duplication
if(is_dir($snippetPath) && is_readable($snippetPath)) {
638
    $d = dir($snippetPath);
639
    while (false !== ($tplfile = $d->read())) {
640
        if(substr($tplfile, -4) != '.tpl') {
641
            continue;
642
        }
643
        $params = parse_docblock($snippetPath, $tplfile);
644
        if(is_array($params) && count($params) > 0) {
645
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
646
            $ms[] = array(
647
                $params['name'],
648
                $description,
649
                "$snippetPath/{$params['filename']}",
650
                $params['properties'],
651
                $params['modx_category'],
652
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
653
            );
654
        }
655
    }
656
    $d->close();
657
}
658
659
// setup plugins template files - array : name, description, type - 0:file or 1:content, file or content,properties
660
$mp = &$modulePlugins;
661 View Code Duplication
if(is_dir($pluginPath) && is_readable($pluginPath)) {
662
    $d = dir($pluginPath);
663
    while (false !== ($tplfile = $d->read())) {
664
        if(substr($tplfile, -4) != '.tpl') {
665
            continue;
666
        }
667
        $params = parse_docblock($pluginPath, $tplfile);
668
        if(is_array($params) && count($params) > 0) {
669
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
670
            $mp[] = array(
671
                $params['name'],
672
                $description,
673
                "$pluginPath/{$params['filename']}",
674
                $params['properties'],
675
                $params['events'],
676
                $params['guid'],
677
                $params['modx_category'],
678
                $params['legacy_names'],
679
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false,
680
                (int)$params['disabled']
681
            );
682
        }
683
    }
684
    $d->close();
685
}
686
687
// setup modules - array : name, description, type - 0:file or 1:content, file or content,properties, guid,enable_sharedparams
688
$mm = &$moduleModules;
689
$mdp = &$moduleDependencies;
690 View Code Duplication
if(is_dir($modulePath) && is_readable($modulePath)) {
691
    $d = dir($modulePath);
692
    while (false !== ($tplfile = $d->read())) {
693
        if(substr($tplfile, -4) != '.tpl') {
694
            continue;
695
        }
696
        $params = parse_docblock($modulePath, $tplfile);
697
        if(is_array($params) && count($params) > 0) {
698
            $description = empty($params['version']) ? $params['description'] : "<strong>{$params['version']}</strong> {$params['description']}";
699
            $mm[] = array(
700
                $params['name'],
701
                $description,
702
                "$modulePath/{$params['filename']}",
703
                $params['properties'],
704
                $params['guid'],
705
                (int)$params['shareparams'],
706
                $params['modx_category'],
707
                array_key_exists('installset', $params) ? preg_split("/\s*,\s*/", $params['installset']) : false
708
            );
709
        }
710
        if ((int)$params['shareparams'] || !empty($params['dependencies'])) {
711
            $dependencies = explode(',', $params['dependencies']);
712
            foreach ($dependencies as $dependency) {
713
                $dependency = explode(':', $dependency);
714
                switch (trim($dependency[0])) {
715
                    case 'template':
716
                        $mdp[] = array(
717
                            'module' => $params['name'],
718
                            'table' => 'templates',
719
                            'column' => 'templatename',
720
                            'type' => 50,
721
                            'name' => trim($dependency[1])
722
                        );
723
                        break;
724
                    case 'tv':
725
                    case 'tmplvar':
726
                        $mdp[] = array(
727
                            'module' => $params['name'],
728
                            'table' => 'tmplvars',
729
                            'column' => 'name',
730
                            'type' => 60,
731
                            'name' => trim($dependency[1])
732
                        );
733
                        break;
734
                    case 'chunk':
735
                    case 'htmlsnippet':
736
                        $mdp[] = array(
737
                            'module' => $params['name'],
738
                            'table' => 'htmlsnippets',
739
                            'column' => 'name',
740
                            'type' => 10,
741
                            'name' => trim($dependency[1])
742
                        );
743
                        break;
744
                    case 'snippet':
745
                        $mdp[] = array(
746
                            'module' => $params['name'],
747
                            'table' => 'snippets',
748
                            'column' => 'name',
749
                            'type' => 40,
750
                            'name' => trim($dependency[1])
751
                        );
752
                        break;
753
                    case 'plugin':
754
                        $mdp[] = array(
755
                            'module' => $params['name'],
756
                            'table' => 'plugins',
757
                            'column' => 'name',
758
                            'type' => 30,
759
                            'name' => trim($dependency[1])
760
                        );
761
                        break;
762
                    case 'resource':
763
                        $mdp[] = array(
764
                            'module' => $params['name'],
765
                            'table' => 'content',
766
                            'column' => 'pagetitle',
767
                            'type' => 20,
768
                            'name' => trim($dependency[1])
769
                        );
770
                        break;
771
                }
772
            }
773
        }
774
    }
775
    $d->close();
776
}
777
778
// setup callback function
779
$callBackFnc = "clean_up";
780
781 View Code Duplication
function clean_up($sqlParser) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
782
    $ids = array();
783
784
    // secure web documents - privateweb
785
    mysqli_query($sqlParser->conn,"UPDATE `".$sqlParser->prefix."site_content` SET privateweb = 0 WHERE privateweb = 1");
786
    $sql =  "SELECT DISTINCT sc.id
787
             FROM `".$sqlParser->prefix."site_content` sc
788
             LEFT JOIN `".$sqlParser->prefix."document_groups` dg ON dg.document = sc.id
789
             LEFT JOIN `".$sqlParser->prefix."webgroup_access` wga ON wga.documentgroup = dg.document_group
790
             WHERE wga.id>0";
791
    $ds = mysqli_query($sqlParser->conn,$sql);
792
    if(!$ds) {
793
        echo "An error occurred while executing a query: ".mysqli_error($sqlParser->conn);
794
    }
795
    else {
796
        while($r = mysqli_fetch_assoc($ds)) $ids[]=$r["id"];
797
        if(count($ids)>0) {
798
            mysqli_query($sqlParser->conn,"UPDATE `".$sqlParser->prefix."site_content` SET privateweb = 1 WHERE id IN (".implode(", ",$ids).")");
799
            unset($ids);
800
        }
801
    }
802
803
    // secure manager documents privatemgr
804
    mysqli_query($sqlParser->conn,"UPDATE `".$sqlParser->prefix."site_content` SET privatemgr = 0 WHERE privatemgr = 1");
805
    $sql =  "SELECT DISTINCT sc.id
806
             FROM `".$sqlParser->prefix."site_content` sc
807
             LEFT JOIN `".$sqlParser->prefix."document_groups` dg ON dg.document = sc.id
808
             LEFT JOIN `".$sqlParser->prefix."membergroup_access` mga ON mga.documentgroup = dg.document_group
809
             WHERE mga.id>0";
810
    $ds = mysqli_query($sqlParser->conn,$sql);
811
    if(!$ds) {
812
        echo "An error occurred while executing a query: ".mysqli_error($sqlParser->conn);
813
    }
814
    else {
815
        while($r = mysqli_fetch_assoc($ds)) $ids[]=$r["id"];
816
        if(count($ids)>0) {
817
            mysqli_query($sqlParser->conn,"UPDATE `".$sqlParser->prefix."site_content` SET privatemgr = 1 WHERE id IN (".implode(", ",$ids).")");
818
            unset($ids);
819
        }
820
    }
821
}
822
823 View Code Duplication
function parse_docblock($element_dir, $filename) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
824
    $params = array();
825
    $fullpath = $element_dir . '/' . $filename;
826
    if(is_readable($fullpath)) {
827
        $tpl = @fopen($fullpath, "r");
828
        if($tpl) {
829
            $params['filename'] = $filename;
830
            $docblock_start_found = false;
831
            $name_found = false;
832
            $description_found = false;
833
834
            while(!feof($tpl)) {
835
                $line = fgets($tpl);
836
                if(!$docblock_start_found) {
837
                    // find docblock start
838
                    if(strpos($line, '/**') !== false) {
839
                        $docblock_start_found = true;
840
                    }
841
                    continue;
842
                } elseif(!$name_found) {
843
                    // find name
844
                    $ma = null;
845
                    if(preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
846
                        $params['name'] = trim($ma[1]);
847
                        $name_found = !empty($params['name']);
848
                    }
849
                    continue;
850
                } elseif(!$description_found) {
851
                    // find description
852
                    $ma = null;
853
                    if(preg_match("/^\s+\*\s+(.+)/", $line, $ma)) {
854
                        $params['description'] = trim($ma[1]);
855
                        $description_found = !empty($params['description']);
856
                    }
857
                    continue;
858
                } else {
859
                    $ma = null;
860
                    if(preg_match("/^\s+\*\s+\@([^\s]+)\s+(.+)/", $line, $ma)) {
861
                        $param = trim($ma[1]);
862
                        $val = trim($ma[2]);
863
                        if(!empty($param) && !empty($val)) {
864
                            if($param == 'internal') {
865
                                $ma = null;
866
                                if(preg_match("/\@([^\s]+)\s+(.+)/", $val, $ma)) {
867
                                    $param = trim($ma[1]);
868
                                    $val = trim($ma[2]);
869
                                }
870
                                //if($val !== '0' && (empty($param) || empty($val))) {
871
                                if(empty($param)) {
872
                                    continue;
873
                                }
874
                            }
875
                            $params[$param] = $val;
876
                        }
877
                    } elseif(preg_match("/^\s*\*\/\s*$/", $line)) {
878
                        break;
879
                    }
880
                }
881
            }
882
            @fclose($tpl);
883
        }
884
    }
885
    return $params;
886
}
887
888
889
include "{$setupPath}/sqlParser.class.php";
890
$sqlParser = new SqlParser($database_server, $database_user, $database_password, str_replace("`", "", $dbase), $table_prefix, $adminname, $adminemail, $adminpass, $database_connection_charset, $managerlanguage, $database_connection_method, $auto_template_logic);
891
$sqlParser->mode = ($installMode < 1) ? "new" : "upd";
892
/* image and file manager paths now handled via settings screen in Manager
893
$sqlParser->imageUrl = 'http://' . $_SERVER['SERVER_NAME'] . $base_url . "assets/";
894
$sqlParser->imageUrl = "assets/";
895
$sqlParser->imagePath = $base_path . "assets/";
896
$sqlParser->fileManagerPath = $base_path;
897
*/
898
$sqlParser->ignoreDuplicateErrors = true;
899
$sqlParser->connect();
900
901
// install/update database
902
echo $_lang['setup_database_creating_tables'];
903
if ($moduleSQLBaseFile) {
904
    $sqlParser->process($moduleSQLBaseFile);
905
    // display database results
906
    if ($sqlParser->installFailed == true) {
907
        $errors += 1;
908
        echo $_lang['database_alerts'] . PHP_EOL;
909
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
910
        echo $_lang['installation_error_occured'] . PHP_EOL;
911
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
912
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
913
        }
914
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
915
        die();
916
    } else {
917
        echo $_lang['ok'].PHP_EOL;
918
    }
919
}
920
921
// custom or not
922
if (file_exists(dirname(__FILE__)."/../../assets/cache/siteManager.php")) {
923
    $mgrdir = 'include_once(dirname(__FILE__)."/../../assets/cache/siteManager.php");';
924
}else{
925
    $mgrdir = 'define(\'MGR_DIR\', \'manager\');';
926
}
927
928
// write the config.inc.php file if new installation
929
echo $_lang['writing_config_file'];
930
931
$confph = array();
932
$confph['database_server']    = $database_server;
933
$confph['user_name']          = mysqli_real_escape_string($conn, $database_user);
934
$confph['password']           = mysqli_real_escape_string($conn, $database_password);
935
$confph['connection_charset'] = $database_connection_charset;
936
$confph['connection_method']  = $database_connection_method;
937
$confph['dbase']              = str_replace('`', '', $dbase);
938
$confph['table_prefix']       = $table_prefix;
939
$confph['lastInstallTime']    = time();
940
$confph['site_sessionname']   = $site_sessionname;
941
942
$configString = file_get_contents('config.inc.tpl');
943
$configString = parse($configString, $confph);
944
945
$filename = '../'.MGR_DIR.'/includes/config.inc.php';
946
$configFileFailed = false;
947
if (@ !$handle = fopen($filename, 'w')) {
948
    $configFileFailed = true;
949
}
950
951
// write $somecontent to our opened file.
952
if (@ fwrite($handle, $configString) === FALSE) {
953
    $configFileFailed = true;
954
}
955
@ fclose($handle);
956
957
// try to chmod the config file go-rwx (for suexeced php)
958
$chmodSuccess = @chmod($filename, 0404);
959
960
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...
961
    echo $_lang['failed'] . PHP_EOL;
962
    $errors += 1;
963
964
    echo $_lang['cant_write_config_file'] . ' ' . MGR_DIR .'/includes/config.inc.php' .PHP_EOL;
965
    echo ' '.PHP_EOL;
966
    echo ' '.PHP_EOL;
967
    echo $configString;
968
    echo ' '.PHP_EOL;
969
    echo ' '.PHP_EOL;
970
    echo $_lang['cant_write_config_file_note'] . PHP_EOL;
971
    die();
972
973
} else {
974
    echo $_lang['ok'].PHP_EOL;
975
}
976
977
// generate new site_id and set manager theme to default
978 View Code Duplication
if ($installMode == 0) {
979
    $siteid = uniqid('');
980
    mysqli_query($sqlParser->conn, "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid'),('manager_theme','default')");
981
} else {
982
    // update site_id if missing
983
    $ds = mysqli_query($sqlParser->conn, "SELECT setting_name,setting_value FROM $dbase.`" . $table_prefix . "system_settings` WHERE setting_name='site_id'");
984
    if ($ds) {
985
        $r = mysqli_fetch_assoc($ds);
986
        $siteid = $r['setting_value'];
987
        if ($siteid == '' || $siteid = 'MzGeQ2faT4Dw06+U49x3') {
988
            $siteid = uniqid('');
989
            mysqli_query($sqlParser->conn, "REPLACE INTO $dbase.`" . $table_prefix . "system_settings` (setting_name,setting_value) VALUES('site_id','$siteid')");
990
        }
991
    }
992
}
993
994
// Reset database for installation of demo-site
995
if ($installData && $moduleSQLDataFile && $moduleSQLResetFile) {
996
	echo $_lang['resetting_database'];
997
	$sqlParser->process($moduleSQLResetFile);
998
	// display database results
999
	if ($sqlParser->installFailed == true) {
1000
		$errors += 1;
1001
		echo $_lang['database_alerts'] . PHP_EOL;
1002
		echo $_lang['setup_couldnt_install'] . PHP_EOL;
1003
		echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
1004
		/*
1005
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
1006
			echo "<em>" . $sqlParser->mysqlErrors[$i]["error"] . "</em>" . $_lang['during_execution_of_sql'] . "<span class='mono'>" . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . "</span>.<hr />";
1007
		}
1008
		echo "</p>";*/
1009
		echo $_lang['some_tables_not_updated'] . PHP_EOL;
1010
		die();
1011
	} else {
1012
		echo $_lang['ok'] . PHP_EOL;
1013
	}
1014
}
1015
1016
// Install Templates
1017
$moduleTemplate = $mt; 
1018
if (!empty($moduleTemplate) || $installData) {
1019
    echo PHP_EOL . $_lang['templates'] . ":" . PHP_EOL;
1020
    //$selTemplates = $_POST['template'];
1021
    foreach ($moduleTemplates as $k=>$moduleTemplate) {
1022
        $installSample = in_array('sample', $moduleTemplate[6]) && $installData == 1;
1023
        if($installSample || is_array($moduleTemplate)) {
1024
            $name = mysqli_real_escape_string($conn, $moduleTemplate[0]);
1025
            $desc = mysqli_real_escape_string($conn, $moduleTemplate[1]);
1026
            $category = mysqli_real_escape_string($conn, $moduleTemplate[4]);
1027
            $locked = mysqli_real_escape_string($conn, $moduleTemplate[5]);
1028
            $filecontent = $moduleTemplate[3];
1029
            $save_sql_id_as = $moduleTemplate[7]; // Nessecary for demo-site
1030
            if (!file_exists($filecontent)) {
1031
                echo "  $name: " . $_lang['unable_install_template'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1032
            } else {
1033
                // Create the category if it does not already exist
1034
                $category_id = getCreateDbCategory($category, $sqlParser);
1035
1036
                // Strip the first comment up top
1037
                $template = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
1038
                $template = mysqli_real_escape_string($conn, $template);
1039
1040
                // See if the template already exists
1041
                $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name'");
1042
1043
                if (mysqli_num_rows($rs)) {
1044
                    if (!mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_templates` SET content='$template', description='$desc', category=$category_id, locked='$locked'  WHERE templatename='$name' LIMIT 1;")) {
1045
                        $errors += 1;
1046
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1047
                        return;
1048
                    }
1049 View Code Duplication
                    if(!is_null($save_sql_id_as)) {
1050
                        $sql_id = @mysqli_insert_id($sqlParser->conn);
1051
                        if(!$sql_id) {
1052
                            $idQuery = mysqli_fetch_assoc(mysqli_query($sqlParser->conn, "SELECT id FROM $dbase.`" . $table_prefix . "site_templates` WHERE templatename='$name' LIMIT 1;"));
1053
                            $sql_id = $idQuery['id'];
1054
                        }
1055
                        $custom_placeholders[$save_sql_id_as] = $sql_id;
1056
                    }
1057
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1058
                } else {
1059
                    if (!@ mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_templates` (templatename,description,content,category,locked) VALUES('$name','$desc','$template',$category_id,'$locked');")) {
1060
                        $errors += 1;
1061
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1062
                        die();
1063
                    }
1064
                    if(!is_null($save_sql_id_as)) $custom_placeholders[$save_sql_id_as] = @mysqli_insert_id($sqlParser->conn);
1065
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1066
                }
1067
            }
1068
        }
1069
    }
1070
}
1071
1072
// Install Template Variables
1073
$moduleTVs = $mtv;
1074
if (is_array($moduleTVs) || $installData) {
1075
    echo PHP_EOL . $_lang['tvs'].': '.PHP_EOL;
1076
    //$selTVs = $_POST['tv'];
1077
    foreach ($moduleTVs as $k=>$moduleTV) {
1078
        $installSample = in_array('sample', $moduleTV[12]) && $installData == 1;
1079
        if($installSample || is_array($moduleTVs)) {
1080
            $name = mysqli_real_escape_string($conn, $moduleTV[0]);
1081
            $caption = mysqli_real_escape_string($conn, $moduleTV[1]);
1082
            $desc = mysqli_real_escape_string($conn, $moduleTV[2]);
1083
            $input_type = mysqli_real_escape_string($conn, $moduleTV[3]);
1084
            $input_options = mysqli_real_escape_string($conn, $moduleTV[4]);
1085
            $input_default = mysqli_real_escape_string($conn, $moduleTV[5]);
1086
            $output_widget = mysqli_real_escape_string($conn, $moduleTV[6]);
1087
            $output_widget_params = mysqli_real_escape_string($conn, $moduleTV[7]);
1088
            $filecontent = $moduleTV[8];
1089
            $assignments = $moduleTV[9];
1090
            $category = mysqli_real_escape_string($conn, $moduleTV[10]);
1091
            $locked = mysqli_real_escape_string($conn, $moduleTV[11]);
1092
1093
1094
            // Create the category if it does not already exist
1095
            $category = getCreateDbCategory($category, $sqlParser);
1096
1097
            $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_tmplvars` WHERE name='$name'");
1098
            if (mysqli_num_rows($rs)) {
1099
                $insert = true;
1100 View Code Duplication
                while($row = mysqli_fetch_assoc($rs)) {
1101
                    if (!mysqli_query($sqlParser->conn, "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']};")) {
1102
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1103
                        return;
1104
                    }
1105
                    $insert = false;
1106
                }
1107
                echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1108
            } else {
1109
                $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');";
1110 View Code Duplication
                if (!mysqli_query($sqlParser->conn, $q)) {
1111
                    echo mysqli_error($sqlParser->conn) . PHP_EOL;
1112
                    return;
1113
                }
1114
                echo "  $name: " . $_lang['installed'] . PHP_EOL;
1115
            }
1116
1117
            // add template assignments
1118
            $assignments = explode(',', $assignments);
1119
1120 View Code Duplication
            if (count($assignments) > 0) {
1121
1122
                // remove existing tv -> template assignments
1123
                $ds=mysqli_query($sqlParser->conn, "SELECT id FROM $dbase.`".$table_prefix."site_tmplvars` WHERE name='$name' AND description='$desc';");
1124
                $row = mysqli_fetch_assoc($ds);
1125
                $id = $row["id"];
1126
                mysqli_query($sqlParser->conn, 'DELETE FROM ' . $dbase . '.`' . $table_prefix . 'site_tmplvar_templates` WHERE tmplvarid = \'' . $id . '\'');
1127
1128
                // add tv -> template assignments
1129
                foreach ($assignments as $assignment) {
1130
                    $template = mysqli_real_escape_string($conn, $assignment);
1131
                    $ts = mysqli_query($sqlParser->conn, "SELECT id FROM $dbase.`".$table_prefix."site_templates` WHERE templatename='$template';");
1132
                    if ($ds && $ts) {
1133
                        $tRow = mysqli_fetch_assoc($ts);
1134
                        $templateId = $tRow['id'];
1135
                        mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_tmplvar_templates` (tmplvarid, templateid) VALUES($id, $templateId)");
1136
                   }
1137
                }
1138
            }
1139
        }
1140
    }
1141
}
1142
1143
1144
$moduleChunks = $mc;
1145
// Install Chunks
1146
if (is_array ($moduleChunks) || $installData) {
1147
    echo PHP_EOL . $_lang['chunks'] . ": " . PHP_EOL;
1148
    foreach ($moduleChunks as $k=>$moduleChunk) {
1149
        $installSample = in_array('sample', $moduleChunk[5]) && $installData == 1;
1150
        $count_new_name = 0;
1151
        if($installSample || is_array ($moduleChunks)) {
1152
1153
            $name = mysqli_real_escape_string($conn, $moduleChunk[0]);
1154
            $desc = mysqli_real_escape_string($conn, $moduleChunk[1]);
1155
            $category = mysqli_real_escape_string($conn, $moduleChunk[3]);
1156
            $overwrite = mysqli_real_escape_string($conn, $moduleChunk[4]);
1157
            $filecontent = $moduleChunk[2];
1158
1159
            if (!file_exists($filecontent))
1160
                echo "  $name: " . $_lang['unable_install_chunk'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1161
            else {
1162
1163
                // Create the category if it does not already exist
1164
                $category_id = getCreateDbCategory($category, $sqlParser);
1165
1166
                $chunk = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', file_get_contents($filecontent), 1);
1167
                $chunk = mysqli_real_escape_string($conn, $chunk);
1168
                $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$name'");
1169
                $count_original_name = mysqli_num_rows($rs);
1170 View Code Duplication
                if($overwrite == 'false') {
1171
                    $newname = $name . '-' . str_replace('.', '_', $modx_version);
1172
                    $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_htmlsnippets` WHERE name='$newname'");
1173
                    $count_new_name = mysqli_num_rows($rs);
1174
                }
1175
                $update = $count_original_name > 0 && $overwrite == 'true';
1176
                if ($update) {
1177
                    if (!mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_htmlsnippets` SET snippet='$chunk', description='$desc', category=$category_id WHERE name='$name';")) {
1178
                        $errors += 1;
1179
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1180
                        return;
1181
                    }
1182
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1183
                } elseif($count_new_name == 0) {
1184
                    if($count_original_name > 0 && $overwrite == 'false') {
1185
                        $name = $newname;
1186
                    }
1187
                    if (!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_htmlsnippets` (name,description,snippet,category) VALUES('$name','$desc','$chunk',$category_id);")) {
1188
                        $errors += 1;
1189
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1190
                        return;
1191
                    }
1192
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1193
                }
1194
            }
1195
        }
1196
    }
1197
}
1198
1199
// Install Modules
1200
$moduleModules = $mm;
1201
if (is_array($moduleModules) || $installData) {
1202
    echo PHP_EOL . $_lang['modules'] . ":" . PHP_EOL;
1203
    //$selModules = $_POST['module'];
1204
    foreach ($moduleModules as $k=>$moduleModule) {
1205
        $installSample = in_array('sample', $moduleModule[7]) && $installData == 1;
1206
        if($installSample || is_array($moduleModules)) {
1207
            $name = mysqli_real_escape_string($conn, $moduleModule[0]);
1208
            $desc = mysqli_real_escape_string($conn, $moduleModule[1]);
1209
            $filecontent = $moduleModule[2];
1210
            $properties = $moduleModule[3];
1211
            $guid = mysqli_real_escape_string($conn, $moduleModule[4]);
1212
            $shared = mysqli_real_escape_string($conn, $moduleModule[5]);
1213
            $category = mysqli_real_escape_string($conn, $moduleModule[6]);
1214
            if (!file_exists($filecontent))
1215
                echo "  $name: " . $_lang['unable_install_module'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1216
            else {
1217
1218
                // Create the category if it does not already exist
1219
                $category = getCreateDbCategory($category, $sqlParser);
1220
1221
                $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...
1222
                // $module = removeDocblock($module, 'module'); // Modules have no fileBinding, keep docblock for info-tab
1223
                $module = mysqli_real_escape_string($conn, $module);
1224
                $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_modules` WHERE name='$name'");
1225
                if (mysqli_num_rows($rs)) {
1226
                    $row = mysqli_fetch_assoc($rs);
1227
                    $props = mysqli_real_escape_string($conn, propUpdate($properties,$row['properties']));
1228
                    if (!mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_modules` SET modulecode='$module', description='$desc', properties='$props', enable_sharedparams='$shared' WHERE name='$name';")) {
1229
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1230
                        return;
1231
                    }
1232
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1233
                } else {
1234
                    if ($properties != NULL ){
1235
                        $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...
1236
                    }
1237
                    if (!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_modules` (name,description,modulecode,properties,guid,enable_sharedparams,category) VALUES('$name','$desc','$module','$properties','$guid','$shared', $category);")) {
1238
                        echo "<p>" . mysqli_error($sqlParser->conn) . "</p>";
1239
                        return;
1240
                    }
1241
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1242
                }
1243
            }
1244
        }
1245
    }
1246
}
1247
1248
// Install Plugins
1249
$modulePlugins = $mp;
1250
if (is_array($modulePlugins) || $installData) {
1251
    echo PHP_EOL . $_lang['plugins'] . ":" . PHP_EOL;
1252
    $selPlugs = $_POST['plugin'];
1253
    foreach ($modulePlugins as $k=>$modulePlugin) {
1254
        //$installSample = in_array('sample', $modulePlugin[8]) && $installData == 1;
1255
        if($installSample || is_array($modulePlugins)) {
1256
            $name = mysqli_real_escape_string($conn, $modulePlugin[0]);
1257
            $desc = mysqli_real_escape_string($conn, $modulePlugin[1]);
1258
            $filecontent = $modulePlugin[2];
1259
            $properties = $modulePlugin[3];
1260
            $events = explode(",", $modulePlugin[4]);
1261
            $guid = mysqli_real_escape_string($conn, $modulePlugin[5]);
1262
            $category = mysqli_real_escape_string($conn, $modulePlugin[6]);
1263
            $leg_names = '';
1264
            $disabled = $modulePlugin[9];
1265 View Code Duplication
            if(array_key_exists(7, $modulePlugin)) {
1266
                // parse comma-separated legacy names and prepare them for sql IN clause
1267
                $leg_names = "'" . implode("','", preg_split('/\s*,\s*/', mysqli_real_escape_string($conn, $modulePlugin[7]))) . "'";
1268
            }
1269
            if (!file_exists($filecontent))
1270
                echo "  $name: " . $_lang['unable_install_plugin'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1271
            else {
1272
1273
                // disable legacy versions based on legacy_names provided
1274 View Code Duplication
                if(!empty($leg_names)) {
1275
                    $update_query = "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE name IN ($leg_names);";
1276
                    $rs = mysqli_query($sqlParser->conn, $update_query);
1277
                }
1278
1279
                // Create the category if it does not already exist
1280
                $category = getCreateDbCategory($category, $sqlParser);
1281
1282
                $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...
1283
                $plugin = removeDocblock($plugin, 'plugin');
1284
                $plugin = mysqli_real_escape_string($conn, $plugin);
1285
                $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_plugins` WHERE name='$name'");
1286
                if (mysqli_num_rows($rs)) {
1287
                    $insert = true;
1288
                    while($row = mysqli_fetch_assoc($rs)) {
1289
                        $props = mysqli_real_escape_string($conn, propUpdate($properties,$row['properties']));
1290
                        if($row['description'] == $desc){
1291
                            if (! mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET plugincode='$plugin', description='$desc', properties='$props' WHERE id={$row['id']};")) {
1292
                                echo mysqli_error($sqlParser->conn) . PHP_EOL;
1293
                                return;
1294
                            }
1295
                            $insert = false;
1296 View Code Duplication
                        } else {
1297
                            if (!mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_plugins` SET disabled='1' WHERE id={$row['id']};")) {
1298
                                echo mysqli_error($sqlParser->conn).PHP_EOL;
1299
                                return;
1300
                            }
1301
                        }
1302
                    }
1303 View Code Duplication
                    if($insert === true) {
1304
                        $properties = mysqli_real_escape_string($conn, propUpdate($properties,$row['properties']));
1305
                        if(!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`".$table_prefix."site_plugins` (name,description,plugincode,properties,moduleguid,disabled,category) VALUES('$name','$desc','$plugin','$properties','$guid','0',$category);")) {
1306
                            echo mysqli_error($sqlParser->conn).PHP_EOL;
1307
                            return;
1308
                        }
1309
                    }
1310
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1311 View Code Duplication
                } else {
1312
                    if ($properties != NULL ){
1313
                        $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...
1314
                    }
1315
                    if (!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_plugins` (name,description,plugincode,properties,moduleguid,category,disabled) VALUES('$name','$desc','$plugin','$properties','$guid',$category,$disabled);")) {
1316
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1317
                        return;
1318
                    }
1319
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1320
                }
1321
                // add system events
1322 View Code Duplication
                if (count($events) > 0) {
1323
                    $ds=mysqli_query($sqlParser->conn, "SELECT id FROM $dbase.`".$table_prefix."site_plugins` WHERE name='$name' AND description='$desc';");
1324
                    if ($ds) {
1325
                        $row = mysqli_fetch_assoc($ds);
1326
                        $id = $row["id"];
1327
                        // remove existing events
1328
                        mysqli_query($sqlParser->conn, 'DELETE FROM ' . $dbase . '.`' . $table_prefix . 'site_plugin_events` WHERE pluginid = \'' . $id . '\'');
1329
                        // add new events
1330
                        mysqli_query($sqlParser->conn, "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("','", $events) . "')");
1331
                    }
1332
                }
1333
            }
1334
        }
1335
    }
1336
}
1337
1338
// Install Snippets
1339
$moduleSnippet = $ms;
1340
if (is_array($moduleSnippet) || $installData) {
1341
    echo PHP_EOL . $_lang['snippets'] . ":" . PHP_EOL;
1342
    //$selSnips = $_POST['snippet'];
1343
    foreach ($moduleSnippets as $k=>$moduleSnippet) {
1344
        $installSample = in_array('sample', $moduleSnippet[5]) && $installData == 1;
1345
        if($installSample || is_array($moduleSnippet)) {
1346
            $name = mysqli_real_escape_string($conn, $moduleSnippet[0]);
1347
            $desc = mysqli_real_escape_string($conn, $moduleSnippet[1]);
1348
            $filecontent = $moduleSnippet[2];
1349
            $properties = $moduleSnippet[3];
1350
            $category = mysqli_real_escape_string($conn, $moduleSnippet[4]);
1351
            if (!file_exists($filecontent))
1352
                echo "  $name: " . $_lang['unable_install_snippet'] . " '$filecontent' " . $_lang['not_found'] . PHP_EOL;
1353
            else {
1354
1355
                // Create the category if it does not already exist
1356
                $category = getCreateDbCategory($category, $sqlParser);
1357
1358
                $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...
1359
                $snippet = removeDocblock($snippet, 'snippet');
1360
                $snippet = mysqli_real_escape_string($conn, $snippet);
1361
                $rs = mysqli_query($sqlParser->conn, "SELECT * FROM $dbase.`" . $table_prefix . "site_snippets` WHERE name='$name'");
1362
                if (mysqli_num_rows($rs)) {
1363
                    $row = mysqli_fetch_assoc($rs);
1364
                    $props = mysqli_real_escape_string($conn, propUpdate($properties,$row['properties']));
1365
                    if (!mysqli_query($sqlParser->conn, "UPDATE $dbase.`" . $table_prefix . "site_snippets` SET snippet='$snippet', description='$desc', properties='$props' WHERE name='$name';")) {
1366
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1367
                        return;
1368
                    }
1369
                    echo "  $name: " . $_lang['upgraded'] . PHP_EOL;
1370 View Code Duplication
                } else {
1371
                    if ($properties != NULL ){
1372
                        $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...
1373
                    }
1374
                    if (!mysqli_query($sqlParser->conn, "INSERT INTO $dbase.`" . $table_prefix . "site_snippets` (name,description,snippet,properties,category) VALUES('$name','$desc','$snippet','$properties',$category);")) {
1375
                        echo mysqli_error($sqlParser->conn) . PHP_EOL;
1376
                        return;
1377
                    }
1378
                    echo "  $name: " . $_lang['installed'] . PHP_EOL;
1379
                }
1380
            }
1381
        }
1382
    }
1383
}
1384
1385
// Install demo-site
1386
if ($installData && $moduleSQLDataFile) {
1387
    echo PHP_EOL . $_lang['installing_demo_site'];
1388
    $sqlParser->process($moduleSQLDataFile);
1389
    // display database results
1390
    if ($sqlParser->installFailed == true) {
1391
        $errors += 1;
1392
        echo $_lang['database_alerts'] . PHP_EOL;
1393
        echo $_lang['setup_couldnt_install'] . PHP_EOL;
1394
        echo $_lang['installation_error_occured'] . PHP_EOL . PHP_EOL;
1395
        for ($i = 0; $i < count($sqlParser->mysqlErrors); $i++) {
1396
            echo $sqlParser->mysqlErrors[$i]["error"] . " " . $_lang['during_execution_of_sql'] . " " . strip_tags($sqlParser->mysqlErrors[$i]["sql"]) . PHP_EOL;
1397
        }
1398
1399
        echo $_lang['some_tables_not_updated'] . PHP_EOL;
1400
        return;
1401 View Code Duplication
    } else {
1402
        $sql = sprintf("SELECT id FROM `%ssite_templates` WHERE templatename='EVO startup - Bootstrap'", $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, 'SELECT id, guid FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_modules` WHERE name="' . $dependency['module'] . '"');
1417 View Code Duplication
	if (!$ds) {
1418
		echo mysqli_error($sqlParser->conn) . PHP_EOL;
1419
		return;
1420
	} else {
1421
		$row = mysqli_fetch_assoc($ds);
1422
		$moduleId = $row["id"];
1423
		$moduleGuid = $row["guid"];
1424
	}
1425
	// get extra id
1426
	$ds = mysqli_query($sqlParser->conn, 'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE ' . $dependency['column'] . '="' . $dependency['name'] . '"');
1427 View Code Duplication
	if (!$ds) {
1428
		echo mysqli_error($sqlParser->conn) . PHP_EOL;
1429
		return;
1430
	} else {
1431
		$row = mysqli_fetch_assoc($ds);
1432
		$extraId = $row["id"];
1433
	}
1434
	// setup extra as module dependency
1435
	$ds = mysqli_query($sqlParser->conn, 'SELECT module FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` WHERE module=' . $moduleId . ' AND resource=' . $extraId . ' AND type=' . $dependency['type'] . ' LIMIT 1');
1436
	if (!$ds) {
1437
		echo mysqli_error($sqlParser->conn) . PHP_EOL;
1438
		return;
1439
	} else {
1440
		if (mysqli_num_rows($ds) === 0) {
1441
			mysqli_query($sqlParser->conn, 'INSERT INTO ' . $dbase . '`' . $sqlParser->prefix . 'site_module_depobj` (module, resource, type) VALUES(' . $moduleId . ',' . $extraId . ',' . $dependency['type'] . ')');
1442
			echo $dependency['module'] . ' Module: ' . $_lang['depedency_create'] . PHP_EOL;
1443 View Code Duplication
		} else {
1444
			mysqli_query($sqlParser->conn, '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']);
1445
			echo $dependency['module'] . ' Module: ' . $_lang['depedency_update'] . PHP_EOL;
1446
		}
1447
		if ($dependency['type'] == 30 || $dependency['type'] == 40) {
1448
			// set extra guid for plugins and snippets
1449
			$ds = mysqli_query($sqlParser->conn, 'SELECT id FROM ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` WHERE id=' . $extraId . ' LIMIT 1');
1450
			if (!$ds) {
1451
				echo mysqli_error($sqlParser->conn) . PHP_EOL;
1452
				return;
1453 View Code Duplication
			} else {
1454
				if (mysqli_num_rows($ds) != 0) {
1455
					mysqli_query($sqlParser->conn, 'UPDATE ' . $dbase . '`' . $sqlParser->prefix . 'site_' . $dependency['table'] . '` SET moduleguid = ' . $moduleGuid . ' WHERE id=' . $extraId);
1456
					echo $dependency['name'] . ': ' . $_lang['guid_set'] . PHP_EOL;
1457
				}
1458
			}
1459
		}
1460
	}
1461
}
1462
1463
// call back function
1464
if ($callBackFnc != "")
1465
    $callBackFnc ($sqlParser);
1466
1467
// Setup the MODX API -- needed for the cache processor
1468
if (!defined('MODX_MANAGER_PATH')) define('MODX_MANAGER_PATH', $base_path.MGR_DIR.'/');
1469
$database_type = 'mysqli';
1470
// initiate a new document parser
1471
include_once('../'.MGR_DIR.'/includes/document.parser.class.inc.php');
1472
$modx = new DocumentParser;
1473
$modx->db->connect();
1474
// always empty cache after install
1475
include_once "../".MGR_DIR."/processors/cache_sync.class.processor.php";
1476
$sync = new synccache();
1477
$sync->setCachepath("../assets/cache/");
1478
$sync->setReport(false);
1479
$sync->emptyCache(); // first empty the cache
1480
1481
// try to chmod the cache go-rwx (for suexeced php)
1482
$chmodSuccess = @chmod('../assets/cache/siteCache.idx.php', 0600);
1483
$chmodSuccess = @chmod('../assets/cache/sitePublishing.idx.php', 0600);
1484
1485
// remove any locks on the manager functions so initial manager login is not blocked
1486
mysqli_query($conn, "TRUNCATE TABLE `".$table_prefix."active_users`");
1487
1488
// close db connection
1489
$sqlParser->close();
1490
1491
// andrazk 20070416 - release manager access
1492
if (file_exists('../assets/cache/installProc.inc.php')) {
1493
    @chmod('../assets/cache/installProc.inc.php', 0755);
1494
    unlink('../assets/cache/installProc.inc.php');
1495
}
1496
1497
// setup completed!
1498
echo PHP_EOL . $_lang['installation_successful'] . PHP_EOL . PHP_EOL;
1499
//echo "<p>" . $_lang['to_log_into_content_manager'] . "</p>";
1500
if ($installMode == 0) {
1501
   echo strip_tags($_lang['installation_note']) . PHP_EOL;
1502
} else {
1503
   echo strip_tags($_lang['upgrade_note']) . PHP_EOL;
1504
}
1505
1506
echo PHP_EOL . 'Remove install folder?'.PHP_EOL;
1507
$removeInstall = readline("Type 'y' or 'n' to continue: ");
1508
if ($removeInstall == 'y') {
1509
    echo 'Install folder deleted!'. PHP_EOL . PHP_EOL;
1510
}
1511
1512
/**
1513
 * Property Update function
1514
 *
1515
 * @param string $new
1516
 * @param string $old
1517
 * @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...
1518
 */
1519 View Code Duplication
function propUpdate($new,$old){
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1520
    $newArr = parseProperties($new);
1521
    $oldArr = parseProperties($old);
1522
    foreach ($oldArr as $k => $v){
0 ignored issues
show
Bug introduced by
The expression $oldArr of type string is not traversable.
Loading history...
1523
        if (isset($v['0']['options'])){
1524
            $oldArr[$k]['0']['options'] = $newArr[$k]['0']['options'];
1525
        }
1526
    }
1527
    $return = $oldArr + $newArr;
1528
    $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...
1529
    $return = ($return !== '[]') ? $return : '';
1530
    return $return;
1531
}
1532
1533
/**
1534
 * @param string $propertyString
1535
 * @param bool|mixed $json
1536
 * @return string
1537
 */
1538 View Code Duplication
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 (L498-516) 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...
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1539
    $propertyString = str_replace('{}', '', $propertyString );
1540
    $propertyString = str_replace('} {', ',', $propertyString );
1541
1542
    if(empty($propertyString)) return array();
1543
    if($propertyString=='{}' || $propertyString=='[]') return array();
1544
1545
    $jsonFormat = isJson($propertyString, true);
1546
    $property = array();
1547
    // old format
1548
    if ( $jsonFormat === false) {
1549
        $props= explode('&', $propertyString);
1550
        foreach ($props as $prop) {
1551
            $prop = trim($prop);
1552
            if($prop === '') {
1553
                continue;
1554
            }
1555
1556
            $arr = explode(';', $prop);
1557
            if( ! is_array($arr)) {
1558
                $arr = array();
1559
            }
1560
            $key = explode('=', isset($arr[0]) ? $arr[0] : '');
1561
            if( ! is_array($key) || empty($key[0])) {
1562
                continue;
1563
            }
1564
1565
            $property[$key[0]]['0']['label'] = isset($key[1]) ? trim($key[1]) : '';
1566
            $property[$key[0]]['0']['type'] = isset($arr[1]) ? trim($arr[1]) : '';
1567
            switch ($property[$key[0]]['0']['type']) {
1568
                case 'list':
1569
                case 'list-multi':
1570
                case 'checkbox':
1571
                case 'radio':
1572
                case 'menu':
1573
                    $property[$key[0]]['0']['value'] = isset($arr[3]) ? trim($arr[3]) : '';
1574
                    $property[$key[0]]['0']['options'] = isset($arr[2]) ? trim($arr[2]) : '';
1575
                    $property[$key[0]]['0']['default'] = isset($arr[3]) ? trim($arr[3]) : '';
1576
                    break;
1577
                default:
1578
                    $property[$key[0]]['0']['value'] = isset($arr[2]) ? trim($arr[2]) : '';
1579
                    $property[$key[0]]['0']['default'] = isset($arr[2]) ? trim($arr[2]) : '';
1580
            }
1581
            $property[$key[0]]['0']['desc'] = '';
1582
1583
        }
1584
    // new json-format
1585
    } else if(!empty($jsonFormat)){
1586
        $property = $jsonFormat;
1587
    }
1588
    if ($json) {
1589
        $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...
1590
    }
1591
    $property = ($property !== '[]') ? $property : '';
1592
    return $property;
1593
}
1594
1595
/**
1596
 * @param string $string
1597
 * @param bool $returnData
1598
 * @return bool|mixed
1599
 */
1600
function isJson($string, $returnData=false) {
1601
    $data = json_decode($string, true);
1602
    return (json_last_error() == JSON_ERROR_NONE) ? ($returnData ? $data : true) : false;
1603
}
1604
1605
/**
1606
 * @param string|int $category
1607
 * @param SqlParser $sqlParser
1608
 * @return int
1609
 */
1610 View Code Duplication
function getCreateDbCategory($category, $sqlParser) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1611
    $dbase = $sqlParser->dbname;
1612
    $dbase = '`' . trim($dbase,'`') . '`';
1613
    $table_prefix = $sqlParser->prefix;
1614
    $category_id = 0;
1615
    if(!empty($category)) {
1616
        $category = mysqli_real_escape_string($sqlParser->conn, $category);
1617
        $rs = mysqli_query($sqlParser->conn, "SELECT id FROM $dbase.`".$table_prefix."categories` WHERE category = '".$category."'");
1618
        if(mysqli_num_rows($rs) && ($row = mysqli_fetch_assoc($rs))) {
1619
            $category_id = $row['id'];
1620
        } else {
1621
            $q = "INSERT INTO $dbase.`".$table_prefix."categories` (`category`) VALUES ('{$category}');";
1622
            $rs = mysqli_query($sqlParser->conn, $q);
1623
            if($rs) {
1624
                $category_id = mysqli_insert_id($sqlParser->conn);
1625
            }
1626
        }
1627
    }
1628
    return $category_id;
1629
}
1630
1631
/**
1632
 * Remove installer Docblock only from components using plugin FileSource / fileBinding
1633
 *
1634
 * @param string $code
1635
 * @param string $type
1636
 * @return string
1637
 */
1638 View Code Duplication
function removeDocblock($code, $type) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1639
1640
    $cleaned = preg_replace("/^.*?\/\*\*.*?\*\/\s+/s", '', $code, 1);
1641
1642
    // Procedure taken from plugin.filesource.php
1643
    switch($type) {
1644
        case 'snippet':
1645
            $elm_name = 'snippets';
1646
            $include = 'return require';
1647
            $count = 47;
1648
            break;
1649
1650
        case 'plugin':
1651
            $elm_name = 'plugins';
1652
            $include = 'require';
1653
            $count = 39;
1654
            break;
1655
1656
        default:
1657
            return $cleaned;
1658
    };
1659
    if(substr(trim($cleaned),0,$count) == $include.' MODX_BASE_PATH.\'assets/'.$elm_name.'/')
1660
        return $cleaned;
1661
1662
    // fileBinding not found - return code incl docblock
1663
    return $code;
1664
}
1665