Passed
Push — master ( 2cc8c4...2ca18e )
by Julito
13:12
created

checkReadable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\DataFixtures\LanguageFixtures;
6
use Chamilo\CoreBundle\Entity\AccessUrl;
7
use Chamilo\CoreBundle\Entity\BranchSync;
8
use Chamilo\CoreBundle\Entity\Group;
9
use Chamilo\CoreBundle\Entity\TicketCategory;
10
use Chamilo\CoreBundle\Entity\TicketPriority;
11
use Chamilo\CoreBundle\Entity\TicketProject;
12
use Chamilo\CoreBundle\Entity\User;
13
use Chamilo\CoreBundle\Framework\Container;
14
use Chamilo\CoreBundle\Repository\GroupRepository;
15
use Chamilo\CoreBundle\Repository\Node\AccessUrlRepository;
16
use Chamilo\CoreBundle\Repository\Node\UserRepository;
17
use Chamilo\CoreBundle\ToolChain;
18
use Doctrine\Migrations\Configuration\Connection\ExistingConnection;
19
use Doctrine\Migrations\Configuration\Migration\PhpFile;
20
use Doctrine\Migrations\DependencyFactory;
21
use Doctrine\Migrations\Query\Query;
22
use Doctrine\ORM\EntityManager;
23
use Symfony\Component\DependencyInjection\Container as SymfonyContainer;
24
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
25
26
/*
27
 * Chamilo LMS
28
 * This file contains functions used by the install and upgrade scripts.
29
 *
30
 * Ideas for future additions:
31
 * - a function get_old_version_settings to retrieve the config file settings
32
 *   of older versions before upgrading.
33
 */
34
define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
35
define('USERNAME_MAX_LENGTH', 100);
36
37
/**
38
 * This function detects whether the system has been already installed.
39
 * It should be used for prevention from second running the installation
40
 * script and as a result - destroying a production system.
41
 *
42
 * @return bool The detected result;
43
 *
44
 * @author Ivan Tcholakov, 2010;
45
 */
46
function isAlreadyInstalledSystem()
47
{
48
    global $new_version, $_configuration;
49
50
    if (empty($new_version)) {
51
        return true; // Must be initialized.
52
    }
53
54
    $current_config_file = api_get_path(CONFIGURATION_PATH).'configuration.php';
55
    if (!file_exists($current_config_file)) {
56
        return false; // Configuration file does not exist, install the system.
57
    }
58
    require $current_config_file;
59
60
    $current_version = null;
61
    if (isset($_configuration['system_version'])) {
62
        $current_version = trim($_configuration['system_version']);
63
    }
64
65
    // If the current version is old, upgrading is assumed, the installer goes ahead.
66
    return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
67
}
68
69
/**
70
 * This function checks if a php extension exists or not and returns an HTML status string.
71
 *
72
 * @param string $extensionName Name of the PHP extension to be checked
73
 * @param string $returnSuccess Text to show when extension is available (defaults to 'Yes')
74
 * @param string $returnFailure Text to show when extension is available (defaults to 'No')
75
 * @param bool   $optional      Whether this extension is optional (then show unavailable text in orange rather than
76
 *                              red)
77
 * @param string $enabledTerm   If this string is not null, then use to check if the corresponding parameter is = 1.
78
 *                              If not, mention it's present but not enabled. For example, for opcache, this should be
79
 *                              'opcache.enable'
80
 *
81
 * @return string HTML string reporting the status of this extension. Language-aware.
82
 *
83
 * @author  Christophe Gesch??
84
 * @author  Patrick Cool <[email protected]>, Ghent University
85
 * @author  Yannick Warnier <[email protected]>
86
 */
87
function checkExtension(
88
    $extensionName,
89
    $returnSuccess = 'Yes',
90
    $returnFailure = 'No',
91
    $optional = false,
92
    $enabledTerm = ''
93
) {
94
    if (extension_loaded($extensionName)) {
95
        if (!empty($enabledTerm)) {
96
            $isEnabled = ini_get($enabledTerm);
97
            if ('1' == $isEnabled) {
98
                return Display::label($returnSuccess, 'success');
99
            } else {
100
                if ($optional) {
101
                    return Display::label(get_lang('Extension installed but not enabled'), 'warning');
102
                }
103
104
                return Display::label(get_lang('Extension installed but not enabled'), 'important');
105
            }
106
        }
107
108
        return Display::label($returnSuccess, 'success');
109
    } else {
110
        if ($optional) {
111
            return Display::label($returnFailure, 'warning');
112
        }
113
114
        return Display::label($returnFailure, 'important');
115
    }
116
}
117
118
/**
119
 * This function checks whether a php setting matches the recommended value.
120
 *
121
 * @param string $phpSetting       A PHP setting to check
122
 * @param string $recommendedValue A recommended value to show on screen
123
 * @param mixed  $returnSuccess    What to show on success
124
 * @param mixed  $returnFailure    What to show on failure
125
 *
126
 * @return string A label to show
127
 *
128
 * @author Patrick Cool <[email protected]>, Ghent University
129
 */
130
function checkPhpSetting(
131
    $phpSetting,
132
    $recommendedValue,
133
    $returnSuccess = false,
134
    $returnFailure = false
135
) {
136
    $currentPhpValue = getPhpSetting($phpSetting);
137
    if ($currentPhpValue == $recommendedValue) {
138
        return Display::label($currentPhpValue.' '.$returnSuccess, 'success');
139
    }
140
141
    return Display::label($currentPhpValue.' '.$returnSuccess, 'important');
142
}
143
144
/**
145
 * This function return the value of a php.ini setting if not "" or if exists,
146
 * otherwise return false.
147
 *
148
 * @param string $phpSetting The name of a PHP setting
149
 *
150
 * @return mixed The value of the setting, or false if not found
151
 */
152
function checkPhpSettingExists($phpSetting)
153
{
154
    if ('' != ini_get($phpSetting)) {
155
        return ini_get($phpSetting);
156
    }
157
158
    return false;
159
}
160
161
/**
162
 * Returns a textual value ('ON' or 'OFF') based on a requester 2-state ini- configuration setting.
163
 *
164
 * @param string $val a php ini value
165
 *
166
 * @return bool ON or OFF
167
 *
168
 * @author Joomla <http://www.joomla.org>
169
 */
170
function getPhpSetting($val)
171
{
172
    $value = ini_get($val);
173
    switch ($val) {
174
        case 'display_errors':
175
            global $originalDisplayErrors;
176
            $value = $originalDisplayErrors;
177
            break;
178
    }
179
180
    return '1' == $value ? 'ON' : 'OFF';
181
}
182
183
/**
184
 * This function returns a string "true" or "false" according to the passed parameter.
185
 *
186
 * @param int $var The variable to present as text
187
 *
188
 * @return string the string "true" or "false"
189
 *
190
 * @author Christophe Gesch??
191
 */
192
function trueFalse($var)
193
{
194
    return $var ? 'true' : 'false';
195
}
196
197
/**
198
 * This function checks if the given folder is writable.
199
 *
200
 * @param string $folder     Full path to a folder
201
 * @param bool   $suggestion Whether to show a suggestion or not
202
 *
203
 * @return string
204
 */
205
function check_writable($folder, $suggestion = false)
206
{
207
    if (is_writable($folder)) {
208
        return Display::label(get_lang('Writable'), 'success');
209
    } else {
210
        if ($suggestion) {
211
            return Display::label(get_lang('Not writable'), 'info');
212
        } else {
213
            return Display::label(get_lang('Not writable'), 'important');
214
        }
215
    }
216
}
217
218
/**
219
 * This function checks if the given folder is readable.
220
 *
221
 * @param string $folder     Full path to a folder
222
 * @param bool   $suggestion Whether to show a suggestion or not
223
 *
224
 * @return string
225
 */
226
function checkReadable($folder, $suggestion = false)
227
{
228
    if (is_readable($folder)) {
229
        return Display::label(get_lang('Readable'), 'success');
230
    } else {
231
        if ($suggestion) {
232
            return Display::label(get_lang('Not readable'), 'info');
233
        } else {
234
            return Display::label(get_lang('Not readable'), 'important');
235
        }
236
    }
237
}
238
239
/**
240
 * We assume this function is called from install scripts that reside inside the install folder.
241
 */
242
function set_file_folder_permissions()
243
{
244
    @chmod('.', 0755); //set permissions on install dir
245
    @chmod('..', 0755); //set permissions on parent dir of install dir
246
}
247
248
/**
249
 * Write the main system config file.
250
 *
251
 * @param string $path Path to the config file
252
 */
253
function writeSystemConfigFile($path)
254
{
255
    $content = file_get_contents(__DIR__.'/'.SYSTEM_CONFIG_FILENAME);
256
    $config['{DATE_GENERATED}'] = date('r');
257
    $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
258
259
    foreach ($config as $key => $value) {
260
        $content = str_replace($key, $value, $content);
261
    }
262
    $fp = @fopen($path, 'w');
263
264
    if (!$fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
265
        echo '<strong>
266
                <font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
267
                <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
268
                You probably do not have write access on Chamilo root directory,
269
                i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
270
                Your problems can be related on two possible causes:<br />
271
                <ul>
272
                  <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
273
                  <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>.
274
                  If possible, try to switch it off.</li>
275
                </ul>
276
                <a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
277
                Please go back to step 5.
278
                <p><input type="submit" name="step5" value="&lt; Back" /></p>
279
                </td></tr></table></form></body></html>';
280
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
281
    }
282
283
    fwrite($fp, $content);
284
    fclose($fp);
285
}
286
287
/**
288
 * This function returns the value of a parameter from the configuration file.
289
 *
290
 * WARNING - this function relies heavily on global variables $updateFromConfigFile
291
 * and $configFile, and also changes these globals. This can be rewritten.
292
 *
293
 * @param string $param      the parameter of which the value is returned
294
 * @param string $updatePath If we want to give the path rather than take it from POST
295
 *
296
 * @return string the value of the parameter
297
 *
298
 * @author Olivier Brouckaert
299
 * @author Reworked by Ivan Tcholakov, 2010
300
 */
301
function get_config_param($param, $updatePath = '')
302
{
303
    global $updateFromConfigFile;
304
    if (empty($updatePath) && !empty($_POST['updatePath'])) {
305
        $updatePath = $_POST['updatePath'];
306
    }
307
308
    if (empty($updatePath)) {
309
        $updatePath = api_get_path(SYMFONY_SYS_PATH);
310
    }
311
    $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath)));
312
313
    if (empty($updateFromConfigFile)) {
314
        // If update from previous install was requested,
315
        if (file_exists($updatePath.'app/config/configuration.php')) {
316
            $updateFromConfigFile = 'app/config/configuration.php';
317
        } else {
318
            // Give up recovering.
319
            return null;
320
        }
321
    }
322
323
    if (file_exists($updatePath.$updateFromConfigFile) &&
324
        !is_dir($updatePath.$updateFromConfigFile)
325
    ) {
326
        require $updatePath.$updateFromConfigFile;
327
        $config = new Laminas\Config\Config($_configuration);
328
329
        return $config->get($param);
330
    }
331
332
    error_log('Config array could not be found in get_config_param()', 0);
333
334
    return null;
335
}
336
337
/**
338
 * Gets a configuration parameter from the database. Returns returns null on failure.
339
 *
340
 * @param string $param Name of param we want
341
 *
342
 * @return mixed The parameter value or null if not found
343
 */
