Completed
Push — master ( 176486...dcf38a )
by Julito
52:32 queued 19:58
created

Virtual::chopLastSlash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Cocur\Slugify\Slugify;
5
use Symfony\Component\Finder\Finder;
6
use Symfony\Component\Console\Input\ArrayInput;
7
use Symfony\Component\Console\Output\StreamOutput;
8
use Symfony\Component\Console\Application;
9
use Doctrine\ORM\EntityManager;
10
11
/**
12
 * Class Virtual
13
 */
14
class Virtual
15
{
16
    /**
17
     * @param array $_configuration
18
     */
19
    public static function hookConfiguration(& $_configuration)
20
    {
21
        global $virtualChamilo;
22
23
        if (defined('CLI_SCRIPT') && !defined('CLI_VCHAMILO_OVERRIDE')) {
24
            return;
25
        }
26
27
28
        // provides an effective value for the virtual root_web based on domain analysis
29
        self::getHostName($_configuration);
30
31
        // We are on physical chamilo. Let original config play
32
        $virtualChamiloWebRoot = $_configuration['vchamilo_web_root'].'/';
33
34
        $virtualChamilo = [];
35
        if ($_configuration['root_web'] == $virtualChamiloWebRoot) {
36
            return;
37
        }
38
39
        // pre hook to chamilo main table and get alternate configuration.
40
        // sure Database object is not set up. Soo use bootstrap connection
41
        /** @var \Doctrine\DBAL\Connection $connection */
42
        $connection = Virtual::bootConnection($_configuration);
43
44
        $query = "SELECT * FROM vchamilo WHERE root_web = '$virtualChamiloWebRoot'";
45
        $result = $connection->executeQuery($query);
46
47
        if ($result->rowCount()) {
48
            $data = $result->fetch();
49
            $excludes = array('id', 'name');
50
            $query = "SELECT * FROM settings_current WHERE subkey = 'vchamilo'";
51
            $virtualSettings = $connection->executeQuery($query);
52
            $virtualSettings = $virtualSettings->fetchAll();
53
54
            $homePath = '';
55
            $coursePath = '';
56
            $archivePath = '';
57
            $uploadPath = '';
58
            $passwordEncryption = '';
59
60
            foreach ($virtualSettings as $setting) {
61
                switch ($setting['variable']) {
62
                    case 'vchamilo_upload_real_root':
63
                        $uploadPath = $setting['selected_value'];
64
                        break;
65
                    case 'vchamilo_home_real_root':
66
                        $homePath = $setting['selected_value'];
67
                        break;
68
                    case 'vchamilo_course_real_root':
69
                        $coursePath = $setting['selected_value'];
70
                        break;
71
                    case 'vchamilo_archive_real_root':
72
                        $archivePath = $setting['selected_value'];
73
                        break;
74
                    case 'vchamilo_password_encryption':
75
                        $passwordEncryption = $setting['selected_value'];
76
                        break;
77
                }
78
            }
79
80
            if (empty($homePath) || empty($coursePath) || empty($archivePath) || empty($uploadPath)) {
81
                echo 'Configure correctly the vchamilo plugin';
82
                exit;
83
            }
84
85
            // Only load if is visible
86
            if ($data && $data['visible'] === '1') {
87
                foreach ($data as $key => $value) {
88
                    if (!in_array($key, $excludes)) {
89
                        // Avoid empty password_encryption
90
                        if ($key == 'password_encryption' && empty($value)) {
91
                            continue;
92
                        }
93
                        $_configuration[$key] = $value;
94
                    }
95
                    $_configuration['virtual'] = $data['root_web'].'/';
96
                }
97
98
                $data['SYS_ARCHIVE_PATH'] = self::addTrailingSlash($archivePath).$data['slug'];
99
                $data['SYS_HOME_PATH'] = self::addTrailingSlash($homePath).$data['slug'];
100
                $data['SYS_COURSE_PATH'] = self::addTrailingSlash($coursePath).$data['slug'];
101
                $data['SYS_UPLOAD_PATH'] = self::addTrailingSlash($uploadPath).$data['slug'];
102
103
                if (!empty($passwordEncryption)) {
104
                    $_configuration['password_encryption'] = $passwordEncryption;
105
                }
106
107
                $virtualChamilo = $data;
108
            } else {
109
                exit("This portal is disabled. Please contact your administrator");
110
            }
111
        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
112
            // Platform was not configured yet
113
            //die("VChamilo : Could not fetch virtual chamilo configuration");
114
        }
115
    }
116
117
    /**
118
     * @param array $_configuration
119
     */
120
    public static function getHostName(&$_configuration)
121
    {
122
        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
123
            $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
124
        ) {
125
            $protocol = 'https';
126
        } else {
127
            $protocol = 'http';
128
        }
129
130
        if (defined('CLI_VCHAMILO_OVERRIDE')) {
131
            $_configuration['vchamilo_web_root'] = CLI_VCHAMILO_OVERRIDE;
132
            $_configuration['vchamilo_name'] = preg_replace('#https?://#', '', CLI_VCHAMILO_OVERRIDE);
133
            // remove radical from override for name
134
135
            // fake the server signature
136
            global $_SERVER;
137
138
            $_SERVER['SERVER_NAME'] = $_configuration['vchamilo_name'];
139
            $_SERVER['HTTP_HOST'] = $_configuration['vchamilo_name'];
140
            $_SERVER['QUERY_STRING'] = '';
141
            $_SERVER['REQUEST_URI'] = CLI_VCHAMILO_OVERRIDE;
142
143
            return;
144
        }
145
146
        $contentPrefix = '/';
147
        if (isset($_SERVER['CONTEXT_PREFIX']) && !empty($_SERVER['CONTEXT_PREFIX'])) {
148
            $contentPrefix = $_SERVER['CONTEXT_PREFIX'];
149
        } else {
150
            // Getting url_append from URL
151
            if (isset($_SERVER['REQUEST_URI'])) {
152
                $requestUri = $_SERVER['REQUEST_URI'];
153
                if (strpos($requestUri, '/courses/') !== false) {
154
                    $result = substr($requestUri, 0, strpos($requestUri, '/courses/'));
155
                    if (!empty($result) && $result != '/') {
156
                        $contentPrefix = $result;
157
                    }
158
                }
159
            }
160
        }
161
162
        $_configuration['vchamilo_web_root'] = "{$protocol}://".@$_SERVER['HTTP_HOST'].$contentPrefix;
163
164
        $_configuration['vchamilo_name'] = @$_SERVER['HTTP_HOST'];
165
        if (empty($_configuration['vchamilo_name'])) { // try again with another source if has failed
166
            $_configuration['vchamilo_name'] = "{$protocol}://".$_SERVER['SERVER_NAME'];
167
            if ($_SERVER['SERVER_PORT'] != 80) {
168
                $_configuration['vchamilo_name'] .= ':'.$_SERVER['SERVER_PORT'];
169
            }
170
            $_configuration['vchamilo_name'] = $_SERVER['SERVER_NAME'];
171
        }
172
    }