344
function get_config_param_from_db($param = '')
345
{
346
    $param = Database::escape_string($param);
347
348
    if (false !== ($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'"))) {
349
        if (Database::num_rows($res) > 0) {
350
            $row = Database::fetch_array($res);
351
352
            return $row['selected_value'];
353
        }
354
    }
355
356
    return null;
357
}
358
359
/**
360
 * Connect to the database and returns the entity manager.
361
 *
362
 * @param string $host
363
 * @param string $username
364
 * @param string $password
365
 * @param string $databaseName
366
 * @param int    $port
367
 *
368
 * @return \Database
369
 */
370
function connectToDatabase(
371
    $host,
372
    $username,
373
    $password,
374
    $databaseName,
375
    $port = 3306
376
) {
377
    $database = new \Database();
378
    $database->connect(
379
        [
380
            'driver' => 'pdo_mysql',
381
            'host' => $host,
382
            'port' => $port,
383
            'user' => $username,
384
            'password' => $password,
385
            'dbname' => $databaseName,
386
        ]
387
    );
388
389
    return $database;
390
}
391
392
/**
393
 * This function prints class=active_step $current_step=$param.
394
 *
395
 * @param int $param A step in the installer process
396
 *
397
 * @author Patrick Cool <[email protected]>, Ghent University
398
 */
399
function step_active($param)
400
{
401
    global $current_step;
402
    if ($param == $current_step) {
403
        echo 'active';
404
    }
405
}
406
407
/**
408
 * This function displays the Step X of Y -.
409
 *
410
 * @return string String that says 'Step X of Y' with the right values
411
 */
412
function display_step_sequence()
413
{
414
    global $current_step;
415
416
    return get_lang('Step'.$current_step).' &ndash; ';
417
}
418
419
/**
420
 * Displays a drop down box for selection the preferred language.
421
 */
422
function display_language_selection_box($name = 'language_list', $default_language = 'en_US')
423
{
424
    // Displaying the box.
425
    return Display::select(
426
        'language_list',
427
        array_column(LanguageFixtures::getLanguages(),'english_name', 'isocode'),
428
        $default_language,
429
        ['class' => 'form-control'],
430
        false
431
    );
432
}
433
434
/**
435
 * This function displays a language dropdown box so that the installatioin
436
 * can be done in the language of the user.
437
 */
438
function display_language_selection()
439
{
440
    ?>
441
        <div class="install-icon">
442
            <img width="150px;" src="chamilo-install.svg"/>
443
        </div>
444
        <h2 class="text-2xl">
445
            <?php echo display_step_sequence(); ?>
446
            <?php echo get_lang('Installation Language'); ?>
447
        </h2>
448
        <label for="language_list"><?php echo get_lang('Please select installation language'); ?></label>
449
        <div class="form-group">
450
            <?php echo display_language_selection_box('language_list', api_get_language_isocode()); ?>
451
        </div>
452
        <button type="submit" name="step1" class="btn btn-success" value="<?php echo get_lang('Next'); ?>">
453
            <em class="fa fa-forward"> </em>
454
            <?php echo get_lang('Next'); ?>
455
        </button>
456
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
457
        <div class="RequirementHeading">
458
            <?php echo get_lang('Cannot find your language in the list? Contact us at [email protected] to contribute as a translator.'); ?>
459
        </div>
460
<?php
461
}
462
463
/**
464
 * This function displays the requirements for installing Chamilo.
465
 *
466
 * @param string $installType
467
 * @param bool   $badUpdatePath
468
 * @param bool   $badUpdatePath
469
 * @param string $updatePath         The updatePath given (if given)
470
 * @param array  $upgradeFromVersion The different subversions from version 1.9
471
 *
472
 * @author unknow
473
 * @author Patrick Cool <[email protected]>, Ghent University
474
 */
475
function display_requirements(
476
    $installType,
477
    $badUpdatePath,
478
    $updatePath = '',
479
    $upgradeFromVersion = []
480
) {
481
    global $_setting, $originalMemoryLimit;
482
483
    $dir = api_get_path(SYS_ARCHIVE_PATH).'temp/';
484
    $fileToCreate = 'test';
485
486
    $perms_dir = [0777, 0755, 0775, 0770, 0750, 0700];
487
    $perms_fil = [0666, 0644, 0664, 0660, 0640, 0600];
488
    $course_test_was_created = false;
489
    $dir_perm_verified = 0777;
490
491
    foreach ($perms_dir as $perm) {
492
        $r = @mkdir($dir, $perm);
493
        if (true === $r) {
494
            $dir_perm_verified = $perm;
495
            $course_test_was_created = true;
496
            break;
497
        }
498
    }
499
500
    $fil_perm_verified = 0666;
501
    $file_course_test_was_created = false;
502
    if (is_dir($dir)) {
503
        foreach ($perms_fil as $perm) {
504
            if (true == $file_course_test_was_created) {
505
                break;
506
            }
507
            $r = @touch($dir.'/'.$fileToCreate, $perm);
508
            if (true === $r) {
509
                $fil_perm_verified = $perm;
510
                $file_course_test_was_created = true;
511
            }
512
        }
513
    }
514
515
    @unlink($dir.'/'.$fileToCreate);
516
    @rmdir($dir);
517
518
    echo '<h2 class="install-title">'.display_step_sequence().get_lang('Requirements').'</h2>';
519
    echo '<div class="RequirementText">';
520
    echo '<strong>'.get_lang('Please read the following requirements thoroughly.').'</strong><br />';
521
    echo get_lang('For more details').'
522
        <a href="../../documentation/installation_guide.html" target="_blank">'.
523
        get_lang('Read the installation guide').'</a>.<br />'."\n";
524
525
    if ('update' == $installType) {
526
        echo get_lang(
527
            'If you plan to upgrade from an older version of Chamilo, you might want to <a href="../../documentation/changelog.html" target="_blank">have a look at the changelog</a> to know what\'s new and what has been changed').'<br />';
528
    }
529
    echo '</div>';
530
531
    //  SERVER REQUIREMENTS
532
    echo '<h4 class="install-subtitle">'.get_lang('Server requirements').'</h4>';
533
    $timezone = checkPhpSettingExists('date.timezone');
534
    if (!$timezone) {
535
        echo "<div class='alert alert-warning'>
536
            <i class=\"fa fa-exclamation-triangle\" aria-hidden=\"true\"></i>&nbsp;".
537
            get_lang('We have detected that your PHP installation does not define the date.timezone setting. This is a requirement of Chamilo. Please make sure it is configured by checking your php.ini configuration, otherwise you will run into problems. We warned you!').'</div>';
538
    }
539
540
    echo '<div class="install-requirement">'.get_lang('Server requirementsInfo').'</div>';
541
    echo '<div class="table-responsive">';
542
    echo '<table class="table table-bordered table-sm">
543
            <tr>
544
                <td class="requirements-item">'.get_lang('PHP version').' >= '.REQUIRED_PHP_VERSION.'</td>
545
                <td class="requirements-value">';
546
    if (version_compare(phpversion(), REQUIRED_PHP_VERSION, '>=') > 1) {
547
        echo '<strong class="text-danger">'.get_lang('PHP versionError').'</strong>';
548
    } else {
549
        echo '<strong class="text-success">'.get_lang('PHP versionOK').' '.phpversion().'</strong>';
550
    }
551
    echo '</td>
552
            </tr>
553
            <tr>
554
                <td class="requirements-item">
555
                    <a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a>
556
                    '.get_lang('Support').'</td>
557
                <td class="requirements-value">'.
558
        checkExtension('session', get_lang('Yes'), get_lang('Sessions extension not available')).'</td>
559
            </tr>
560
            <tr>
561
                <td class="requirements-item">
562
                    <a href="http://php.net/manual/en/book.mysql.php" target="_blank">pdo_mysql</a> '.get_lang('Support').'</td>
563
                <td class="requirements-value">'.
564
                    checkExtension('pdo_mysql', get_lang('Yes'), get_lang('MySQL extension not available')).'</td>
565
            </tr>
566
            <tr>
567
                <td class="requirements-item">
568
                    <a href="http://php.net/manual/en/book.zip.php" target="_blank">Zip</a> '.get_lang('Support').'</td>
569
                <td class="requirements-value">'.
570
                checkExtension('zip', get_lang('Yes'), get_lang('Extension not available')).'</td>
571
            </tr>
572
            <tr>
573
                <td class="requirements-item">
574
                    <a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('Support').'</td>
575
                <td class="requirements-value">'.
576
                checkExtension('zlib', get_lang('Yes'), get_lang('Zlib extension not available')).'</td>
577
            </tr>
578
            <tr>
579
                <td class="requirements-item">
580
                    <a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('Support').'</td>
581
                <td class="requirements-value">'.
582
                    checkExtension('pcre', get_lang('Yes'), get_lang('PCRE extension not available')).'</td>
583
            </tr>
584
            <tr>
585
                <td class="requirements-item">
586
                    <a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('Support').'</td>
587
                <td class="requirements-value">'.
588
                    checkExtension('xml', get_lang('Yes'), get_lang('No')).'</td>
589
            </tr>
590
            <tr>
591
                <td class="requirements-item">
592
                    <a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('Support').'</td>
593
                <td class="requirements-value">'.checkExtension('intl', get_lang('Yes'), get_lang('No')).'</td>
594
            </tr>
595
               <tr>
596
                <td class="requirements-item">
597
                    <a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('Support').'</td>
598
                <td class="requirements-value">'.checkExtension('json', get_lang('Yes'), get_lang('No')).'</td>
599
            </tr>
600
             <tr>
601
                <td class="requirements-item">
602
                    <a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('Support').'</td>
603
                <td class="requirements-value">'.
604
                    checkExtension('gd', get_lang('Yes'), get_lang('GD Extension not available')).'</td>
605
            </tr>
606
            <tr>
607
                <td class="requirements-item">
608
                    <a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>'.get_lang('Support').'</td>
609
                <td class="requirements-value">'.
610
                checkExtension('curl', get_lang('Yes'), get_lang('No')).'</td>
611
            </tr>
612
            <tr>
613
                <td class="requirements-item">
614
                    <a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('Support').'</td>
615
                <td class="requirements-value">'.
616
                    checkExtension('mbstring', get_lang('Yes'), get_lang('MBString extension not available'), true).'</td>
617
            </tr>
618
           <tr>
619
                <td class="requirements-item">
620
                    <a href="http://php.net/manual/en/book.exif.php" target="_blank">Exif</a> '.get_lang('Support').'</td>
621
                <td class="requirements-value">'.
622
                    checkExtension('exif', get_lang('Yes'), get_lang('Exif extension not available'), true).'</td>
623
            </tr>
624
            <tr>
625
                <td class="requirements-item">
626
                    <a href="http://php.net/opcache" target="_blank">Zend OpCache</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
627
                <td class="requirements-value">'.
628
                    checkExtension('Zend OPcache', get_lang('Yes'), get_lang('No'), true, 'opcache.enable').'</td>
629
            </tr>
630
            <tr>
631
                <td class="requirements-item">
632
                    <a href="http://php.net/apcu" target="_blank">APCu</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
633
                <td class="requirements-value">'.
634
                    checkExtension('apcu', get_lang('Yes'), get_lang('No'), true, 'apc.enabled').'</td>
635
            </tr>
636
            <tr>
637
                <td class="requirements-item">
638
                    <a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
639
                <td class="requirements-value">'.
640
                    checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
641
            </tr>
642
            <tr>
643
                <td class="requirements-item">
644
                        <a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
645
                <td class="requirements-value">'.
646
                checkExtension('ldap', get_lang('Yes'), get_lang('LDAP Extension not available'), true).'</td>
647
            </tr>
648
            <tr>
649
                <td class="requirements-item">
650
                    <a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
651
                <td class="requirements-value">'.
652
                    checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
653
            </tr>
654
        </table>';
655
    echo '</div>';
656
657
    // RECOMMENDED SETTINGS
658
    // Note: these are the settings for Joomla, does this also apply for Chamilo?
659
    // Note: also add upload_max_filesize here so that large uploads are possible
660
    echo '<h4 class="install-subtitle">'.get_lang('(recommended) settings').'</h4>';
661
    echo '<div class="install-requirement">'.get_lang('(recommended) settingsInfo').'</div>';
662
    echo '<div class="table-responsive">';
663
    echo '<table class="table table-bordered table-sm">
664
            <tr>
665
                <th>'.get_lang('Setting').'</th>
666
                <th>'.get_lang('(recommended)').'</th>
667
                <th>'.get_lang('Currently').'</th>
668
            </tr>
669
            <tr>
670
                <td class="requirements-item">
671
                <a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
672
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
673
                <td class="requirements-value">'.checkPhpSetting('display_errors', 'OFF').'</td>
674
            </tr>
675
            <tr>
676
                <td class="requirements-item">
677
                <a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
678
                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
679
                <td class="requirements-value">'.checkPhpSetting('file_uploads', 'ON').'</td>
680
            </tr>
681
            <tr>
682
                <td class="requirements-item">
683
                <a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
684
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
685
                <td class="requirements-value">'.checkPhpSetting('session.auto_start', 'OFF').'</td>
686
            </tr>
687
            <tr>
688
                <td class="requirements-item">
689
                <a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
690
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
691
                <td class="requirements-value">'.checkPhpSetting('short_open_tag', 'OFF').'</td>
692
            </tr>
693
            <tr>
694
                <td class="requirements-item">
695
                    <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
696
                <td class="requirements-recommended">'.
697
                    Display::label('ON', 'success').'</td>
698
                <td class="requirements-value">'.checkPhpSetting('session.cookie_httponly', 'ON').'</td>
699
            </tr>
700
            <tr>
701
                <td class="requirements-item">
702
                    <a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
703
                <td class="requirements-recommended">'.
704
                    Display::label('>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M', 'success').'</td>
705
                <td class="requirements-value">'.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'</td>
706
            </tr>
707
            <tr>
708
                <td class="requirements-item">
709
                    <a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
710
                <td class="requirements-recommended">'.
711
                Display::label('>= '.REQUIRED_MIN_POST_MAX_SIZE.'M', 'success').'</td>
712
                <td class="requirements-value">'.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'</td>
713
            </tr>
714
            <tr>
715
                <td class="requirements-item">
716
                    <a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
717
                <td class="requirements-recommended">'.
718
                    Display::label('>= '.REQUIRED_MIN_MEMORY_LIMIT.'M', 'success').'</td>
719
                <td class="requirements-value">'.compare_setting_values($originalMemoryLimit, REQUIRED_MIN_MEMORY_LIMIT).'</td>
720
            </tr>
721
          </table>';
722
    echo '</div>';
723
724
    // DIRECTORY AND FILE PERMISSIONS
725
    echo '<h4 class="install-subtitle">'.get_lang('Directory and files permissions').'</h4>';
726
    echo '<div class="install-requirement">'.get_lang('Directory and files permissionsInfo').'</div>';
727
    echo '<div class="table-responsive">';
728
729
    $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified;
730
    $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified;
731
732
    $dir_perm = Display::label('0'.decoct($dir_perm_verified), 'info');
733
    $file_perm = Display::label('0'.decoct($fil_perm_verified), 'info');
734
735
    $oldConf = '';
736
    if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) {
737
        $oldConf = '<tr>
738
            <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'inc/conf</td>
739
            <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').'</td>
740
        </tr>';
741
    }
742
    $basePath = api_get_path(SYMFONY_SYS_PATH);
743
    echo '<table class="table table-bordered table-sm">
744
            '.$oldConf.'
745
            <tr>
746
                <td class="requirements-item">'.$basePath.'var/</td>
747
                <td class="requirements-value">'.check_writable($basePath.'var').'</td>
748
            </tr>
749
            <tr>
750
                <td class="requirements-item">'.$basePath.'.env.local</td>
751
                <td class="requirements-value">'.checkCanCreateFile($basePath.'.env.local').'</td>
752
            </tr>
753
            <tr>
754
                <td class="requirements-item">'.$basePath.'config/</td>
755
                <td class="requirements-value">'.check_writable($basePath.'config').'</td>
756
            </tr>
757
            <tr>
758
                <td class="requirements-item">'.get_lang('Permissions for new directories').'</td>
759
                <td class="requirements-value">'.$dir_perm.' </td>
760
            </tr>
761
            <tr>
762
                <td class="requirements-item">'.get_lang('Permissions for new files').'</td>
763
                <td class="requirements-value">'.$file_perm.' </td>
764
            </tr>
765
        </table>';
766
    echo '</div>';
767
768
    if ('update' === $installType && (empty($updatePath) || $badUpdatePath)) {
769
        if ($badUpdatePath) {
770
            echo '<div class="alert alert-warning">';
771
            echo get_lang('Error');
772
            echo '<br />';
773
            echo 'Chamilo '.implode('|', $upgradeFromVersion).' '.get_lang('has not been found in that directory').'</div>';
774
        } else {
775
            echo '<br />';
776
        } ?>
777
            <div class="row">
778
                <div class="col-md-12">
779
                    <p><?php echo get_lang('Old version\'s root path'); ?>:
780
                        <input
781
                            type="text"
782
                            name="updatePath" size="50"
783
                            value="<?php echo ($badUpdatePath && !empty($updatePath)) ? htmlentities($updatePath) : ''; ?>" />
784
                    </p>
785
                    <p>
786
                        <div class="btn-group">
787
                            <button type="submit" class="btn btn-secondary" name="step1" value="<?php echo get_lang('Back'); ?>" >
788
                                <em class="fa fa-backward"> <?php echo get_lang('Back'); ?></em>
789
                            </button>
790
                            <input type="hidden" name="is_executable" id="is_executable" value="-" />
791
                            <button
792
                                type="submit"
793
                                class="btn btn-success"
794
                                name="<?php echo isset($_POST['step2_update_6']) ? 'step2_update_6' : 'step2_update_8'; ?>"
795
                                value="<?php echo get_lang('Next'); ?> &gt;" >
796
                                <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
797
                            </button>
798
                        </div>
799
                    </p>
800
                </div>
801
            </div>
802
        <?php
803
    } else {
804
        $error = false;
805
        // First, attempt to set writing permissions if we don't have them yet
806
        //$perm = api_get_permissions_for_new_directories();
807
        $perm = octdec('0777');
808
        //$perm_file = api_get_permissions_for_new_files();
809
        $perm_file = octdec('0666');
810
        $notWritable = [];
811
812
        $checked_writable = api_get_path(SYS_PUBLIC_PATH);
813
        if (!is_writable($checked_writable)) {
814
            $notWritable[] = $checked_writable;
815
            @chmod($checked_writable, $perm);
816
        }
817
818
        if (false == $course_test_was_created) {
819
            error_log('Installer: Could not create test course - Make sure permissions are fine.');
820
            $error = true;
821
        }
822
823
        $checked_writable = api_get_path(CONFIGURATION_PATH).'configuration.php';
824
        if (file_exists($checked_writable) && !is_writable($checked_writable)) {
825
            $notWritable[] = $checked_writable;
826
            @chmod($checked_writable, $perm_file);
827
        }
828
829
        // Second, if this fails, report an error
830
        //--> The user would have to adjust the permissions manually
831
        if (count($notWritable) > 0) {
832
            error_log('Installer: At least one needed directory or file is not writeable');
833
            $error = true; ?>
834
            <div class="text-danger">
835
                <h3 class="text-center"><?php echo get_lang('Warning !'); ?></h3>
836
                <p>
837
                    <?php printf(get_lang('Some files or folders don\'t have writing permission. To be able to install Chamilo you should first change their permissions (using CHMOD). Please read the %s installation guide %s'), '<a href="../../documentation/installation_guide.html" target="blank">', '</a>'); ?>
838
                </p>
839
            </div>
840
            <?php
841
            echo '<ul>';
842
            foreach ($notWritable as $value) {
843
                echo '<li class="text-danger">'.$value.'</li>';
844
            }
845
            echo '</ul>';
846
        } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
847
            // Check wether a Chamilo configuration file already exists.
848
            echo '<div class="alert alert-warning"><h4><center>';
849
            echo get_lang('Warning !ExistingLMSInstallationDetected');
850
            echo '</center></h4></div>';
851
        }
852
853
        $deprecated = [
854
            api_get_path(SYS_CODE_PATH).'exercice/',
855
            api_get_path(SYS_CODE_PATH).'newscorm/',
856
            api_get_path(SYS_PLUGIN_PATH).'ticket/',
857
            api_get_path(SYS_PLUGIN_PATH).'skype/',
858
        ];
859
        $deprecatedToRemove = [];
860
        foreach ($deprecated as $deprecatedDirectory) {
861
            if (!is_dir($deprecatedDirectory)) {
862
                continue;
863
            }
864
            $deprecatedToRemove[] = $deprecatedDirectory;
865
        }
866
867
        if (count($deprecatedToRemove) > 0) {
868
            ?>
869
            <p class="text-danger"><?php echo get_lang('Warning !ForDeprecatedDirectoriesForUpgrade'); ?></p>
870
            <ul>
871
                <?php foreach ($deprecatedToRemove as $deprecatedDirectory) {
872
                ?>
873
                    <li class="text-danger"><?php echo $deprecatedDirectory; ?></li>
874
                <?php
875
            } ?>
876
            </ul>
877
            <?php
878
        }
879
880
        // And now display the choice buttons (go back or install)?>
881
        <p align="center" style="padding-top:15px">
882
            <button
883
                type="submit"
884
                name="step1"
885
                class="btn btn-default"
886
                onclick="javascript: window.location='index.php'; return false;"
887
                value="<?php echo get_lang('Previous'); ?>" >
888
                <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
889
            </button>
890
            <button
891
                type="submit" name="step2_install"
892
                class="btn btn-success"
893
                value="<?php echo get_lang('New installation'); ?>" <?php if ($error) {
894
            echo 'disabled="disabled"';
895
        } ?> >
896
                <em class="fa fa-forward"> </em> <?php echo get_lang('New installation'); ?>
897
            </button>
898
            <input type="hidden" name="is_executable" id="is_executable" value="-" />
899
            <button
900
                type="submit"
901
                class="btn btn-default" <?php echo !$error ?: 'disabled="disabled"'; ?>
902
                name="step2_update_8"
903
                value="Upgrade from Chamilo 1.11.x">
904
                <em class="fa fa-forward" aria-hidden="true"></em>
905
                <?php echo get_lang('Upgrade Chamilo LMS version'); ?>
906
            </button>
907
            </p>
908
        <?php
909
    }