173
174
    /**
175
     * @param string $path
176
     * @return string
177
     */
178
    public static function addTrailingSlash($path)
179
    {
180
        return substr($path, -1) == '/' ? $path : $path.'/';
181
    }
182
183
    /**
184
    * provides a side connection to a vchamilo database
185
    * @param array $_configuration
186
     *
187
    * @return \Doctrine\DBAL\Driver\Connection
188
    */
189
    public static function bootConnection(&$_configuration)
190
    {
191
        $dbParams = array(
192
            'driver' => 'pdo_mysql',
193
            'host' => $_configuration['db_host'],
194
            'user' => $_configuration['db_user'],
195
            'password' => $_configuration['db_password'],
196
            'dbname' => isset($_configuration['main_database']) ? $_configuration['main_database'] : '',
197
            // Only relevant for pdo_sqlite, specifies the path to the SQLite database.
198
            'path' => isset($_configuration['db_path']) ? $_configuration['db_path'] : '',
199
            // Only relevant for pdo_mysql, pdo_pgsql, and pdo_oci/oci8,
200
            'port' => isset($_configuration['db_port']) ? $_configuration['db_port'] : '',
201
        );
202
203
        try {
204
            $database = new \Database();
205
            $connection = $database->connect(
206
                $dbParams,
207
                $_configuration['root_sys'],
208
                $_configuration['root_sys'],
209
                true
210
            );
211
        } catch (Exception $e) {
212
            echo('Side connection failure with '.$_configuration['db_host'].', '.$_configuration['db_user'].', ******** ');
213
            die();
214
        }
215
216
        return $connection;
217
    }
218
219
    /**
220
     * @param string $url
221
     */
222
    public static function redirect($url)
223
    {
224 View Code Duplication
        if (preg_match('#https?://#', $url)) {
225
            header('location: '.$url);
226
        } else {
227
            header('location: ' . api_get_path(WEB_PATH).$url);
228
        }
229
        exit;
230
    }
231
232
    /**
233
     * @param string $course_folder
234
     * @return string
235
     */
236
    public static function getHtaccessFragment($course_folder)
237
    {
238
        $str = "
239
        # Change this file to fit your configuration and save it as .htaccess in the courses folder #
240
        # Chamilo mod rewrite
241
        # Comment lines start with # and are not processed
242
        
243
        <IfModule mod_rewrite.c>
244
        RewriteEngine On
245
        
246
        # Rewrite base is the dir chamilo is installed in with trailing slash
247
        RewriteBase /{$course_folder}/
248
        
249
        # Do not rewrite on the main dir
250
        # Change this path to the path of your main folder
251
        RewriteCond %{REQUEST_URI} !^/main/
252
        
253
        #replace nasty ampersands by 3 slashes, we change these back in download.php
254
        RewriteRule ([^/]+)/document/(.*)&(.*)$ $1/document/$2///$3 [N]
255
        
256
        # Rewrite everything in the scorm folder of a course to the download script
257
        RewriteRule ([^/]+)/scorm/(.*)$ /main/document/download_scorm.php?doc_url=/$2&cDir=$1 [QSA,L]
258
        
259
        # Rewrite everything in the document folder of a course to the download script
260
        RewriteRule ([^/]+)/document/(.*)$ /main/document/download.php?doc_url=/$2&cDir=$1 [QSA,L]
261
        
262
        # Rewrite everything in the work folder
263
        RewriteRule ([^/]+)/work/(.*)$ /main/work/download.php?file=work/$2&cDir=$1 [QSA,L]
264
        </IfModule>
265
        ";
266
267
        return $str;
268
    }
269
270
    /**
271
     * @return string
272
     */
273
    public static function getDefaultCourseIndexFragment()
274
    {
275
        return "<html><head></head><body></body></html>";
276
    }
277
278
    /**
279
     * @param string $template
280
     * @return bool
281
     */
282
    public static function templateExists($template)
283
    {
284
        global $_configuration;
285
286
        // Find and checktemplate directory (files and SQL).
287
        $separator = DIRECTORY_SEPARATOR;
288
        $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
289
        $relative_datadir = $templatefoldername.$separator.$template.'_sql';
290
        $absolute_datadir = $_configuration['root_sys'].$relative_datadir;
291
292
        return is_dir($absolute_datadir);
293
    }
294
295
    /**
296
    * drop a vchamilo instance databases using the physical connection
297
    * @param stdClass $params
298
    * return an array of errors or false if ok
299
    */
300
    public static function dropDatabase($params)