910
}
911
912
/**
913
 * Displays the license (GNU GPL) as step 2, with
914
 * - an "I accept" button named step3 to proceed to step 3;
915
 * - a "Back" button named step1 to go back to the first step.
916
 */
917
function display_license_agreement()
918
{
919
    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Licence').'</h2>';
920
    echo '<p>'.get_lang('Chamilo is free software distributed under the GNU General Public licence (GPL).').'</p>';
921
    echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('Printable version').'</a></p>';
922
    $license = api_htmlentities(@file_get_contents(api_get_path(SYMFONY_SYS_PATH).'public/documentation/license.txt'));
923
    echo '</div>';
924
925
    echo '<div class="form-group">
926
        <pre style="overflow: auto; height: 200px; margin-top: 5px;">
927
            '.$license.'
928
        </pre>
929
    </div>
930
    <div class="form-group form-check">
931
        <input type="checkbox" name="accept" id="accept_licence" value="1">
932
        <label for="accept_licence">'.get_lang('I Accept').'</label>
933
    </div>
934
    <div class="row">
935
        <div class="col-md-12">
936
            <p class="alert alert-info">'.
937
            get_lang('The images and media galleries of Chamilo use images from Nuvola, Crystal Clear and Tango icon galleries. Other images and media like diagrams and Flash animations are borrowed from Wikimedia and Ali Pakdel\'s and Denis Hoa\'s courses with their agreement and released under BY-SA Creative Commons license. You may find the license details at <a href="http://creativecommons.org/licenses/by-sa/3.0/">the CC website</a>, where a link to the full text of the license is provided at the bottom of the page.').'
938
            </p>
939
        </div>
940
    </div>
941
    <!-- Contact information form -->
942
    <div class="section-parameters">
943
        <a href="javascript://" class = "advanced_parameters" >
944
        <span id="img_plus_and_minus">&nbsp;<i class="fa fa-eye" aria-hidden="true"></i>&nbsp;'.get_lang('Contact information').'</span>
945
        </a>
946
    </div>
947
    <div id="id_contact_form" style="display:block">
948
        <div class="normal-message">'.get_lang('Contact informationDescription').'</div>
949
        <div id="contact_registration">
950
            <p>'.get_contact_registration_form().'</p><br />
951
        </div>
952
    </div>
953
    <div class="text-center">
954
    <button type="submit" class="btn btn-default" name="step1" value="&lt; '.get_lang('Previous').'" >
955
        <em class="fa fa-backward"> </em> '.get_lang('Previous').'
956
    </button>
957
    <input type="hidden" name="is_executable" id="is_executable" value="-" />
958
    <button
959
        type="submit"
960
        id="license-next"
961
        class="btn btn-success" name="step3"
962
        onclick="javascript:if(!document.getElementById(\'accept_licence\').checked) { alert(\''.get_lang('You must accept the licence').'\');return false;}"
963
        value="'.get_lang('Next').' &gt;">
964
        <em class="fa fa-forward"> </em>'.get_lang('Next').'
965
    </button>
966
    </div>';
967
}
968
969
/**
970
 * Get contact registration form.
971
 */
972
function get_contact_registration_form()
973
{
974
    return '
975
    <div class="form-horizontal">
976
        <div class="panel panel-default">
977
        <div class="panel-body">
978
        <div id="div_sent_information"></div>
979
        <div class="form-group row">
980
                <label class="col-sm-3">
981
                <span class="form_required">*</span>'.get_lang('Name').'</label>
982
                <div class="col-sm-9">
983
                    <input id="person_name" class="form-control" type="text" name="person_name" size="30" />
984
                </div>
985
        </div>
986
        <div class="form-group row">
987
            <label class="col-sm-3">
988
            <span class="form_required">*</span>'.get_lang('e-mail').'</label>
989
            <div class="col-sm-9">
990
            <input id="person_email" class="form-control" type="text" name="person_email" size="30" /></div>
991
        </div>
992
        <div class="form-group row">
993
                <label class="col-sm-3">
994
                <span class="form_required">*</span>'.get_lang('Your company\'s name').'</label>
995
                <div class="col-sm-9">
996
                <input id="company_name" class="form-control" type="text" name="company_name" size="30" /></div>
997
        </div>
998
        <div class="form-group row">
999
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your company\'s activity').'</label>
1000
            <div class="col-sm-9">
1001
                <select class="form-control show-tick" name="company_activity" id="company_activity" >
1002
                    <option value="">--- '.get_lang('Select one').' ---</option>
1003
                    <Option value="Advertising/Marketing/PR">Advertising/Marketing/PR</Option>
1004
                    <Option value="Agriculture/Forestry">Agriculture/Forestry</Option>
1005
                    <Option value="Architecture">Architecture</Option>
1006
                    <Option value="Banking/Finance">Banking/Finance</Option>
1007
                    <Option value="Biotech/Pharmaceuticals">Biotech/Pharmaceuticals</Option>
1008
                    <Option value="Business Equipment">Business Equipment</Option>
1009
                    <Option value="Business Services">Business Services</Option>
1010
                    <Option value="Construction">Construction</Option>
1011
                    <Option value="Consulting/Research">Consulting/Research</Option>
1012
                    <Option value="Education">Education</Option>
1013
                    <Option value="Engineering">Engineering</Option>
1014
                    <Option value="Environmental">Environmental</Option>
1015
                    <Option value="Government">Government</Option>
1016
                    <Option value="Healthcare">Health Care</Option>
1017
                    <Option value="Hospitality/Lodging/Travel">Hospitality/Lodging/Travel</Option>
1018
                    <Option value="Insurance">Insurance</Option>
1019
                    <Option value="Legal">Legal</Option><Option value="Manufacturing">Manufacturing</Option>
1020
                    <Option value="Media/Entertainment">Media/Entertainment</Option>
1021
                    <Option value="Mortgage">Mortgage</Option>
1022
                    <Option value="Non-Profit">Non-Profit</Option>
1023
                    <Option value="Real Estate">Real Estate</Option>
1024
                    <Option value="Restaurant">Restaurant</Option>
1025
                    <Option value="Retail">Retail</Option>
1026
                    <Option value="Shipping/Transportation">Shipping/Transportation</Option>
1027
                    <Option value="Technology">Technology</Option>
1028
                    <Option value="Telecommunications">Telecommunications</Option>
1029
                    <Option value="Other">Other</Option>
1030
                </select>
1031
            </div>
1032
        </div>
1033
1034
        <div class="form-group row">
1035
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your job\'s description').'</label>
1036
            <div class="col-sm-9">
1037
                <select class="form-control show-tick" name="person_role" id="person_role" >
1038
                    <option value="">--- '.get_lang('Select one').' ---</option>
1039
                    <Option value="Administration">Administration</Option>
1040
                    <Option value="CEO/President/ Owner">CEO/President/ Owner</Option>
1041
                    <Option value="CFO">CFO</Option><Option value="CIO/CTO">CIO/CTO</Option>
1042
                    <Option value="Consultant">Consultant</Option>
1043
                    <Option value="Customer Service">Customer Service</Option>
1044
                    <Option value="Engineer/Programmer">Engineer/Programmer</Option>
1045
                    <Option value="Facilities/Operations">Facilities/Operations</Option>
1046
                    <Option value="Finance/ Accounting Manager">Finance/ Accounting Manager</Option>
1047
                    <Option value="Finance/ Accounting Staff">Finance/ Accounting Staff</Option>
1048
                    <Option value="General Manager">General Manager</Option>
1049
                    <Option value="Human Resources">Human Resources</Option>
1050
                    <Option value="IS/IT Management">IS/IT Management</Option>
1051
                    <Option value="IS/ IT Staff">IS/ IT Staff</Option>
1052
                    <Option value="Marketing Manager">Marketing Manager</Option>
1053
                    <Option value="Marketing Staff">Marketing Staff</Option>
1054
                    <Option value="Partner/Principal">Partner/Principal</Option>
1055
                    <Option value="Purchasing Manager">Purchasing Manager</Option>
1056
                    <Option value="Sales/ Business Dev. Manager">Sales/ Business Dev. Manager</Option>
1057
                    <Option value="Sales/ Business Dev.">Sales/ Business Dev.</Option>
1058
                    <Option value="Vice President/Senior Manager">Vice President/Senior Manager</Option>
1059
                    <Option value="Other">Other</Option>
1060
                </select>
1061
            </div>
1062
        </div>
1063
1064
        <div class="form-group row">
1065
            <label class="col-sm-3">
1066
                <span class="form_required">*</span>'.get_lang('Your company\'s home country').'</label>
1067
            <div class="col-sm-9">'.get_countries_list_from_array(true).'</div>
1068
        </div>
1069
        <div class="form-group row">
1070
            <label class="col-sm-3">'.get_lang('Company city').'</label>
1071
            <div class="col-sm-9">
1072
                    <input type="text" class="form-control" id="company_city" name="company_city" size="30" />
1073
            </div>
1074
        </div>
1075
        <div class="form-group row">
1076
            <label class="col-sm-3">'.get_lang('Preferred contact language').'</label>
1077
            <div class="col-sm-9">
1078
                <select class="form-control show-tick" id="language" name="language">
1079
                    <option value="bulgarian">Bulgarian</option>
1080
                    <option value="indonesian">Bahasa Indonesia</option>
1081
                    <option value="bosnian">Bosanski</option>
1082
                    <option value="german">Deutsch</option>
1083
                    <option selected="selected" value="english">English</option>
1084
                    <option value="spanish">Spanish</option>
1085
                    <option value="french">Français</option>
1086
                    <option value="italian">Italian</option>
1087
                    <option value="hungarian">Magyar</option>
1088
                    <option value="dutch">Nederlands</option>
1089
                    <option value="brazilian">Português do Brasil</option>
1090
                    <option value="portuguese">Português europeu</option>
1091
                    <option value="slovenian">Slovenčina</option>
1092
                </select>
1093
            </div>
1094
        </div>
1095
1096
        <div class="form-group row">
1097
            <label class="col-sm-3">'.
1098
                get_lang('Do you have the power to take financial decisions on behalf of your company?').'</label>
1099
            <div class="col-sm-9">
1100
                <div class="radio">
1101
                    <label>
1102
                        <input type="radio" name="financial_decision" id="financial_decision1" value="1" checked /> '.
1103
                        get_lang('Yes').'
1104
                    </label>
1105
                </div>
1106
                <div class="radio">
1107
                    <label>
1108
                        <input type="radio" name="financial_decision" id="financial_decision2" value="0" /> '.
1109
                        get_lang('No').'
1110
                    </label>
1111
                </div>
1112
            </div>
1113
        </div>
1114
        <div class="clear"></div>
1115
        <div class="form-group row">
1116
            <div class="col-sm-3">&nbsp;</div>
1117
            <div class="col-sm-9">
1118
            <button
1119
                type="button"
1120
                class="btn btn-default"
1121
                onclick="javascript:send_contact_information();"
1122
                value="'.get_lang('Send information').'" >
1123
                <em class="fa fa-check"></em> '.get_lang('Send information').'
1124
            </button>
1125
            <span id="loader-button"></span></div>
1126
        </div>
1127
        <div class="form-group row">
1128
            <div class="col-sm-3">&nbsp;</div>
1129
            <div class="col-sm-9">
1130
                <span class="form_required">*</span><small>'.get_lang('Mandatory field').'</small>
1131
            </div>
1132
        </div></div></div>
1133
        </div>';
1134
}
1135
1136
/**
1137
 * Displays a parameter in a table row.
1138
 * Used by the display_database_settings_form function.
1139
 *
1140
 * @param   string  Type of install
1141
 * @param   string  Name of parameter
1142
 * @param   string  Field name (in the HTML form)
1143
 * @param   string  Field value
1144
 * @param   string  Extra notice (to show on the right side)
1145
 * @param   bool Whether to display in update mode
1146
 * @param   string  Additional attribute for the <tr> element
1147
 */