301
    {
302
        $params = clone $params;
303
304
        if (empty($params->main_database)) {
305
            Display::addFlash(Display::return_message('No database found'));
306
307
            return;
308
        }
309
310
        $databaseToDelete = $params->main_database;
311
        unset($params->main_database);
312
        $connection = self::getConnectionFromInstance($params);
313
        if ($connection) {
314
            $databases = $connection->getSchemaManager()->listDatabases();
315
316 View Code Duplication
            if (in_array($databaseToDelete, $databases)) {
317
                $connection->getSchemaManager()->dropDatabase(
318
                    $databaseToDelete
319
                );
320
                Display::addFlash(
321
                    Display::return_message(
322
                        'Database deleted: '.$databaseToDelete
323
                    )
324
                );
325
            } else {
326
                Display::addFlash(
327
                    Display::return_message(
328
                        'Database does not exist: '.$databaseToDelete
329
                    )
330
                );
331
            }
332
        } else {
333
            Display::addFlash(
334
                Display::return_message(
335
                    "Cannot connect DB: $databaseToDelete"
336
                )
337
            );
338
        }
339
340
        return false;
341
    }
342
343
    /**
344
     * @param stdClass $params
345
     * @return bool
346
     */
347
    public static function createDatabase($params)
348
    {
349
        $params = clone $params;
350
        $databaseName = $params->main_database;
351
        unset($params->main_database);
352
353
        $connection = Virtual::getConnectionFromInstance($params);
354
        if ($connection) {
355
            $databaseList = $connection->getSchemaManager()->listDatabases();
356
357 View Code Duplication
            if (!in_array($databaseName, $databaseList)) {
358
                $connection->getSchemaManager()->createDatabase($databaseName);
359
                Display::addFlash(
360
                    Display::return_message("Creating DB ".$databaseName)
361
                );
362
            } else {
363
                Display::addFlash(
364
                    Display::return_message("DB already exists: ".$databaseName)
365
                );
366
            }
367
368
            return true;
369
        }
370
        return false;
371
    }
372
373
    /**
374
    * get a proper SQLdump command
375
    * @param object $vchamilodata the complete new host information
376
    * @return string the shell command
377
    */
378
    public static function getDatabaseDumpCmd($vchamilodata)
379
    {
380
        $pgm = self::getConfig('vchamilo', 'mysql_cmd');
381
382
        if (!$pgm) {
383
            $pgm = '/usr/bin/mysql';
384
        }
385
386
        $phppgm = str_replace("\\", '/', $pgm);
387
        $phppgm = str_replace("\"", '', $phppgm);
388
        $pgm = str_replace("/", DIRECTORY_SEPARATOR, $pgm);
389
390
        if (!is_executable($phppgm)) {
391
            throw new Exception('databasecommanddoesnotmatchanexecutablefile');
392
        }
393
394
        // Retrieves the host configuration (more secure).
395
        $vchamilodata = empty($vchamilodata) ? Virtual::makeThis() : $vchamilodata;
396 View Code Duplication
        if (strstr($vchamilodata->db_host, ':') !== false) {
397
            list($vchamilodata->db_host, $vchamilodata->db_port) = explode(
398
                ':',
399
                $vchamilodata->db_host
400
            );
401
        }
402
403
        // Password.
404
        $databasePassword = '';
405
        if (!empty($vchamilodata->db_password)) {
406
            $databasePassword = '-p'.escapeshellarg($vchamilodata->db_password).' ';
407
        }
408
409
        // Making the command line (see 'vconfig.php' file for defining the right paths).
410
        $sqlcmd = $pgm.' -h'.$vchamilodata->db_host.(isset($vchamilodata->db_port) ? ' -P'.$vchamilodata->db_port.' ' : ' ' );
411
        $sqlcmd .= '-u'.$vchamilodata->db_user.' '.$databasePassword;
412
        $sqlcmd .= '%DATABASE% < ';
413
414
        return $sqlcmd;
415
    }
416
417
    /**
418
     * @param stdClass $vchamilo
419
     * @param string $template
420
     * @return bool
421
     */
422
    public static function loadDbTemplate($vchamilo, $template)
423
    {
424
        global $_configuration;
425
426
        // Make template directory (files and SQL).
427
        $separator = DIRECTORY_SEPARATOR;
428
        $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
429
        $absolute_datadir = $_configuration['root_sys'].$templatefoldername.$separator.$template.$separator.'dump.sql';
430
431
        if (!$sqlcmd = Virtual::getDatabaseDumpCmd($vchamilo)) {
432
            return false;
433
        }
434
435
        $sqlcmd = str_replace('%DATABASE%', $vchamilo->main_database, $sqlcmd);
436
437
        // Make final commands to execute, depending on the database type.
438
        $import = $sqlcmd.$absolute_datadir;
439
440
        // Execute the command.
441
        Display::addFlash(Display::return_message("Load database from template dump: \n $import "));
442
443
        if (!defined('CLI_SCRIPT')) {
444
            putenv('LANG=en_US.utf-8');
445
        }
446
        // ensure utf8 is correctly handled by php exec()
447
        // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
448
449
        exec($import, $output, $return);
450
        if (!empty($output)) {
451
            Display::addFlash(Display::return_message(implode("\n", $output)."\n"));
452
        }
453
454
        return true;
455
    }
456
457
    /**
458
     * Backups a database for having a snapshot.
459
     * @param        $vchamilo    object        The Vchamilo object.
460
     * @param        $outputfilerad    string        The output SQL file radical.
461
     * @return        bool    If TRUE, dumping database was a success, otherwise FALSE.
462
     */
463
    public static function backupDatabase($vchamilo, $outputfilerad)
464
    {
465
        // Separating host and port, if sticked.
466 View Code Duplication
        if (strstr($vchamilo->db_host, ':') !== false) {
467
            list($host, $port) = explode(':', $vchamilo->db_host);
468
        } else {
469
            $host = $vchamilo->db_host;
470
        }
471
472
        // By default, empty password.
473
        $pass = '';
474
        $pgm = null;
475
476
        if (empty($port)) {
477
            $port = 3306;
478
        }
479
480
        // Password.
481
        if (!empty($vchamilo->db_password)) {
482
            $pass = "-p".escapeshellarg($vchamilo->db_password);
483
        }
484
485
        // Making the commands for each database.
486
        $cmds = array();
487
        //if ($CFG->ostype == 'WINDOWS') {
488
        if (false) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
489
            $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
490
            $cmds[] = $cmd_main . ' > ' . $outputfilerad;
491
        } else {
492
            $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
493
            $cmds[] = $cmd_main . ' > ' . escapeshellarg($outputfilerad);
494
        }