1148
function displayDatabaseParameter(
1149
    $installType,
1150
    $parameterName,
1151
    $formFieldName,
1152
    $parameterValue,
1153
    $extra_notice,
1154
    $displayWhenUpdate = true
1155
) {
1156
    echo "<dt class='col-sm-4'>$parameterName</dt>";
1157
    echo '<dd class="col-sm-8">';
1158
    if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) {
1159
        echo '<input
1160
                type="hidden"
1161
                name="'.$formFieldName.'"
1162
                id="'.$formFieldName.'"
1163
                value="'.api_htmlentities($parameterValue).'" />'.$parameterValue;
1164
    } else {
1165
        $inputType = 'dbPassForm' === $formFieldName ? 'password' : 'text';
1166
        //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on
1167
        $maxLength = 'dbPrefixForm' === $formFieldName ? '15' : MAX_FORM_FIELD_LENGTH;
1168
        if (INSTALL_TYPE_UPDATE == $installType) {
1169
            echo '<input
1170
                type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'"
1171
                value="'.api_htmlentities($parameterValue).'" />';
1172
            echo api_htmlentities($parameterValue);
1173
        } else {
1174
            echo '<input
1175
                        type="'.$inputType.'"
1176
                        class="form-control"
1177
                        size="'.DATABASE_FORM_FIELD_DISPLAY_LENGTH.'"
1178
                        maxlength="'.$maxLength.'"
1179
                        name="'.$formFieldName.'"
1180
                        id="'.$formFieldName.'"
1181
                        value="'.api_htmlentities($parameterValue).'" />
1182
                    '.$extra_notice.'
1183
                  ';
1184
        }
1185
    }
1186
    echo '</dd>';
1187
}
1188
1189
/**
1190
 * Displays step 3 - a form where the user can enter the installation settings
1191
 * regarding the databases - login and password, names, prefixes, single
1192
 * or multiple databases, tracking or not...
1193
 *
1194
 * @param string $installType
1195
 * @param string $dbHostForm
1196
 * @param string $dbUsernameForm
1197
 * @param string $dbPassForm
1198
 * @param string $dbNameForm
1199
 * @param int    $dbPortForm
1200
 * @param string $installationProfile
1201
 */
1202
function display_database_settings_form(
1203
    $installType,
1204
    $dbHostForm,
1205
    $dbUsernameForm,
1206
    $dbPassForm,
1207
    $dbNameForm,
1208
    $dbPortForm = 3306,
1209
    $installationProfile = ''
1210
) {
1211
    if ('update' === $installType) {
1212
        $dbHostForm = get_config_param('db_host');
1213
        $dbUsernameForm = get_config_param('db_user');
1214
        $dbPassForm = get_config_param('db_password');
1215
        $dbNameForm = get_config_param('main_database');
1216
        $dbPortForm = get_config_param('db_port');
1217
1218
        echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Database settings').'</h2></div>';
1219
        echo '<div class="RequirementContent">';
1220
        echo get_lang('The upgrade script will recover and update the Chamilo database(s). In order to do this, this script will use the databases and settings defined below. Because our software runs on a wide range of systems and because all of them might not have been tested, we strongly recommend you do a full backup of your databases before you proceed with the upgrade!');
1221
        echo '</div>';
1222
    } else {
1223
        echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Database settings').'</h2></div>';
1224
        echo '<div class="RequirementContent">';
1225
        echo get_lang('The install script will create (or use) the Chamilo database using the database name given here. Please make sure the user you give has the right to create the database by the name given here. If a database with this name exists, it will be overwritten. Please do not use the root user as the Chamilo database user. This can lead to serious security issues.');
1226
        echo '</div>';
1227
    }
1228
1229
    echo '
1230
        <div class="card">
1231
            <div class="card-body">
1232
            <dl class="row">
1233
                <dt class="col-sm-4">'.get_lang('Database Host').'</dt>';
1234
    if ('update' === $installType) {
1235
        echo '<dd class="col-sm-8">
1236
                <input
1237
                    type="hidden"
1238
                    name="dbHostForm" value="'.htmlentities($dbHostForm).'" />'.$dbHostForm.'
1239
                </dd>';
1240
    } else {
1241
        echo '<dd class="col-sm-8">
1242
                <input
1243
                    type="text"
1244
                    class="form-control"
1245
                    size="25"
1246
                    maxlength="50" name="dbHostForm" value="'.htmlentities($dbHostForm).'" />
1247
                    '.get_lang('ex.').'localhost
1248
            </dd>';
1249
    }
1250
1251
    echo '<dt class="col-sm-4">'.get_lang('Port').'</dt>';
1252
    if ('update' === $installType) {
1253
        echo '<dd class="col-sm-8">
1254
            <input
1255
                type="hidden"
1256
                name="dbPortForm" value="'.htmlentities($dbPortForm).'" />'.$dbPortForm.'
1257
            </dd>';
1258
    } else {
1259
        echo '
1260
        <dd class="col-sm-8">
1261
            <input
1262
            type="text"
1263
            class="form-control"
1264
            size="25"
1265
            maxlength="50" name="dbPortForm" value="'.htmlentities($dbPortForm).'" />
1266
            '.get_lang('ex.').' 3306
1267
        </dd>';
1268
    }
1269
    //database user username
1270
    $example_login = get_lang('ex.').' root';
1271
    displayDatabaseParameter(
1272
        $installType,
1273
        get_lang('Database Login'),
1274
        'dbUsernameForm',
1275
        $dbUsernameForm,
1276
        $example_login
1277
    );
1278
1279
    //database user password
1280
    $example_password = get_lang('ex.').' '.api_generate_password();
1281
    displayDatabaseParameter($installType, get_lang('Database Password'), 'dbPassForm', $dbPassForm, $example_password);
1282
    // Database Name fix replace weird chars
1283
    if (INSTALL_TYPE_UPDATE != $installType) {
1284
        $dbNameForm = str_replace(['-', '*', '$', ' ', '.'], '', $dbNameForm);
1285
    }
1286
    displayDatabaseParameter(
1287
        $installType,
1288
        get_lang('Database name'),
1289
        'dbNameForm',
1290
        $dbNameForm,
1291
        '&nbsp;',
1292
        null,
1293
        'id="optional_param1"'
1294
    );
1295
    echo '</div></div>';
1296
    if (INSTALL_TYPE_UPDATE != $installType) { ?>
1297
        <button type="submit" class="btn btn-primary" name="step3" value="step3">
1298
            <em class="fa fa-sync"> </em>
1299
            <?php echo get_lang('Check database connection'); ?>
1300
        </button>
1301
        <?php
1302
    }
1303
1304
    $databaseExistsText = '';
1305
    $manager = null;
1306
    try {
1307
        if ('update' === $installType) {
1308
            /** @var \Database $manager */
1309
            $manager = connectToDatabase(
1310
                $dbHostForm,
1311
                $dbUsernameForm,
1312
                $dbPassForm,
1313
                $dbNameForm,
1314
                $dbPortForm
1315
            );
1316
1317
            $connection = $manager->getConnection();
1318
            $connection->connect();
1319
            $schemaManager = $connection->getSchemaManager();
1320
1321
            // Test create/alter/drop table
1322
            $table = 'zXxTESTxX_'.mt_rand(0, 1000);
1323
            $sql = "CREATE TABLE $table (id INT AUTO_INCREMENT NOT NULL, name varchar(255), PRIMARY KEY(id))";
1324
            $connection->executeQuery($sql);
1325
            $tableCreationWorks = false;
1326
            $tableDropWorks = false;
1327
            if ($schemaManager->tablesExist($table)) {
1328
                $sql = "ALTER TABLE $table ADD COLUMN name2 varchar(140) ";
1329
                $connection->executeQuery($sql);
1330
                $schemaManager->dropTable($table);
1331
                $tableDropWorks = false === $schemaManager->tablesExist($table);
1332
            }
1333
        } else {
1334
            $manager = connectToDatabase(
1335
                $dbHostForm,
1336
                $dbUsernameForm,
1337
                $dbPassForm,
1338
                null,
1339
                $dbPortForm
1340
            );
1341
1342
            $schemaManager = $manager->getConnection()->getSchemaManager();
1343
            $databases = $schemaManager->listDatabases();
1344
            if (in_array($dbNameForm, $databases)) {
1345
                $databaseExistsText = '<div class="alert alert-warning">'.
1346
                get_lang('A database with the same name <b>already exists</b>. It will be <b>deleted</b>.').
1347
                    '</div>';
1348
            }
1349
        }
1350
    } catch (Exception $e) {
1351
        $databaseExistsText = $e->getMessage();
1352
        $manager = false;
1353
    }
1354
1355
    if ($manager && $manager->getConnection()->isConnected()) {
1356
        echo $databaseExistsText; ?>
1357
        <div id="db_status" class="alert alert-success">
1358
            Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br/>
1359
            Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br/>
1360
            Database driver: <strong><?php echo $manager->getConnection()->getDriver()->getName(); ?></strong><br/>
1361
            <?php
1362
                if ('update' === $installType) {
1363
                    echo get_lang('CreateTableWorks').' <strong>Ok</strong>';
1364
                    echo '<br/ >';
1365
                    echo get_lang('AlterTableWorks').' <strong>Ok</strong>';
1366
                    echo '<br/ >';
1367
                    echo get_lang('DropColumnWorks').' <strong>Ok</strong>';
1368
                } ?>
1369
        </div>
1370
    <?php
1371
    } else { ?>
1372
        <div id="db_status" class="alert alert-danger">
1373
            <p>
1374
                <?php echo get_lang('The database connection has failed. This is generally due to the wrong user, the wrong password or the wrong database prefix being set above. Please review these settings and try again.'); ?>
1375
            </p>
1376
            <code><?php echo $databaseExistsText; ?></code>
1377
        </div>
1378
    <?php } ?>
1379
1380
   <div class="btn-group" role="group">
1381
       <button type="submit" name="step2"
1382
               class="btn btn-secondary" value="&lt; <?php echo get_lang('Previous'); ?>" >
1383
           <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1384
       </button>
1385
       <input type="hidden" name="is_executable" id="is_executable" value="-" />
1386
       <?php if ($manager) {
1387
        ?>
1388
           <button type="submit" class="btn btn-success" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1389
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1390
           </button>
1391
       <?php
1392
    } else {
1393
        ?>
1394
           <button
1395
                   disabled="disabled"
1396
                   type="submit" class="btn btn-success disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1397
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1398
           </button>
1399
       <?php
1400
    } ?>
1401
   </div>
1402
    <?php
1403
}
1404
1405
/**
1406
 * Displays a parameter in a table row.
1407
 * Used by the display_configuration_settings_form function.
1408
 *
1409
 * @param string $installType
1410
 * @param string $parameterName
1411
 * @param string $formFieldName
1412
 * @param string $parameterValue
1413
 * @param string $displayWhenUpdate
1414
 *
1415
 * @return string
1416
 */