495
496
        $mysqldumpcmd = self::getConfig('vchamilo', 'cmd_mysqldump', true);
497
498
        $pgm = !empty($mysqldumpcmd) ? stripslashes($mysqldumpcmd) : false;
499
500
        if (!$pgm) {
501
            $message = "Database dump command not available check here: ";
502
            $url = api_get_path(WEB_CODE_PATH).'admin/configure_plugin.php?name=vchamilo';
503
            $message .= Display::url($url, $url);
504
            Display::addFlash(Display::return_message($message));
505
506
            return false;
507
        } else {
508
            $phppgm = str_replace("\\", '/', $pgm);
509
            $phppgm = str_replace("\"", '', $phppgm);
510
            $pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
511
512
            if (!is_executable($phppgm)) {
513
                $message = "Database dump command $phppgm does not match any executable";
514
                Display::addFlash(Display::return_message($message));
515
516
                return false;
517
            }
518
519
            // executing all commands
520
            foreach ($cmds as $cmd) {
521
                // Final command.
522
                $cmd = $pgm.' '.$cmd;
523
524
                // Executes the SQL command.
525
                exec($cmd, $execoutput, $returnvalue);
526
            }
527
        }
528
529
        // End with success.
530
        return 1;
531
    }
532
533
    /**
534
    * read manifest values in vchamilo template.
535
    */
536
    public static function getVmanifest($version)
537
    {
538
        $file = api_get_path(SYS_PATH).'/plugin/vchamilo/templates/'.$version.'/manifest.php';
539
        if (file_exists($file)) {
540
            include $file;
541
542
            $manifest = new stdClass();
543
            $manifest->templatewwwroot = $templatewwwroot;
0 ignored issues
show
Bug introduced by
The variable $templatewwwroot does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
544
            //    $manifest->templatevdbprefix = $templatevdbprefix;
545
            //    $manifest->coursefolder = $coursefolder;
546
547
            return $manifest;
548
        }
549
550
        return false;
551
    }
552
553
    /**
554
    * make a fake vchamilo that represents the current host
555
    */
556
    public static function makeThis()
557
    {
558
        global $_configuration;
559
560
        $thisPortal = new stdClass();
561
        $thisPortal->root_web = $_configuration['root_web'];
562
        $thisPortal->db_host = $_configuration['db_host'];
563
        $thisPortal->db_user = $_configuration['db_user'];
564
        $thisPortal->db_password = $_configuration['db_password'];
565
        $thisPortal->main_database = $_configuration['main_database'];
566
567
        return $thisPortal;
568
    }
569
570
    /**
571
     * Get available templates for defining a new virtual host.
572
     * @return        array        The available templates, or EMPTY array.
573
     */
574
    public static function getAvailableTemplates()
575
    {
576
        global $_configuration;
577
578
        $separator = DIRECTORY_SEPARATOR;
579
580
        $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
581
        $tempDir = $_configuration['root_sys'].$templatefoldername;
582
583
        // Scans the templates.
584
        if (!is_dir($tempDir)) {
585
            mkdir($tempDir, 0777, true);
586
        }
587
588
        $finder = new \Symfony\Component\Finder\Finder();
589
        $dirs = $finder->in($tempDir)->depth('== 0');
590
591
        // Retrieves template(s) name(s). Should be hostnames.
592
        $templates = [];
593
        /*if ($addEmptyTemplate) {
594
            $templates = array('' => $plugin->get_lang('emptysite'));
595
        }*/
596
597
        $template = self::getConfig('vchamilo', 'default_template');
598
599
        if ($dirs) {
600
            /** @var Symfony\Component\Finder\SplFileInfo $dir */
601
            foreach ($dirs as $dir) {
602
                if (is_dir($dir->getPathname())) {
603
                    // A template is considered when a dump.sql exists.
604
                    if (file_exists($dir->getPathname().'/dump.sql')) {
605
                        $templateName = $dir->getRelativePathname();
606
                        if ($templateName == $template) {
607
                            $templateName .= ' (default)';
608
                        }
609
                        $templates[$dir->getRelativePathname()] = $templateName;
610
                    }
611
                }
612
            }
613
        }
614
615
        return $templates;
616
    }
617
618
    /**
619
    * this function set will map standard moodle API calls to chamilo
620
    * internal primitives. This avoids too many changes to do in imported
621
    * code
622
    */
623
    public static function getConfig($module, $key, $isplugin = true)
624
    {
625
        if ($isplugin) {
626
            $key = $module.'_'.$key;
627
        }
628
629
        $params = array('variable = ? AND subkey = ?' => [$key, $module]);
630
        $result = api_get_settings_params_simple($params);
631
        if ($result) {
632
            return $result['selected_value'];
633
        }
634
635
        return false;
636
    }
637
638
    /**
639
     * @param stdClass $vchamilo
640
     * @param string $template
641
     */
642
    public static function loadFilesFromTemplate($vchamilo, $template)
643
    {
644
        global $_configuration;
645
646
        // Make template directory (files and SQL).
647
        $separator = DIRECTORY_SEPARATOR;
648
        $templateDir = $_configuration['root_sys'].'plugin'.$separator.'vchamilo'.$separator.'templates'.$separator.$template;
649
        $vchamilo->virtual = true;
650
        $coursePath = self::getConfig('vchamilo', 'course_real_root').$separator.$vchamilo->slug;
651
        $homePath = self::getConfig('vchamilo', 'home_real_root').$separator.$vchamilo->slug;
652
        $archivePath = self::getConfig('vchamilo', 'archive_real_root').$separator.$vchamilo->slug;
653
        $uploadPath = self::getConfig('vchamilo', 'upload_real_root').$separator.$vchamilo->slug;
654
655
        // get the protocol free hostname
656
        Display::addFlash(
657
            Display::return_message("Copying {$templateDir}/data/courses => $coursePath")
658
        );
659
660
        copyDirTo(
661
            self::chopLastSlash($templateDir.'/data/courses'),
662
            self::chopLastSlash($coursePath),
663
            false
664
        );
665
666
        Display::addFlash(
667
            Display::return_message("Copying {$templateDir}/data/archive => $archivePath")
668
        );
669
670
        copyDirTo(
671
            self::chopLastSlash($templateDir.'/data/archive'),
672
            self::chopLastSlash($archivePath),
673
            false
674
        );
675
676
        Display::addFlash(
677
            Display::return_message("Copying {$templateDir}/data/home => $homePath")
678
        );
679
680
        copyDirTo(
681
            self::chopLastSlash($templateDir.'/data/home'),
682
            self::chopLastSlash($homePath),
683
            false
684
        );
685
686
        // Upload
687
        Display::addFlash(
688
            Display::return_message("Copying {$templateDir}/data/upload => $uploadPath")
689
        );
690
691
        copyDirTo(
692
            self::chopLastSlash($templateDir.'/data/upload/'),
693
            self::chopLastSlash($uploadPath),
694
            false
695
        );
696
    }
697
698
    /**
699
     * @param string $path
700
     *
701
     * @return mixed
702
     */
703
    public static function chopLastSlash($path)
704
    {
705
        return preg_replace('/\/$/', '', $path);
706
    }
707
708
    /**
709
     * @param string $str
710
     */
711
    public static function ctrace($str)
712
    {
713
        error_log($str);
714
        Display::addFlash(Display::return_message($str, 'normal', false));
715
    }
716
717
    /**
718
     * @param $file
719
     * @param $component
720
     * @param bool $return
721
     * @return string
722
     */
723 View Code Duplication
    public static function requireJs($file, $component, $return = false)
724
    {
725
        global $_configuration, $htmlHeadXtra;
726
727
        if (preg_match('/^local_/', $component)) {
728
            $component = str_replace('local_', '', $component);
729
            $path = 'local/';
730
        } else {
731
            $path = 'plugin/';
732
        }
733
734
        // Secure the postslashing of the roots.
735
        $root_web = $_configuration['root_web'].'/';
736
        $root_web = preg_replace('#//$#', '/', $root_web);
737
738
        $str = '<script type="text/javascript" src="'.$root_web.$path.$component.'/js/'.$file.'"></script>'."\n";
739
        if ($return === 'head') {
740
            $htmlHeadXtra[] = $str;
741
        }
742
743
        if ($return) {
744
            return $str;
745
        }
746
        echo $str;
747
    }
748
749
    /**
750
     * @param $file
751
     * @param $component
752
     * @param bool $return
753
     * @return string
754
     */
755 View Code Duplication
    public static function requireCss($file, $component, $return = false)
756
    {
757
        global $_configuration, $htmlHeadXtra;
758
759
        if (preg_match('/^local_/', $component)) {
760
            $component = str_replace('local_', '', $component);
761
            $path = 'local/';
762
        } else {
763
            $path = 'plugin/';
764
        }
765
766
        // Secure the postslashing of the roots.
767
        $root_web = $_configuration['root_web'].'/';
768
        $root_web = preg_replace('#//$#', '/', $root_web);
769
770
        $str = '<link rel="stylesheet" type="text/css" href="'.$root_web.$path.$component.'/'.$file.'.css" />'."\n";
771
        if ($return === 'head') {
772
            $htmlHeadXtra[] = $str;
773
        }
774
        if ($return) {
775
            return $str;
776
        }
777
        echo $str;
778
    }
779
780
    /**
781
     * @param string $url
782
     * @return string
783
     */
784
    public static function getSlugFromUrl($url)
785
    {
786
        $slugify = new Slugify();
787
        $urlInfo = parse_url($url);
788
        if (isset($urlInfo['host'])) {
789
            $path = $urlInfo['path'] != '/' ? '_'.$urlInfo['path'] : '';
790
            return $slugify->slugify($urlInfo['host'].$path);
791
        }
792
793
        return false;
794
    }
795
796
    /**
797
     * Check if all settings are complete
798
     */
799
    public static function checkSettings()
800
    {
801
        $enabled = self::getConfig('vchamilo', 'enable_virtualisation');
802
803
        if (empty($enabled)) {
804
            api_not_allowed(true, 'Plugin is not enabled');
805
        }
806
807
        global $virtualChamilo;
808
        if (!isset($virtualChamilo)) {
809
            api_not_allowed(
810
                true,
811
                'You have to edit the configuration.php. Please check the readme file.'
812
            );
813
        }
814
815
        $coursePath = self::getConfig('vchamilo', 'course_real_root');
816
        $homePath = self::getConfig('vchamilo', 'home_real_root');
817
        $archivePath = self::getConfig('vchamilo', 'archive_real_root');
818
        $uploadPath = self::getConfig('vchamilo', 'upload_real_root');
819
        $cmdSql = self::getConfig('vchamilo', 'cmd_mysql');
820
        $cmdMySql = self::getConfig('vchamilo', 'cmd_mysqldump');
821
822
        if (empty($coursePath) || empty($homePath) || empty($uploadPath) || empty($archivePath) || empty($cmdSql) || empty($cmdMySql)) {
823
            api_not_allowed(true, 'You have to complete all plugin settings.');
824
        }
825
826
        $separator = DIRECTORY_SEPARATOR;
827
        $templatePath = api_get_path(SYS_PATH).'plugin'.$separator.'vchamilo'.$separator.'templates';
828
829
        $paths = [
830
            $coursePath,
831
            $homePath,
832
            $archivePath,
833
            $uploadPath,
834
            $templatePath
835
        ];
836
837
        foreach ($paths as $path) {
838
            $path = trim($path);
839 View Code Duplication
            if (is_dir($path)) {
840
                if (!is_writable($path)) {
841
                    Display::addFlash(
842
                        Display::return_message("Directory must have writable permissions: '$path'", 'warning')
843
                    );
844
                };
845
            } else {
846
                Display::addFlash(
847
                    Display::return_message("Directory doesn't exist: '$path'", 'warning')
848
                );
849
            }
850
        }
851
    }