1417
function display_configuration_parameter(
1418
    $installType,
1419
    $parameterName,
1420
    $formFieldName,
1421
    $parameterValue,
1422
    $displayWhenUpdate = 'true'
1423
) {
1424
    $html = '<div class="form-group row">';
1425
    $html .= '<label class="col-sm-6 control-label">'.$parameterName.'</label>';
1426
    if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) {
1427
        $html .= '<input
1428
            type="hidden"
1429
            name="'.$formFieldName.'"
1430
            value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />'.$parameterValue;
1431
    } else {
1432
        $html .= '<div class="col-sm-6">
1433
                    <input
1434
                        class="form-control"
1435
                        type="text"
1436
                        size="'.FORM_FIELD_DISPLAY_LENGTH.'"
1437
                        maxlength="'.MAX_FORM_FIELD_LENGTH.'"
1438
                        name="'.$formFieldName.'"
1439
                        value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />
1440
                    '.'</div>';
1441
    }
1442
    $html .= '</div>';
1443
1444
    return $html;
1445
}
1446
1447
/**
1448
 * Displays step 4 of the installation - configuration settings about Chamilo itself.
1449
 *
1450
 * @param string $installType
1451
 * @param string $urlForm
1452
 * @param string $languageForm
1453
 * @param string $emailForm
1454
 * @param string $adminFirstName
1455
 * @param string $adminLastName
1456
 * @param string $adminPhoneForm
1457
 * @param string $campusForm
1458
 * @param string $institutionForm
1459
 * @param string $institutionUrlForm
1460
 * @param string $encryptPassForm
1461
 * @param bool   $allowSelfReg
1462
 * @param bool   $allowSelfRegProf
1463
 * @param string $loginForm
1464
 * @param string $passForm
1465
 */
1466
function display_configuration_settings_form(
1467
    $installType,
1468
    $urlForm,
1469
    $languageForm,
1470
    $emailForm,
1471
    $adminFirstName,
1472
    $adminLastName,
1473
    $adminPhoneForm,
1474
    $campusForm,
1475
    $institutionForm,
1476
    $institutionUrlForm,
1477
    $encryptPassForm,
1478
    $allowSelfReg,
1479
    $allowSelfRegProf,
1480
    $loginForm,
1481
    $passForm
1482
) {
1483
    if ('update' !== $installType && empty($languageForm)) {
1484
        $languageForm = $_SESSION['install_language'];
1485
    }
1486
    echo '<div class="RequirementHeading">';
1487
    echo '<h2>'.display_step_sequence().get_lang('Configuration settings').'</h2>';
1488
    echo '</div>';
1489
1490
    // Parameter 1: administrator's login
1491
    if ('update' === $installType) {
1492
        $rootSys = get_config_param('root_web');
1493
        $html = display_configuration_parameter(
1494
            $installType,
1495
            get_lang('Chamilo URL'),
1496
            'loginForm',
1497
            $rootSys,
1498
            true
1499
        );
1500
        $rootSys = get_config_param('root_sys');
1501
        $html .= display_configuration_parameter(
1502
            $installType,
1503
            get_lang('Path'),
1504
            'loginForm',
1505
            $rootSys,
1506
            true
1507
        );
1508
        $systemVersion = get_config_param('system_version');
1509
        $html .= display_configuration_parameter(
1510
            $installType,
1511
            get_lang('Version'),
1512
            'loginForm',
1513
            $systemVersion,
1514
            true
1515
        );
1516
        echo Display::panel($html, get_lang('System'));
1517
    }
1518
1519
    $html = display_configuration_parameter(
1520
        $installType,
1521
        get_lang('Administrator login'),
1522
        'loginForm',
1523
        $loginForm,
1524
        'update' == $installType
1525
    );
1526
1527
    // Parameter 2: administrator's password
1528
    if ('update' !== $installType) {
1529
        $html .= display_configuration_parameter(
1530
            $installType,
1531
            get_lang('Administrator password (<font color="red">you may want to change this</font>)'),
1532
            'passForm',
1533
            $passForm,
1534
            false
1535
        );
1536
    }
1537
1538
    // Parameters 3 and 4: administrator's names
1539
    $html .= display_configuration_parameter(
1540
        $installType,
1541
        get_lang('Administrator first name'),
1542
        'adminFirstName',
1543
        $adminFirstName
1544
    );
1545
    $html .= display_configuration_parameter(
1546
        $installType,
1547
        get_lang('Administrator last name'),
1548
        'adminLastName',
1549
        $adminLastName
1550
    );
1551
1552
    // Parameter 3: administrator's email
1553
    $html .= display_configuration_parameter($installType, get_lang('Admin-mail'), 'emailForm', $emailForm);
1554
1555
    // Parameter 6: administrator's telephone
1556
    $html .= display_configuration_parameter(
1557
        $installType,
1558
        get_lang('Administrator telephone'),
1559
        'adminPhoneForm',
1560
        $adminPhoneForm
1561
    );
1562
    echo Display::panel($html, get_lang('Administrator'));
1563
1564
    // First parameter: language.
1565
    $html = '<div class="form-group row">';
1566
    $html .= '<label class="col-sm-6 control-label">'.get_lang('Language').'</label>';
1567
    if ('update' === $installType) {
1568
        $html .= '<input
1569
            type="hidden"
1570
            name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES).'" />'.
1571
            $languageForm;
1572
    } else {
1573
        $html .= '<div class="col-sm-6">';
1574
        $html .= display_language_selection_box('languageForm', $languageForm);
1575
        $html .= '</div>';
1576
    }
1577
    $html .= '</div>';
1578
1579
    // Second parameter: Chamilo URL
1580
    if ('install' === $installType) {
1581
        $html .= '<div class="form-group row">';
1582
        $html .= '<label class="col-sm-6 control-label">'.get_lang('Chamilo URL').'</label>';
1583
        $html .= '<div class="col-sm-6">';
1584
        $html .= '<input
1585
            class="form-control"
1586
            type="text" size="40"
1587
            required
1588
            maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES).'" />';
1589
        $html .= '</div>';
1590
1591
        $html .= '</div>';
1592
    }
1593
1594
    // Parameter 9: campus name
1595
    $html .= display_configuration_parameter(
1596
        $installType,
1597
        get_lang('Your portal name'),
1598
        'campusForm',
1599
        $campusForm
1600
    );
1601
1602
    // Parameter 10: institute (short) name
1603
    $html .= display_configuration_parameter(
1604
        $installType,
1605
        get_lang('Your company short name'),
1606
        'institutionForm',
1607
        $institutionForm
1608
    );
1609
1610
    // Parameter 11: institute (short) name
1611
    $html .= display_configuration_parameter(
1612
        $installType,
1613
        get_lang('URL of this company'),
1614
        'institutionUrlForm',
1615
        $institutionUrlForm
1616
    );
1617
1618
    $html .= '<div class="form-group row">
1619
            <label class="col-sm-6 control-label">'.get_lang('Encryption method').'</label>
1620
        <div class="col-sm-6">';
1621
    if ('update' === $installType) {
1622
        $html .= '<input type="hidden" name="encryptPassForm" value="'.$encryptPassForm.'" />'.$encryptPassForm;
1623
    } else {
1624
        $html .= '<div class="checkbox">
1625
                    <label>
1626
                        <input
1627
                            type="radio"
1628
                            name="encryptPassForm"
1629
                            value="bcrypt"
1630
                            id="encryptPass1" '.('bcrypt' === $encryptPassForm ? 'checked="checked" ' : '').'/> bcrypt
1631
                    </label>';
1632
1633
        $html .= '<label>
1634
                        <input
1635
                            type="radio"
1636
                            name="encryptPassForm"
1637
                            value="sha1"
1638
                            id="encryptPass1" '.('sha1' === $encryptPassForm ? 'checked="checked" ' : '').'/> sha1
1639
                    </label>';
1640
1641
        $html .= '<label>
1642
                        <input type="radio"
1643
                            name="encryptPassForm"
1644
                            value="md5"
1645
                            id="encryptPass0" '.('md5' === $encryptPassForm ? 'checked="checked" ' : '').'/> md5
1646
                    </label>';
1647
1648
        $html .= '<label>
1649
                        <input
1650
                            type="radio"
1651
                            name="encryptPassForm"
1652
                            value="none"
1653
                            id="encryptPass2" '.
1654
                            ('none' === $encryptPassForm ? 'checked="checked" ' : '').'/>'.get_lang('none').'
1655
                    </label>';
1656
        $html .= '</div>';
1657
    }
1658
    $html .= '</div></div>';
1659
1660
    $html .= '<div class="form-group row">
1661
            <label class="col-sm-6 control-label">'.get_lang('Allow self-registration').'</label>
1662
            <div class="col-sm-6">';
1663
    if ('update' === $installType) {
1664
        if ('true' === $allowSelfReg) {
1665
            $label = get_lang('Yes');
1666
        } elseif ('false' === $allowSelfReg) {
1667
            $label = get_lang('No');
1668
        } else {
1669
            $label = get_lang('After approval');
1670
        }
1671
        $html .= '<input type="hidden" name="allowSelfReg" value="'.$allowSelfReg.'" />'.$label;
1672
    } else {
1673
        $html .= '<div class="control-group">';
1674
        $html .= '<label class="checkbox-inline">
1675
                    <input type="radio"
1676
                        name="allowSelfReg" value="true"
1677
                        id="allowSelfReg1" '.('true' == $allowSelfReg ? 'checked="checked" ' : '').' /> '.get_lang('Yes').'
1678
                  </label>';
1679
        $html .= '<label class="checkbox-inline">
1680
                    <input
1681
                        type="radio"
1682
                        name="allowSelfReg"
1683
                        value="false"
1684
                        id="allowSelfReg0" '.('false' == $allowSelfReg ? '' : 'checked="checked" ').' /> '.get_lang('No').'
1685
                </label>';
1686
        $html .= '<label class="checkbox-inline">
1687
                    <input
1688
                        type="radio"
1689
                        name="allowSelfReg"
1690
                        value="approval"
1691
                        id="allowSelfReg2" '.('approval' == $allowSelfReg ? '' : 'checked="checked" ').' /> '.get_lang('After approval').'
1692
                </label>';
1693
        $html .= '</div>';
1694
    }
1695
    $html .= '</div>';
1696
    $html .= '</div>';
1697
1698
    $html .= '<div class="form-group row">';
1699
    $html .= '<label class="col-sm-6 control-label">'.get_lang('Allow self-registrationProf').'</label>
1700
                <div class="col-sm-6">';
1701
    if ('update' === $installType) {
1702
        if ('true' === $allowSelfRegProf) {
1703
            $label = get_lang('Yes');
1704
        } else {
1705
            $label = get_lang('No');
1706
        }
1707
        $html .= '<input type="hidden" name="allowSelfRegProf" value="'.$allowSelfRegProf.'" />'.$label;
1708
    } else {
1709
        $html .= '<div class="control-group">
1710
                <label class="checkbox-inline">
1711
                    <input
1712
                        type="radio"
1713
                        name="allowSelfRegProf" value="1"
1714
                        id="allowSelfRegProf1" '.($allowSelfRegProf ? 'checked="checked" ' : '').'/>
1715
                '.get_lang('Yes').'
1716
                </label>';
1717
        $html .= '<label class="checkbox-inline">
1718
                    <input
1719
                        type="radio" name="allowSelfRegProf" value="0"
1720
                        id="allowSelfRegProf0" '.($allowSelfRegProf ? '' : 'checked="checked" ').' />
1721
                   '.get_lang('No').'
1722
                </label>';
1723
        $html .= '</div>';
1724
    }
1725
    $html .= '</div>
1726
    </div>';
1727
    echo Display::panel($html, get_lang('Portal')); ?>
1728
    <div class='btn-group'>
1729
        <button
1730
            type="submit"
1731
            class="btn btn-secondary "
1732
            name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" >
1733
                <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1734
        </button>