852
853
    /**
854
     * @param object $instance
855
     * @return \Doctrine\DBAL\Connection
856
     */
857
    public static function getConnectionFromInstance($instance, $getManager = false)
858
    {
859
        $dbParams = array(
860
            'driver' => 'pdo_mysql',
861
            'host' => $instance->db_host,
862
            'user' => $instance->db_user,
863
            'password' => $instance->db_password,
864
            //'dbname' => $instance->main_database,
865
            // Only relevant for pdo_sqlite, specifies the path to the SQLite database.
866
            //'path' => isset($_configuration['db_path']) ? $_configuration['db_path'] : '',
867
            // Only relevant for pdo_mysql, pdo_pgsql, and pdo_oci/oci8,
868
            //'port' => isset($_configuration['db_port']) ? $_configuration['db_port'] : '',
869
        );
870
871
        if (!empty($instance->main_database)) {
872
            $dbParams['dbname'] = $instance->main_database;
873
        }
874
875
        try {
876
            $database = new \Database();
877
            $manager = $database->connect(
878
                $dbParams,
879
                api_get_configuration_value('root_sys'),
880
                api_get_configuration_value('root_sys'),
881
                false,
882
                true
883
            );
884
885
            if ($getManager) {
886
                return $manager;
887
            }
888
889
            return $manager->getConnection();
0 ignored issues
show
Bug introduced by
The method getConnection does only exist in Doctrine\ORM\EntityManager, but not in Doctrine\DBAL\Connection.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
890
        } catch (Exception $e) {
891
            echo $e->getMessage();
892
        }
893
    }
894
895
    /**
896
     * @param $data
897
     */
898
    public static function addInstance($data)
899
    {
900
        if (isset($data->what)) {
901
            unset($data->what);
902
        }
903
        if (isset($data->submitbutton)) {
904
            unset($data->submitbutton);
905
        }
906
        if (isset($data->id)) {
907
            unset($data->id);
908
        }
909
        if (isset($data->vid)) {
910
            unset($data->vid);
911
        }
912
        if (isset($data->testconnection)) {
913
            unset($data->testconnection);
914
        }
915
        if (isset($data->testdatapath)) {
916
            unset($data->testdatapath);
917
        }
918
919
        $registeronly = $data->registeronly;
920
        unset($data->registeronly);
921
        $data->lastcron = 0;
922
        $data->lastcrongap = 0;
923
        $data->croncount = 0;
924
925
        if (isset($data->template) && !empty($data->template)) {
926
            $template = $data->template;
927
        } else {
928
            $template = '';
929
        }
930
931
        $mainDatabase = api_get_configuration_value('main_database');
932
933
        if ($mainDatabase == $data->main_database) {
934
            Display::addFlash(
935
                Display::return_message('You cannot use the same database as the chamilo master', 'error')
936
            );
937
938
            return ;
939
        }
940
941
        $data->root_web = api_add_trailing_slash($data->root_web);
942
943
        self::ctrace('Registering: '.$data->root_web);
944
        $tablename = Database::get_main_table('vchamilo');
945
        $sql = "SELECT * FROM $tablename 
946
                WHERE root_web = '".Database::escape_string($data->root_web)."'";
947
        $result = Database::query($sql);
948
949
        if (Database::num_rows($result)) {
950
            Database::update($tablename, $data, ['root_web = ?' => $data->root_web]);
951
            $virtualInfo = Database::fetch_array($result);
952
            $slug = $virtualInfo['slug'];
953
        } else {
954
            $slug = $data->slug = Virtual::getSlugFromUrl($data->root_web);
955
            if (empty($slug)) {
956
                Display::addFlash(
957
                    Display::return_message('Cannot create slug from url: '.$data->root_web, 'error')
958
                );
959
                return ;
960
            }
961
            Database::insert($tablename, (array) $data);
962
        }
963
964
        if ($registeronly) {
965
            // Stop it now.
966
            self::ctrace('Registering only. out.');
967
            Virtual::redirect(api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php');
968
        }
969
970
        // or we continue with physical creation
971
        self::createDirsFromSlug($slug);
972
973
        if (!$template) {
974
            // Create empty database for install
975
            self::ctrace("Creating database");
976
            Virtual::createDatabase($data);
977
        } else {
978
            // Deploy template database
979
            self::ctrace("Creating databases from template '$template'");
980
            Virtual::createDatabase($data);
981
            self::ctrace("Loading data template '$template'");
982
            Virtual::loadDbTemplate($data, $template);
983
            self::ctrace("Coying files from template '$template'");
984
            Virtual::loadFilesFromTemplate($data, $template);
985
        }
986
987
        // pluging in site name institution
988
        $settingstable = $data->main_database.'.settings_current';
989
        $accessurltable = $data->main_database.'.access_url';
990
991
        $sitename = Database::escape_string($data->sitename);
992
        $institution = Database::escape_string($data->institution);
993
994
        $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$sitename}' 
995
                   WHERE variable = 'siteName' AND category = 'Platform' ";
996
997
        $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$institution}' 
998
                   WHERE variable = 'institution' AND category = 'Platform' ";
999
1000
        $sqls[] = "UPDATE {$accessurltable} SET url = '{$data->root_web}' WHERE id = '1' ";
1001
1002
        foreach ($sqls as $sql) {
1003
            Database::query($sql);
1004
        }
1005
1006
        self::ctrace("Finished");
1007
    }
1008
1009
    /**
1010
     * @param stdClass $data
1011
     * @param string $fromVersion
1012
     */
1013
    public static function importInstance($data, $fromVersion)