1735
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
1736
        <button class="btn btn-success" type="submit" name="step5">
1737
            <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1738
        </button>
1739
    </div>
1740
    <?php
1741
}
1742
1743
/**
1744
 * After installation is completed (step 6), this message is displayed.
1745
 */
1746
function display_after_install_message()
1747
{
1748
    $container = Container::$container;
1749
    $trans = $container->get('translator');
1750
    $html = '<div class="RequirementContent">'.
1751
    $trans->trans(
1752
        'When you enter your portal for the first time, the best way to understand it is to create a course with the \'Create course\' link in the menu and play around a little.').'</div>';
1753
    $html .= '<div class="alert alert-warning">';
1754
    $html .= '<strong>'.$trans->trans('Security advice').'</strong>';
1755
    $html .= ': ';
1756
    $html .= sprintf($trans->trans(
1757
        'To protect your site, make the whole %s directory read-only (chmod -R 0555 on Linux) and delete the %s directory.'), 'var/config/', 'main/install/');
1758
    $html .= '</div></form>
1759
    <br />
1760
    <a class="btn btn-success btn-block" href="../../">
1761
        '.$trans->trans('Go to your newly created portal.').'
1762
    </a>';
1763
1764
    return $html;
1765
}
1766
1767
/**
1768
 * This function return countries list from array (hardcoded).
1769
 *
1770
 * @param bool $combo (Optional) True for returning countries list with select html
1771
 *
1772
 * @return array|string countries list
1773
 */
1774
function get_countries_list_from_array($combo = false)
1775
{
1776
    $a_countries = [
1777
        'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan',
1778
        'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi',
1779
        'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombi', 'Comoros', 'Congo (Brazzaville)', 'Congo', 'Costa Rica', "Cote d'Ivoire", 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic',
1780
        'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic',
1781
        'East Timor (Timor Timur)', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia',
1782
        'Fiji', 'Finland', 'France',
1783
        'Gabon', 'Gambia, The', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana',
1784
        'Haiti', 'Honduras', 'Hungary',
1785
        'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy',
1786
        'Jamaica', 'Japan', 'Jordan',
1787
        'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, North', 'Korea, South', 'Kuwait', 'Kyrgyzstan',
1788
        'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg',
1789
        'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Morocco', 'Mozambique', 'Myanmar',
1790
        'Namibia', 'Nauru', 'Nepa', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway',
1791
        'Oman',
1792
        'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal',
1793
        'Qatar',
1794
        'Romania', 'Russia', 'Rwanda',
1795
        'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia and Montenegro', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria',
1796
        'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu',
1797
        'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan',
1798
        'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam',
1799
        'Yemen',
1800
        'Zambia', 'Zimbabwe',
1801
    ];
1802
    if ($combo) {
1803
        $country_select = '<select class="form-control show-tick" id="country" name="country">';
1804
        $country_select .= '<option value="">--- '.get_lang('Select one').' ---</option>';
1805
        foreach ($a_countries as $country) {
1806
            $country_select .= '<option value="'.$country.'">'.$country.'</option>';
1807
        }
1808
        $country_select .= '</select>';
1809
1810
        return $country_select;
1811
    }
1812
1813
    return $a_countries;
1814
}
1815
1816
/**
1817
 * Lock settings that can't be changed in other portals.
1818
 */
1819
function lockSettings()
1820
{
1821
    $settings = api_get_locked_settings();
1822
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1823
    foreach ($settings as $setting) {
1824
        $sql = "UPDATE $table SET access_url_locked = 1 WHERE variable  = '$setting'";
1825
        Database::query($sql);
1826
    }
1827
}
1828
1829
/**
1830
 * Update dir values.
1831
 */
1832
function updateDirAndFilesPermissions()
1833
{
1834
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1835
    $permissions_for_new_directories = isset($_SESSION['permissions_for_new_directories']) ? $_SESSION['permissions_for_new_directories'] : 0770;
1836
    $permissions_for_new_files = isset($_SESSION['permissions_for_new_files']) ? $_SESSION['permissions_for_new_files'] : 0660;
1837
    // use decoct() to store as string
1838
    Database::update(
1839
        $table,
1840
        ['selected_value' => '0'.decoct($permissions_for_new_directories)],
1841
        ['variable = ?' => 'permissions_for_new_directories']
1842
    );
1843
1844
    Database::update(
1845
        $table,
1846
        ['selected_value' => '0'.decoct($permissions_for_new_files)],
1847
        ['variable = ?' => 'permissions_for_new_files']
1848
    );
1849
1850
    if (isset($_SESSION['permissions_for_new_directories'])) {
1851
        unset($_SESSION['permissions_for_new_directories']);
1852
    }
1853
1854
    if (isset($_SESSION['permissions_for_new_files'])) {
1855
        unset($_SESSION['permissions_for_new_files']);
1856
    }
1857
}
1858
1859
/**
1860
 * @param $current_value
1861
 * @param $wanted_value
1862
 *
1863
 * @return string
1864
 */
1865
function compare_setting_values($current_value, $wanted_value)
1866
{
1867
    $current_value_string = $current_value;
1868
    $current_value = (float) $current_value;
1869
    $wanted_value = (float) $wanted_value;
1870
1871
    if ($current_value >= $wanted_value) {
1872
        return Display::label($current_value_string, 'success');
1873
    }
1874
1875
    return Display::label($current_value_string, 'important');
1876
}
1877
1878
/**
1879
 * Save settings values.
1880
 *
1881
 * @param string $organizationName
1882
 * @param string $organizationUrl
1883
 * @param string $siteName
1884
 * @param string $adminEmail
1885
 * @param string $adminLastName
1886
 * @param string $adminFirstName
1887
 * @param string $language
1888
 * @param string $allowRegistration
1889
 * @param string $allowTeacherSelfRegistration
1890
 * @param string $installationProfile          The name of an installation profile file in main/install/profiles/
1891
 */
1892
function installSettings(
1893
    $organizationName,
1894
    $organizationUrl,
1895
    $siteName,
1896
    $adminEmail,
1897
    $adminLastName,
1898
    $adminFirstName,
1899
    $language,
1900
    $allowRegistration,
1901
    $allowTeacherSelfRegistration,
1902
    $installationProfile = ''
1903
) {
1904
    error_log('installSettings');
1905
    $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false';
1906
1907
    $settings = [
1908
        'institution' => $organizationName,
1909
        'institution_url' => $organizationUrl,
1910
        'site_name' => $siteName,
1911
        'administrator_email' => $adminEmail,
1912
        'administrator_surname' => $adminLastName,
1913
        'administrator_name' => $adminFirstName,
1914
        'platform_language' => $language,
1915
        'allow_registration' => $allowRegistration,
1916
        'allow_registration_as_teacher' => $allowTeacherSelfRegistration,
1917
    ];
1918
1919
    foreach ($settings as $variable => $value) {
1920
        $sql = "UPDATE settings_current
1921
                SET selected_value = '$value'
1922
                WHERE variable = '$variable'";
1923
        Database::query($sql);
1924
    }
1925
    installProfileSettings($installationProfile);
1926
}
1927
1928
/**
1929
 * Executes DB changes based in the classes defined in
1930
 * /src/CoreBundle/Migrations/Schema/V200/*.
1931
 *
1932
 * @return bool
1933
 */
1934
function migrate(EntityManager $manager)
1935
{
1936
    $debug = true;
1937
    $connection = $manager->getConnection();
1938
    $to = null; // if $to == null then schema will be migrated to latest version
1939
1940
    // Loading migration configuration.
1941
    $config = new PhpFile('./migrations.php');
1942
    $dependency = DependencyFactory::fromConnection($config, new ExistingConnection($connection));
1943
1944
    // Check if old "version" table exists from 1.11.x, use new version.
1945
    $schema = $manager->getConnection()->getSchemaManager();
1946
    $dropOldVersionTable = false;
1947
    if ($schema->tablesExist('version')) {
1948
        $columns = $schema->listTableColumns('version');
1949
        if (in_array('id', array_keys($columns), true)) {
1950
            $dropOldVersionTable = true;
1951
        }
1952
    }
1953
1954
    if ($dropOldVersionTable) {
1955
        error_log('Drop version table');
1956
        $schema->dropTable('version');
1957
    }
1958
1959
    // Creates "version" table.
1960
    $dependency->getMetadataStorage()->ensureInitialized();
1961
1962
    // Loading migrations.
1963
    $migratorConfigurationFactory = $dependency->getConsoleInputMigratorConfigurationFactory();
1964
    $result = '';
1965
    $input = new Symfony\Component\Console\Input\StringInput($result);
1966
    $migratorConfiguration = $migratorConfigurationFactory->getMigratorConfiguration($input);
1967
    $migrator = $dependency->getMigrator();
1968
    $planCalculator = $dependency->getMigrationPlanCalculator();
1969
    $migrations = $planCalculator->getMigrations();
1970
    $lastVersion = $migrations->getLast();
1971
1972
    $plan = $dependency->getMigrationPlanCalculator()->getPlanUntilVersion($lastVersion->getVersion());
1973
1974
    foreach ($plan->getItems() as $item) {
1975
        error_log("Version to be executed: ".$item->getVersion());
1976
        $item->getMigration()->setEntityManager($manager);
1977
        $item->getMigration()->setContainer(Container::$container);
1978
    }
1979
1980
    // Execute migration!!
1981
    /** @var $migratedVersions */
1982
    $versions = $migrator->migrate($plan, $migratorConfiguration);
1983
1984
    if ($debug) {
1985
        /** @var Query[] $queries */
1986
        $versionCounter = 1;
1987
        foreach ($versions as $version => $queries) {
1988
            $total = count($queries);
1989
            echo '----------------------------------------------<br />';
1990
            $message = "VERSION: $version";
1991
            echo "$message<br/>";
1992
            error_log('-------------------------------------');
1993
            error_log($message);
1994
            $counter = 1;
1995
            foreach ($queries as $query) {
1996
                $sql = $query->getStatement();
1997
                echo "<code>$sql</code><br>";
1998
                error_log("$counter/$total : $sql");
1999
                $counter++;
2000
            }
2001
            $versionCounter++;
2002
        }
2003
        echo '<br/>DONE!<br />';
2004
        error_log('DONE!');
2005
    }
2006
2007
    return true;
2008
}
2009
2010
/**
2011
 * @param string $distFile
2012
 * @param string $envFile
2013
 * @param array  $params
2014
 */
2015
function updateEnvFile($distFile, $envFile, $params)
2016
{
2017
    $requirements = [
2018
        'DATABASE_HOST',
2019
        'DATABASE_PORT',
2020
        'DATABASE_NAME',
2021
        'DATABASE_USER',
2022
        'DATABASE_PASSWORD',
2023
        'APP_INSTALLED',
2024
        'APP_ENCRYPT_METHOD',
2025
    ];
2026
2027
    foreach ($requirements as $requirement) {
2028
        if (!isset($params['{{'.$requirement.'}}'])) {
2029
            throw new \Exception("The parameter $requirement is needed in order to edit the .env.local file");
2030
        }
2031
    }
2032
2033
    $contents = file_get_contents($distFile);
2034
    $contents = str_replace(array_keys($params), array_values($params), $contents);
2035
    file_put_contents($envFile, $contents);
2036
    error_log("File env saved here: $envFile");
2037
}
2038
2039
function installTools($container, $manager, $upgrade = false)
2040
{
2041
    error_log('installTools');
2042
    // Install course tools (table "tool")
2043
    /** @var ToolChain $toolChain */
2044
    $toolChain = $container->get(ToolChain::class);
2045
    $toolChain->createTools($manager);
2046
}
2047
2048
/**
2049
 * @param SymfonyContainer $container
2050
 * @param bool             $upgrade
2051
 */