1014
    {
1015
        if (isset($data->what)) {
1016
            unset($data->what);
1017
        }
1018
        if (isset($data->submitbutton)) {
1019
            unset($data->submitbutton);
1020
        }
1021
        if (isset($data->id)) {
1022
            unset($data->id);
1023
        }
1024
        if (isset($data->vid)) {
1025
            unset($data->vid);
1026
        }
1027
        if (isset($data->testconnection)) {
1028
            unset($data->testconnection);
1029
        }
1030
        if (isset($data->testdatapath)) {
1031
            unset($data->testdatapath);
1032
        }
1033
1034
        $fromCoursePath = $data->course_path;
1035
        $fromHomePath = $data->home_path;
1036
        $fromUploadPath = $data->upload_path;
1037
1038
        unset($data->course_path);
1039
        unset($data->home_path);
1040
        unset($data->upload_path);
1041
1042
        $newDatabase = clone $data;
1043
        $newDatabase->main_database = $newDatabase->import_to_main_database;
1044
        $newDatabase->db_user = $newDatabase->import_to_db_user;
1045
        $newDatabase->db_password = $newDatabase->import_to_db_password;
1046
        $newDatabase->db_host = $newDatabase->import_to_db_host;
1047
1048
        unset($newDatabase->import_to_main_database);
1049
        unset($newDatabase->import_to_db_user);
1050
        unset($newDatabase->import_to_db_password);
1051
        unset($newDatabase->import_to_db_host);
1052
1053
        unset($data->import_to_main_database);
1054
        unset($data->import_to_db_user);
1055
        unset($data->import_to_db_password);
1056
        unset($data->import_to_db_host);
1057
1058
        $data->lastcron = 0;
1059
        $data->lastcrongap = 0;
1060
        $data->croncount = 0;
1061
1062
        $mainDatabase = api_get_configuration_value('main_database');
1063
1064
        if ($mainDatabase == $data->main_database) {
1065
            Display::addFlash(
1066
                Display::return_message('You cannot use the same database as the chamilo master', 'error')
1067
            );
1068
1069
            return false;
1070
        }
1071
1072
        self::ctrace('Registering: '.$data->root_web);
1073
1074
        $table = Database::get_main_table('vchamilo');
1075
        $sql = "SELECT * FROM $table 
1076
                WHERE root_web = '".Database::escape_string($data->root_web)."'";
1077
        $result = Database::query($sql);
1078
        $id = null;
1079
        if (Database::num_rows($result)) {
1080
            Display::addFlash(
1081
                Display::return_message('Instance was already added: '.$data->root_web, 'error')
1082
            );
1083
            return false;
1084
        } else {
1085
            /** @var EntityManager $em */
1086
            $em = Virtual::getConnectionFromInstance($data, true);
1087
            if ($em) {
1088
                $connection = $em->getConnection();
1089
                $statement = $connection->query('SELECT * FROM settings_current');
1090
                $settings = $statement->fetchAll();
1091
                $settings = array_column(
1092
                    $settings,
1093
                    'selected_value',
1094
                    'variable'
1095
                );
1096
                $institution = $settings['Institution'];
1097
                $siteName = $settings['siteName'];
1098
                $newDatabase->sitename = $siteName;
1099
                $newDatabase->institution = $institution;
1100
                $slug = $newDatabase->slug = $data->slug = Virtual::getSlugFromUrl($data->root_web);
1101
                $id = Database::insert($table, (array)$newDatabase);
1102
            }
1103
        }
1104
1105
        if (!$id) {
1106
            var_dump($data);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($data); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
1107
            throw new Exception('Was not registered');
1108
        }
1109
1110
        if (empty($slug)) {
1111
            throw new Exception('Slug is empty');
1112
        }
1113
1114
        self::createDirsFromSlug($slug);
1115
        $databaseCreated = Virtual::createDatabase($newDatabase);
1116
        if (!$databaseCreated) {
1117
            Display::addFlash(
1118
                Display::return_message('Error while creating a DB', 'error')
1119
            );
1120
            return false;
1121
        }
1122
1123
        $coursePath = self::getConfig('vchamilo', 'course_real_root').'/'.$slug;
1124
        $homePath = self::getConfig('vchamilo', 'home_real_root').'/'.$slug;
1125
        $uploadPath = self::getConfig('vchamilo', 'upload_real_root').'/'.$slug;
1126
1127
        $dumpFile = api_get_path(SYS_ARCHIVE_PATH).uniqid($data->main_database.'_dump_', true).'.sql';
1128
        self::ctrace('Create backup from "'.$data->main_database.'" here: '.$dumpFile.' ');
1129
        Virtual::backupDatabase($data, $dumpFile);
1130
1131
        $sqlcmd = Virtual::getDatabaseDumpCmd($newDatabase);
1132
        $sqlcmd = str_replace('%DATABASE%', $newDatabase->main_database, $sqlcmd);
1133
        $import = $sqlcmd.$dumpFile;
1134
1135
        // Execute the command.
1136
        if (!defined('CLI_SCRIPT')) {
1137
            putenv('LANG=en_US.utf-8');
1138
        }
1139
1140
        // ensure utf8 is correctly handled by php exec()
1141
        // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
1142
        $result = exec($import, $output, $return);
1143
1144
        self::ctrace('Restore backup here "'.$newDatabase->main_database.'" : <br />'.$import.' ');
1145
        self::ctrace($result);
1146
1147
        $command = new \Chash\Command\Installation\UpgradeDatabaseCommand();
1148
        // Creates the helper set
1149
        $helperSet = \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($em);
1150
1151
        $helpers = array(
1152
            'configuration' => new Chash\Helpers\ConfigurationHelper(),
1153
            'dialog' => new \Symfony\Component\Console\Helper\QuestionHelper(),
1154
        );
1155
1156
        foreach ($helpers as $name => $helper) {
1157
            $helperSet->set($helper, $name);
1158
        }
1159
1160
        $command->setHelperSet($helperSet);
1161
1162
        $tmpFile = tmpfile();
1163
        $outputStream = new \Symfony\Component\Console\Output\BufferedOutput($tmpFile);
1164
1165
        $arguments = array(
1166
            'from-version' => $fromVersion, // @todo change value
1167
            'to-version' => '1.11.x',
1168
            'host' => $newDatabase->db_host,
1169
            'username' => $newDatabase->db_user,
1170
            'password' => $newDatabase->db_password,
1171
            'db_name' => $newDatabase->main_database,
1172
            'root_sys' => api_get_configuration_value('root_sys')
1173
        );
1174
1175
        $input = new ArrayInput($arguments);
1176
        $command->run($input, $outputStream);
1177
1178
        error_log($outputStream->fetch());
1179
1180
        if (file_exists($dumpFile)) {
1181
            unlink($dumpFile);
1182
        }
1183
1184
        // Course
1185
        self::ctrace("Copy from '$fromCoursePath' to backup '$coursePath' ");
1186
        copyDirTo(
1187
            self::chopLastSlash($fromCoursePath),
1188
            self::chopLastSlash($coursePath),
1189
            false
1190
        );
1191
1192
        // Home
1193
        self::ctrace("Copy from '$fromHomePath' to backup '$homePath' ");
1194
        copyDirTo(
1195
            self::chopLastSlash($fromHomePath),
1196
            self::chopLastSlash($homePath),
1197
            false
1198
        );
1199
1200
        // Upload
1201
        self::ctrace("Copy from '$fromUploadPath' to backup '$uploadPath' ");
1202
        copyDirTo(
1203
            self::chopLastSlash($fromUploadPath),
1204
            self::chopLastSlash($uploadPath),
1205
            false
1206
        );
1207
1208
        self::ctrace("Finished");
1209
    }
1210
1211
    /**
1212
     * @param stdClass $params
1213
     */
1214
    public static function upgradeInstance($params)
1215
    {
1216
        $connection = Virtual::getConnectionFromInstance($params);
1217
        $statement = $connection->query('SELECT * FROM settings_current');
1218
        $settings = $statement->fetchAll();
1219
        $settings = array_column($settings, 'selected_value', 'variable');
1220
        $settings['data_base'];
1221
    }
1222
1223
    /**
1224
     * @param string $slug
1225
     *
1226
     * @return string
1227
     */
1228
    public static function createDirsFromSlug($slug)
1229
    {
1230
        // We continue with physical creation
1231
1232
        // Create course directory for operations.
1233
        // this is very important here (DO NOT USE api_get_path() !!) because storage may be remotely located
1234
        $absAlternateCourse = Virtual::getConfig('vchamilo', 'course_real_root');
1235
        $courseDir = $absAlternateCourse.'/'.$slug;
1236
1237
        if (!is_dir($courseDir)) {
1238
            self::ctrace("Creating physical course dir in $courseDir");
1239
            mkdir($courseDir, 0777, true);
1240
            // initiate default index
1241
            $indexFile = $courseDir.'/index.html';
1242
            if ($indexFile) {
1243
                file_put_contents($indexFile, self::getDefaultCourseIndexFragment());
1244
            }
1245
1246
            $htaccessFile = $courseDir.'/.htaccess';
1247
            if ($htaccessFile) {
1248
                file_put_contents($htaccessFile, self::getHtaccessFragment($slug));
1249
            }
1250
        }
1251
1252
        $absAlternateHome = Virtual::getConfig('vchamilo', 'home_real_root');
1253
        $absAlternateArchive = Virtual::getConfig('vchamilo', 'archive_real_root');
1254
        $absAlternateUpload = Virtual::getConfig('vchamilo', 'upload_real_root');
1255
1256
        // absalternatehome is a vchamilo config setting that tells where the
1257
        // real physical storage for home pages are.
1258
        $homeDir = $absAlternateHome.'/'.$slug;
1259
        $archiveDir = $absAlternateArchive.'/'.$slug;
1260
        $uploadDir = $absAlternateUpload.'/'.$slug;
1261
1262
        $dirs = [
1263
            $homeDir,
1264
            $archiveDir,
1265
            $uploadDir
1266
        ];
1267
1268
        foreach ($dirs as $dir) {
1269
            self::ctrace("Making dir as $dir");
1270
1271
            if (!is_dir($dir)) {
1272
                if (!mkdir($dir, 0777, true)) {
1273
                    self::ctrace("Error creating dir $dir \n");
1274
                }
1275
            }
1276
        }
1277
    }
1278
1279
    /**
1280
     * @param $id
1281
     * @return array|mixed
1282
     */
1283
    public static function getInstance($id)
1284
    {
1285
        $vhost = new stdClass();
1286
        if ($id) {
1287
            $id = (int) $id;
1288
            $sql = "SELECT * FROM vchamilo WHERE id = $id";
1289
            $result = Database::query($sql);
1290
            $vhost =  (object) Database::fetch_array($result, 'ASSOC');
1291
        }
1292
1293
        return $vhost;
1294
    }
1295
1296
    /**
1297
     * @param stdClass $instance
1298
     *
1299
     * @return bool|string returns the original version of the app
1300
     */
1301
    public static function canBeUpgraded($instance)
1302
    {
1303
        $connection = Virtual::getConnectionFromInstance($instance);
1304
        $statement = $connection->query('SELECT * FROM settings_current WHERE variable = "chamilo_database_version"');
1305
        $settings = $statement->fetchAll();
1306
        $settings = array_column($settings, 'selected_value', 'variable');
1307
        $version = $settings['chamilo_database_version'];
1308
        $versionParts = explode('.', $version);
1309
        $version = implode('.', [$versionParts[0], $versionParts[1], '0']);
1310
1311
        $currentVersion = api_get_setting('chamilo_database_version');
1312
        $versionParts = explode('.', $currentVersion);
1313
        $currentVersion = implode('.', [$versionParts[0], $versionParts[1], '0']);
1314
1315
        if (version_compare($version, $currentVersion, '<')) {
1316
            return $version;
1317
        }
1318
1319
        return false;
1320
    }
1321
1322
    /**
1323
     * @return array
1324
     */
1325
    public static function getEncryptList()
1326
    {
1327
        $encryptList = [
1328
            'bcrypt',
1329
            'sha1',
1330
            'md5',
1331
            'none'
1332
        ];
1333
1334
        return array_combine($encryptList, $encryptList);
1335
    }
1336
1337
1338
}
1339
1340