2052
function installSchemas($container, $upgrade = false)
2053
{
2054
    error_log('installSchemas');
2055
    $settingsManager = $container->get('chamilo.settings.manager');
2056
2057
    $urlRepo = $container->get(AccessUrlRepository::class);
2058
    $accessUrl = $urlRepo->find(1);
2059
    if (null === $accessUrl) {
2060
        $em = Database::getManager();
2061
2062
        // Creating AccessUrl.
2063
        $accessUrl = new AccessUrl();
2064
        $accessUrl
2065
            ->setUrl(AccessUrl::DEFAULT_ACCESS_URL)
2066
            ->setDescription('')
2067
            ->setActive(1)
2068
            ->setCreatedBy(1)
2069
        ;
2070
        $em->persist($accessUrl);
2071
        $em->flush();
2072
2073
        error_log('AccessUrl created');
2074
    }
2075
2076
    if ($upgrade) {
2077
        error_log('Upgrade settings');
2078
        $settingsManager->updateSchemas($accessUrl);
2079
    } else {
2080
        error_log('Install settings');
2081
        // Installing schemas (filling settings_current table)
2082
        $settingsManager->installSchemas($accessUrl);
2083
    }
2084
}
2085
2086
/**
2087
 * @param SymfonyContainer $container
2088
 */
2089
function upgradeWithContainer($container)
2090
{
2091
    Container::setContainer($container);
2092
    Container::setLegacyServices($container, false);
2093
    error_log('setLegacyServices');
2094
    $manager = Database::getManager();
2095
2096
    /** @var GroupRepository $repo */
2097
    $repo = $container->get(GroupRepository::class);
2098
    $repo->createDefaultGroups();
2099
2100
    // @todo check if adminId = 1
2101
    installTools($container, $manager, true);
2102
    installSchemas($container, true);
2103
}
2104
2105
/**
2106
 * After the schema was created (table creation), the function adds
2107
 * admin/platform information.
2108
 *
2109
 * @param \Psr\Container\ContainerInterface $container
2110
 * @param string                            $sysPath
2111
 * @param string                            $encryptPassForm
2112
 * @param string                            $passForm
2113
 * @param string                            $adminLastName
2114
 * @param string                            $adminFirstName
2115
 * @param string                            $loginForm
2116
 * @param string                            $emailForm
2117
 * @param string                            $adminPhoneForm
2118
 * @param string                            $languageForm
2119
 * @param string                            $institutionForm
2120
 * @param string                            $institutionUrlForm
2121
 * @param string                            $siteName
2122
 * @param string                            $allowSelfReg
2123
 * @param string                            $allowSelfRegProf
2124
 * @param string                            $installationProfile Installation profile, if any was provided
2125
 */
2126
function finishInstallationWithContainer(
2127
    $container,
2128
    $sysPath,
2129
    $encryptPassForm,
2130
    $passForm,
2131
    $adminLastName,
2132
    $adminFirstName,
2133
    $loginForm,
2134
    $emailForm,
2135
    $adminPhoneForm,
2136
    $languageForm,
2137
    $institutionForm,
2138
    $institutionUrlForm,
2139
    $siteName,
2140
    $allowSelfReg,
2141
    $allowSelfRegProf,
2142
    $installationProfile = ''
2143
) {
2144
    error_log('finishInstallationWithContainer');
2145
    Container::setContainer($container);
2146
    Container::setLegacyServices($container, false);
2147
    error_log('setLegacyServices');
2148
2149
    //UserManager::setPasswordEncryption($encryptPassForm);
2150
    $timezone = api_get_timezone();
2151
2152
    error_log('user creation - admin');
2153
2154
    $repo = Container::getUserRepository();
2155
    /** @var User $admin */
2156
    $admin = $repo->findOneBy(['username' => 'admin']);
2157
2158
    $admin
2159
        ->setLastname($adminLastName)
2160
        ->setFirstname($adminFirstName)
2161
        ->setUsername($loginForm)
2162
        ->setStatus(1)
2163
        ->setPlainPassword($passForm)
2164
        ->setEmail($emailForm)
2165
        ->setOfficialCode('ADMIN')
2166
        ->setAuthSource(PLATFORM_AUTH_SOURCE)
2167
        ->setPhone($adminPhoneForm)
2168
        ->setLocale($languageForm)
2169
        ->setTimezone($timezone)
2170
    ;
2171
2172
    $repo->updateUser($admin);
2173
2174
    $repo = Container::getUserRepository();
2175
    $repo->updateUser($admin);
2176
2177
    // Set default language
2178
    Database::update(
2179
        Database::get_main_table(TABLE_MAIN_LANGUAGE),
2180
        ['available' => 1],
2181
        ['english_name = ?' => $languageForm]
2182
    );
2183
2184
    // Install settings
2185
    installSettings(
2186
        $institutionForm,
2187
        $institutionUrlForm,
2188
        $siteName,
2189
        $emailForm,
2190
        $adminLastName,
2191
        $adminFirstName,
2192
        $languageForm,
2193
        $allowSelfReg,
2194
        $allowSelfRegProf,
2195
        $installationProfile
2196
    );
2197
    lockSettings();
2198
    updateDirAndFilesPermissions();
2199
}
2200
2201
/**
2202
 * Update settings based on installation profile defined in a JSON file.
2203
 *
2204
 * @param string $installationProfile The name of the JSON file in main/install/profiles/ folder
2205
 *
2206
 * @return bool false on failure (no bad consequences anyway, just ignoring profile)
2207
 */
2208
function installProfileSettings($installationProfile = '')
2209
{
2210
    error_log('installProfileSettings');
2211
    if (empty($installationProfile)) {
2212
        return false;
2213
    }
2214
    $jsonPath = api_get_path(SYS_PATH).'main/install/profiles/'.$installationProfile.'.json';
2215
    // Make sure the path to the profile is not hacked
2216
    if (!Security::check_abs_path($jsonPath, api_get_path(SYS_PATH).'main/install/profiles/')) {
2217
        return false;
2218
    }
2219
    if (!is_file($jsonPath)) {
2220
        return false;
2221
    }
2222
    if (!is_readable($jsonPath)) {
2223
        return false;
2224
    }
2225
    if (!function_exists('json_decode')) {
2226
        // The php-json extension is not available. Ignore profile.
2227
        return false;
2228
    }
2229
    $json = file_get_contents($jsonPath);
2230
    $params = json_decode($json);
2231
    if (false === $params or null === $params) {
2232
        return false;
2233
    }
2234
    $settings = $params->params;
2235
    if (!empty($params->parent)) {
2236
        installProfileSettings($params->parent);
2237
    }
2238
2239
    $tblSettings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
2240
2241
    foreach ($settings as $id => $param) {
2242
        $conditions = ['variable = ? ' => $param->variable];
2243
2244
        if (!empty($param->subkey)) {
2245
            $conditions['AND subkey = ? '] = $param->subkey;
2246
        }
2247
2248
        Database::update(
2249
            $tblSettings,
2250
            ['selected_value' => $param->selected_value],
2251
            $conditions
2252
        );
2253
    }
2254
2255
    return true;
2256
}
2257
2258
/**
2259
 * Quick function to remove a directory with its subdirectories.
2260
 *
2261
 * @param $dir
2262
 */
2263
function rrmdir($dir)
2264
{
2265
    if (is_dir($dir)) {
2266
        $objects = scandir($dir);
2267
        foreach ($objects as $object) {
2268
            if ('.' != $object && '..' != $object) {
2269
                if ('dir' == filetype($dir.'/'.$object)) {
2270
                    @rrmdir($dir.'/'.$object);
2271
                } else {
2272
                    @unlink($dir.'/'.$object);
2273
                }
2274
            }
2275
        }
2276
        reset($objects);
2277
        rmdir($dir);
2278
    }
2279
}
2280
2281
/**
2282
 * Control the different steps of the migration through a big switch.
2283
 *
2284
 * @param string        $fromVersion
2285
 * @param EntityManager $manager
2286
 * @param bool          $processFiles
2287
 *
2288
 * @return bool Always returns true except if the process is broken
2289
 */
2290
function migrateSwitch($fromVersion, $manager, $processFiles = true)
2291
{
2292
    error_log('-----------------------------------------');
2293
    error_log('Starting migration process from '.$fromVersion.' ('.date('Y-m-d H:i:s').')');
2294
    //echo '<a class="btn btn-secondary" href="javascript:void(0)" id="details_button">'.get_lang('Details').'</a><br />';
2295
    //echo '<div id="details" style="display:none">';
2296
    $connection = $manager->getConnection();
2297
2298
    switch ($fromVersion) {
2299
        case '1.11.0':
2300
        case '1.11.1':
2301
        case '1.11.2':
2302
        case '1.11.4':
2303
        case '1.11.6':
2304
        case '1.11.8':
2305
        case '1.11.10':
2306
        case '1.11.12':
2307
        case '1.11.14':
2308
            $start = time();
2309
            // Migrate using the migration files located in:
2310
            // /srv/http/chamilo2/src/CoreBundle/Migrations/Schema/V200
2311
            $result = migrate($manager);
2312
            error_log('-----------------------------------------');
2313
2314
            if ($result) {
2315
                error_log('Migrations files were executed ('.date('Y-m-d H:i:s').')');
2316
                $sql = "UPDATE settings_current SET selected_value = '2.0.0'
2317
                        WHERE variable = 'chamilo_database_version'";
2318
                $connection->executeQuery($sql);
2319
                if ($processFiles) {
2320
                    error_log('Update config files');
2321
                    include __DIR__.'/update-files-1.11.0-2.0.0.inc.php';
2322
                    // Only updates the configuration.inc.php with the new version
2323
                    //include __DIR__.'/update-configuration.inc.php';
2324
                }
2325
                $finish = time();
2326
                $total = round(($finish - $start) / 60);
2327
                error_log('Database migration finished:  ('.date('Y-m-d H:i:s').') took '.$total.' minutes');
2328
            } else {
2329
                error_log('There was an error during running migrations. Check error.log');
2330
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2331
            }
2332
            break;
2333
        default:
2334
            break;
2335
    }
2336
2337
    //echo '</div>';
2338
2339
    return true;
2340
}
2341
2342
/**
2343
 * @return string
2344
 */
2345
function generateRandomToken()
2346
{
2347
    return hash('sha1', uniqid(mt_rand(), true));
2348
}
2349
2350
/**
2351
 * This function checks if the given file can be created or overwritten.
2352
 *
2353
 * @param string $file Full path to a file
2354
 *
2355
 * @return string An HTML coloured label showing success or failure
2356
 */
2357
function checkCanCreateFile($file)
2358
{
2359
    if (file_exists($file)) {
2360
        if (is_writable($file)) {
2361
            return Display::label(get_lang('Writable'), 'success');
2362
        } else {
2363
            return Display::label(get_lang('Not writable'), 'important');
2364
        }
2365
    } else {
2366
        $write = @file_put_contents($file, '');
2367
        if (false !== $write) {
2368
            unlink($file);
2369
2370
            return Display::label(get_lang('Writable'), 'success');
2371
        } else {
2372
            return Display::label(get_lang('Not writable'), 'important');
2373
        }
2374
    }
2375
}
2376