Completed
Push — master ( 02c608...a638fe )
by Julito
12:19
created

displayDatabaseParameter()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 23
c 0
b 0
f 0
nc 9
nop 7
dl 0
loc 40
rs 8.9297
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\AccessUrl;
5
use Chamilo\CoreBundle\Entity\BranchSync;
6
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Chamilo\CoreBundle\Entity\Group;
8
use Chamilo\CoreBundle\Entity\TicketCategory;
9
use Chamilo\CoreBundle\Entity\TicketPriority;
10
use Chamilo\CoreBundle\Entity\TicketProject;
11
use Chamilo\CoreBundle\Entity\User;
12
use Chamilo\CoreBundle\Framework\Container;
13
use Chamilo\CoreBundle\ToolChain;
14
use Doctrine\ORM\EntityManager;
15
use Symfony\Component\DependencyInjection\Container as SymfonyContainer;
16
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
17
18
/**
19
 * Chamilo LMS
20
 * This file contains functions used by the install and upgrade scripts.
21
 *
22
 * Ideas for future additions:
23
 * - a function get_old_version_settings to retrieve the config file settings
24
 *   of older versions before upgrading.
25
 */
26
27
define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
28
define('USERNAME_MAX_LENGTH', 100);
29
30
/**
31
 * This function detects whether the system has been already installed.
32
 * It should be used for prevention from second running the installation
33
 * script and as a result - destroying a production system.
34
 *
35
 * @return bool The detected result;
36
 *
37
 * @author Ivan Tcholakov, 2010;
38
 */
39
function isAlreadyInstalledSystem()
40
{
41
    global $new_version, $_configuration;
42
43
    if (empty($new_version)) {
44
        return true; // Must be initialized.
45
    }
46
47
    $current_config_file = api_get_path(CONFIGURATION_PATH).'configuration.php';
48
    if (!file_exists($current_config_file)) {
49
        return false; // Configuration file does not exist, install the system.
50
    }
51
    require $current_config_file;
52
53
    $current_version = null;
54
    if (isset($_configuration['system_version'])) {
55
        $current_version = trim($_configuration['system_version']);
56
    }
57
58
    // If the current version is old, upgrading is assumed, the installer goes ahead.
59
    return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
60
}
61
62
/**
63
 * This function checks if a php extension exists or not and returns an HTML status string.
64
 *
65
 * @param string $extensionName Name of the PHP extension to be checked
66
 * @param string $returnSuccess Text to show when extension is available (defaults to 'Yes')
67
 * @param string $returnFailure Text to show when extension is available (defaults to 'No')
68
 * @param bool   $optional      Whether this extension is optional (then show unavailable text in orange rather than red)
69
 * @param string $enabledTerm   If this string is not null, then use to check if the corresponding parameter is = 1.
70
 *                              If not, mention it's present but not enabled. For example, for opcache, this should be 'opcache.enable'
71
 *
72
 * @return string HTML string reporting the status of this extension. Language-aware.
73
 *
74
 * @author  Christophe Gesch??
75
 * @author  Patrick Cool <[email protected]>, Ghent University
76
 * @author  Yannick Warnier <[email protected]>
77
 */
78
function checkExtension(
79
    $extensionName,
80
    $returnSuccess = 'Yes',
81
    $returnFailure = 'No',
82
    $optional = false,
83
    $enabledTerm = ''
84
) {
85
    if (extension_loaded($extensionName)) {
86
        if (!empty($enabledTerm)) {
87
            $isEnabled = ini_get($enabledTerm);
88
            if ('1' == $isEnabled) {
89
                return Display::label($returnSuccess, 'success');
90
            } else {
91
                if ($optional) {
92
                    return Display::label(get_lang('Extension installed but not enabled'), 'warning');
93
                }
94
95
                return Display::label(get_lang('Extension installed but not enabled'), 'important');
96
            }
97
        }
98
        return Display::label($returnSuccess, 'success');
99
    } else {
100
        if ($optional) {
101
            return Display::label($returnFailure, 'warning');
102
        }
103
104
        return Display::label($returnFailure, 'important');
105
    }
106
}
107
108
/**
109
 * This function checks whether a php setting matches the recommended value.
110
 *
111
 * @param string $phpSetting       A PHP setting to check
112
 * @param string $recommendedValue A recommended value to show on screen
113
 * @param mixed  $returnSuccess    What to show on success
114
 * @param mixed  $returnFailure    What to show on failure
115
 *
116
 * @return string A label to show
117
 *
118
 * @author Patrick Cool <[email protected]>, Ghent University
119
 */
120
function checkPhpSetting(
121
    $phpSetting,
122
    $recommendedValue,
123
    $returnSuccess = false,
124
    $returnFailure = false
125
) {
126
    $currentPhpValue = getPhpSetting($phpSetting);
127
    if ($currentPhpValue == $recommendedValue) {
128
        return Display::label($currentPhpValue.' '.$returnSuccess, 'success');
0 ignored issues
show
Bug introduced by
Are you sure $returnSuccess of type false|mixed can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

128
        return Display::label($currentPhpValue.' './** @scrutinizer ignore-type */ $returnSuccess, 'success');
Loading history...
129
    }
130
131
    return Display::label($currentPhpValue.' '.$returnSuccess, 'important');
132
}
133
134
135
/**
136
 * This function return the value of a php.ini setting if not "" or if exists,
137
 * otherwise return false.
138
 *
139
 * @param string $phpSetting The name of a PHP setting
140
 *
141
 * @return mixed The value of the setting, or false if not found
142
 */
143
function checkPhpSettingExists($phpSetting)
144
{
145
    if ('' != ini_get($phpSetting)) {
146
        return ini_get($phpSetting);
147
    }
148
149
    return false;
150
}
151
152
/**
153
 * Returns a textual value ('ON' or 'OFF') based on a requester 2-state ini- configuration setting.
154
 *
155
 * @param string $val a php ini value
156
 *
157
 * @return bool ON or OFF
158
 *
159
 * @author Joomla <http://www.joomla.org>
160
 */
161
function getPhpSetting($val)
162
{
163
    $value = ini_get($val);
164
    switch ($val) {
165
        case 'display_errors':
166
            global $originalDisplayErrors;
167
            $value = $originalDisplayErrors;
168
            break;
169
    }
170
171
    return '1' == $value ? 'ON' : 'OFF';
172
}
173
174
/**
175
 * This function returns a string "true" or "false" according to the passed parameter.
176
 *
177
 * @param int $var The variable to present as text
178
 *
179
 * @return string the string "true" or "false"
180
 *
181
 * @author Christophe Gesch??
182
 */
183
function trueFalse($var)
184
{
185
    return $var ? 'true' : 'false';
186
}
187
188
/**
189
 * Removes memory and time limits as much as possible.
190
 */
191
function remove_memory_and_time_limits()
192
{
193
    if (function_exists('ini_set')) {
194
        ini_set('memory_limit', -1);
195
        ini_set('max_execution_time', 0);
196
        error_log('Update-db script: memory_limit set to -1', 0);
197
        error_log('Update-db script: max_execution_time 0', 0);
198
    } else {
199
        error_log('Update-db script: could not change memory and time limits', 0);
200
    }
201
}
202
203
/**
204
 * Detects browser's language.
205
 *
206
 * @return string Returns a language identificator, i.e. 'english', 'spanish', ...
207
 *
208
 * @author Ivan Tcholakov, 2010
209
 */
210
function detect_browser_language()
211
{
212
    static $language_index = [
213
        'ar' => 'arabic',
214
        'ast' => 'asturian',
215
        'bg' => 'bulgarian',
216
        'bs' => 'bosnian',
217
        'ca' => 'catalan',
218
        'zh' => 'simpl_chinese',
219
        'zh-tw' => 'trad_chinese',
220
        'cs' => 'czech',
221
        'da' => 'danish',
222
        'prs' => 'dari',
223
        'de' => 'german',
224
        'el' => 'greek',
225
        'en' => 'english',
226
        'es' => 'spanish',
227
        'eo' => 'esperanto',
228
        'eu' => 'basque',
229
        'fa' => 'persian',
230
        'fr' => 'french',
231
        'fur' => 'friulian',
232
        'gl' => 'galician',
233
        'ka' => 'georgian',
234
        'hr' => 'croatian',
235
        'he' => 'hebrew',
236
        'hi' => 'hindi',
237
        'id' => 'indonesian',
238
        'it' => 'italian',
239
        'ko' => 'korean',
240
        'lv' => 'latvian',
241
        'lt' => 'lithuanian',
242
        'mk' => 'macedonian',
243
        'hu' => 'hungarian',
244
        'ms' => 'malay',
245
        'nl' => 'dutch',
246
        'ja' => 'japanese',
247
        'no' => 'norwegian',
248
        'oc' => 'occitan',
249
        'ps' => 'pashto',
250
        'pl' => 'polish',
251
        'pt' => 'portuguese',
252
        'pt-br' => 'brazilian',
253
        'ro' => 'romanian',
254
        'qu' => 'quechua_cusco',
255
        'ru' => 'russian',
256
        'sk' => 'slovak',
257
        'sl' => 'slovenian',
258
        'sr' => 'serbian',
259
        'fi' => 'finnish',
260
        'sv' => 'swedish',
261
        'th' => 'thai',
262
        'tr' => 'turkish',
263
        'uk' => 'ukrainian',
264
        'vi' => 'vietnamese',
265
        'sw' => 'swahili',
266
        'yo' => 'yoruba',
267
    ];
268
269
    $system_available_languages = get_language_folder_list();
270
    $accept_languages = strtolower(str_replace('_', '-', $_SERVER['HTTP_ACCEPT_LANGUAGE']));
271
    foreach ($language_index as $code => $language) {
272
        if (0 === strpos($accept_languages, $code)) {
273
            if (!empty($system_available_languages[$language])) {
274
                return $language;
275
            }
276
        }
277
    }
278
279
    $user_agent = strtolower(str_replace('_', '-', $_SERVER['HTTP_USER_AGENT']));
280
    foreach ($language_index as $code => $language) {
281
        if (@preg_match("/[\[\( ]{$code}[;,_\-\)]/", $user_agent)) {
282
            if (!empty($system_available_languages[$language])) {
283
                return $language;
284
            }
285
        }
286
    }
287
288
    return 'english';
289
}
290
291
/**
292
 * This function checks if the given folder is writable.
293
 *
294
 * @param string $folder     Full path to a folder
295
 * @param bool   $suggestion Whether to show a suggestion or not
296
 *
297
 * @return string
298
 */
299
function check_writable($folder, $suggestion = false)
300
{
301
    if (is_writable($folder)) {
302
        return Display::label(get_lang('Writable'), 'success');
303
    } else {
304
        if ($suggestion) {
305
            return Display::label(get_lang('Not writable'), 'info');
306
        } else {
307
            return Display::label(get_lang('Not writable'), 'important');
308
        }
309
    }
310
}
311
312
/**
313
 * This function checks if the given folder is readable.
314
 *
315
 * @param string $folder     Full path to a folder
316
 * @param bool   $suggestion Whether to show a suggestion or not
317
 *
318
 * @return string
319
 */
320
function checkReadable($folder, $suggestion = false)
321
{
322
    if (is_readable($folder)) {
323
        return Display::label(get_lang('Readable'), 'success');
324
    } else {
325
        if ($suggestion) {
326
            return Display::label(get_lang('Not readable'), 'info');
327
        } else {
328
            return Display::label(get_lang('Not readable'), 'important');
329
        }
330
    }
331
}
332
333
/**
334
 * This function is similar to the core file() function, except that it
335
 * works with line endings in Windows (which is not the case of file()).
336
 *
337
 * @param string $filename
338
 *
339
 * @return array The lines of the file returned as an array
340
 */
341
function file_to_array($filename)
342
{
343
    if (!is_readable($filename) || is_dir($filename)) {
344
        return [];
345
    }
346
    $fp = fopen($filename, 'rb');
347
    $buffer = fread($fp, filesize($filename));
348
    fclose($fp);
349
350
    return explode('<br />', nl2br($buffer));
351
}
352
353
/**
354
 * We assume this function is called from install scripts that reside inside the install folder.
355
 */
356
function set_file_folder_permissions()
357
{
358
    @chmod('.', 0755); //set permissions on install dir
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

358
    /** @scrutinizer ignore-unhandled */ @chmod('.', 0755); //set permissions on install dir

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
359
    @chmod('..', 0755); //set permissions on parent dir of install dir
360
}
361
362
/**
363
 * Write the main system config file.
364
 *
365
 * @param string $path Path to the config file
366
 */
367
function write_system_config_file($path)
368
{
369
    global $dbHostForm;
370
    global $dbPortForm;
371
    global $dbUsernameForm;
372
    global $dbPassForm;
373
    global $dbNameForm;
374
    global $urlAppendPath;
375
    global $languageForm;
376
    global $encryptPassForm;
377
    global $session_lifetime;
378
    global $new_version;
379
    global $new_version_stable;
380
381
    $content = file_get_contents(__DIR__.'/'.SYSTEM_CONFIG_FILENAME);
382
383
    $config['{DATE_GENERATED}'] = date('r');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.
Loading history...
384
    $config['{DATABASE_HOST}'] = $dbHostForm;
385
    $config['{DATABASE_PORT}'] = $dbPortForm;
386
    $config['{DATABASE_USER}'] = $dbUsernameForm;
387
    $config['{DATABASE_PASSWORD}'] = $dbPassForm;
388
    $config['{DATABASE_MAIN}'] = $dbNameForm;
389
390
    $config['{URL_APPEND_PATH}'] = $urlAppendPath;
391
    $config['{PLATFORM_LANGUAGE}'] = $languageForm;
392
    $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
393
    $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm;
394
395
    $config['SESSION_LIFETIME'] = $session_lifetime;
396
    $config['{NEW_VERSION}'] = $new_version;
397
    $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable);
398
399
    foreach ($config as $key => $value) {
400
        $content = str_replace($key, $value, $content);
401
    }
402
    $fp = @fopen($path, 'w');
403
404
    if (!$fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
405
        echo '<strong>
406
                <font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
407
                <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
408
                You probably do not have write access on Chamilo root directory,
409
                i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
410
                Your problems can be related on two possible causes:<br />
411
                <ul>
412
                  <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
413
                  <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>.
414
                  If possible, try to switch it off.</li>
415
                </ul>
416
                <a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
417
                Please go back to step 5.
418
                <p><input type="submit" name="step5" value="&lt; Back" /></p>
419
                </td></tr></table></form></body></html>';
420
        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...
421
    }
422
423
    fwrite($fp, $content);
424
    fclose($fp);
425
}
426
427
/**
428
 * Returns a list of language directories.
429
 */
430
function get_language_folder_list()
431
{
432
    return [
433
        'ar' => 'arabic',
434
        'ast' => 'asturian',
435
        'bg' => 'bulgarian',
436
        'bs' => 'bosnian',
437
        'ca' => 'catalan',
438
        'zh' => 'simpl_chinese',
439
        'zh-tw' => 'trad_chinese',
440
        'cs' => 'czech',
441
        'da' => 'danish',
442
        'prs' => 'dari',
443
        'de' => 'german',
444
        'el' => 'greek',
445
        'en' => 'english',
446
        'es' => 'spanish',
447
        'eo' => 'esperanto',
448
        'eu' => 'basque',
449
        'fa' => 'persian',
450
        'fr' => 'french',
451
        'fur' => 'friulian',
452
        'gl' => 'galician',
453
        'ka' => 'georgian',
454
        'hr' => 'croatian',
455
        'he' => 'hebrew',
456
        'hi' => 'hindi',
457
        'id' => 'indonesian',
458
        'it' => 'italian',
459
        'ko' => 'korean',
460
        'lv' => 'latvian',
461
        'lt' => 'lithuanian',
462
        'mk' => 'macedonian',
463
        'hu' => 'hungarian',
464
        'ms' => 'malay',
465
        'nl' => 'dutch',
466
        'ja' => 'japanese',
467
        'no' => 'norwegian',
468
        'oc' => 'occitan',
469
        'ps' => 'pashto',
470
        'pl' => 'polish',
471
        'pt' => 'portuguese',
472
        'pt-br' => 'brazilian',
473
        'ro' => 'romanian',
474
        'qu' => 'quechua_cusco',
475
        'ru' => 'russian',
476
        'sk' => 'slovak',
477
        'sl' => 'slovenian',
478
        'sr' => 'serbian',
479
        'fi' => 'finnish',
480
        'sv' => 'swedish',
481
        'th' => 'thai',
482
        'tr' => 'turkish',
483
        'uk' => 'ukrainian',
484
        'vi' => 'vietnamese',
485
        'sw' => 'swahili',
486
        'yo' => 'yoruba',
487
    ];
488
}
489
490
/**
491
 * This function returns the value of a parameter from the configuration file.
492
 *
493
 * WARNING - this function relies heavily on global variables $updateFromConfigFile
494
 * and $configFile, and also changes these globals. This can be rewritten.
495
 *
496
 * @param string $param      the parameter of which the value is returned
497
 * @param string $updatePath If we want to give the path rather than take it from POST
498
 *
499
 * @return string the value of the parameter
500
 *
501
 * @author Olivier Brouckaert
502
 * @author Reworked by Ivan Tcholakov, 2010
503
 */
504
function get_config_param($param, $updatePath = '')
505
{
506
    global $configFile, $updateFromConfigFile;
507
508
    // Look if we already have the queried parameter.
509
    if (is_array($configFile) && isset($configFile[$param])) {
510
        return $configFile[$param];
511
    }
512
    if (empty($updatePath) && !empty($_POST['updatePath'])) {
513
        $updatePath = $_POST['updatePath'];
514
    }
515
516
    if (empty($updatePath)) {
517
        $updatePath = api_get_path(SYS_PATH);
518
    }
519
    $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath)));
520
    $updateFromInstalledVersionFile = '';
521
522
    if (empty($updateFromConfigFile)) {
523
        // If update from previous install was requested,
524
        // try to recover config file from Chamilo 1.9.x
525
        if (file_exists($updatePath.'main/inc/conf/configuration.php')) {
526
            $updateFromConfigFile = 'main/inc/conf/configuration.php';
527
        } elseif (file_exists($updatePath.'app/config/configuration.php')) {
528
            $updateFromConfigFile = 'app/config/configuration.php';
529
        } elseif (file_exists($updatePath.'config/configuration.php')) {
530
            $updateFromConfigFile = 'config/configuration.php';
531
        } else {
532
            // Give up recovering.
533
            //error_log('Chamilo Notice: Could not find previous config file at '.$updatePath.'main/inc/conf/configuration.php nor at '.$updatePath.'claroline/inc/conf/claro_main.conf.php in get_config_param(). Will start new config (in '.__FILE__.', line '.__LINE__.')', 0);
534
            return null;
535
        }
536
    }
537
538
    if (file_exists($updatePath.$updateFromConfigFile) &&
539
        !is_dir($updatePath.$updateFromConfigFile)
540
    ) {
541
        require $updatePath.$updateFromConfigFile;
542
        $config = new Laminas\Config\Config($_configuration);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $_configuration does not exist. Did you maybe mean $config?
Loading history...
543
544
        return $config->get($param);
545
    }
546
547
    error_log('Config array could not be found in get_config_param()', 0);
548
549
    return null;
550
}
551
552
/**
553
 * Gets a configuration parameter from the database. Returns returns null on failure.
554
 *
555
 * @param string $param Name of param we want
556
 *
557
 * @return mixed The parameter value or null if not found
558
 */
559
function get_config_param_from_db($param = '')
560
{
561
    $param = Database::escape_string($param);
562
563
    if (false !== ($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'"))) {
564
        if (Database::num_rows($res) > 0) {
565
            $row = Database::fetch_array($res);
566
567
            return $row['selected_value'];
568
        }
569
    }
570
571
    return null;
572
}
573
574
/**
575
 * Connect to the database and returns the entity manager.
576
 *
577
 * @param string $dbHostForm     DB host
578
 * @param string $dbUsernameForm DB username
579
 * @param string $dbPassForm     DB password
580
 * @param string $dbNameForm     DB name
581
 * @param int    $dbPortForm     DB port
582
 *
583
 * @return \Database
584
 */
585
function connectToDatabase(
586
    $dbHostForm,
587
    $dbUsernameForm,
588
    $dbPassForm,
589
    $dbNameForm,
590
    $dbPortForm = 3306
591
) {
592
    $dbParams = [
593
        'driver' => 'pdo_mysql',
594
        'host' => $dbHostForm,
595
        'port' => $dbPortForm,
596
        'user' => $dbUsernameForm,
597
        'password' => $dbPassForm,
598
        'dbname' => $dbNameForm,
599
    ];
600
601
    $database = new \Database();
602
    $database->connect($dbParams);
603
604
    return $database;
605
}
606
607
/**
608
 * This function prints class=active_step $current_step=$param.
609
 *
610
 * @param int $param A step in the installer process
611
 *
612
 * @author Patrick Cool <[email protected]>, Ghent University
613
 */
614
function step_active($param)
615
{
616
    global $current_step;
617
    if ($param == $current_step) {
618
        echo 'active';
619
    }
620
}
621
622
/**
623
 * This function displays the Step X of Y -.
624
 *
625
 * @return string String that says 'Step X of Y' with the right values
626
 */
627
function display_step_sequence()
628
{
629
    global $current_step;
630
631
    return get_lang('Step'.$current_step).' &ndash; ';
632
}
633
634
/**
635
 * Displays a drop down box for selection the preferred language.
636
 */
637
function display_language_selection_box(
638
    $name = 'language_list',
639
    $default_language = 'english'
640
) {
641
    // Reading language list.
642
    $language_list = get_language_folder_list();
643
644
    // Sanity checks due to the possibility for customizations.
645
    if (!is_array($language_list) || empty($language_list)) {
646
        $language_list = ['en' => 'English'];
647
    }
648
649
    // Sorting again, if it is necessary.
650
    //asort($language_list);
651
652
    // More sanity checks.
653
    if (!array_key_exists($default_language, $language_list)) {
654
        if (array_key_exists('en', $language_list)) {
655
            $default_language = 'en';
656
        } else {
657
            $language_keys = array_keys($language_list);
658
            $default_language = $language_keys[0];
659
        }
660
    }
661
662
    // Displaying the box.
663
    $html = Display::select(
664
        'language_list',
665
        $language_list,
666
        $default_language,
667
        ['class' => 'selectpicker'],
668
        false
669
    );
670
671
    return $html;
672
}
673
674
/**
675
 * This function displays a language dropdown box so that the installatioin
676
 * can be done in the language of the user.
677
 */
678
function display_language_selection()
679
{
680
    ?>
681
        <div class="install-icon">
682
            <img width="150px;" src="chamilo-install.svg"/>
683
        </div>
684
        <h2 class="install-title">
685
            <?php echo display_step_sequence(); ?>
686
            <?php echo get_lang('Installation Language'); ?>
687
        </h2>
688
        <label for="language_list"><?php echo get_lang('Please select installation language'); ?></label>
689
        <div class="form-group">
690
            <?php echo display_language_selection_box('language_list', api_get_interface_language()); ?>
691
        </div>
692
        <button type="submit" name="step1" class="btn btn-success" value="<?php echo get_lang('Next'); ?>">
693
            <em class="fa fa-forward"> </em>
694
            <?php echo get_lang('Next'); ?>
695
        </button>
696
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
697
        <div class="RequirementHeading">
698
            <?php echo get_lang('Cannot find your language in the list? Contact us at [email protected] to contribute as a translator.'); ?>
699
        </div>
700
<?php
701
}
702
703
/**
704
 * This function displays the requirements for installing Chamilo.
705
 *
706
 * @param string $installType
707
 * @param bool   $badUpdatePath
708
 * @param bool   $badUpdatePath
709
 * @param string $updatePath            The updatePath given (if given)
710
 * @param array  $update_from_version_8 The different subversions from version 1.9
711
 *
712
 * @author unknow
713
 * @author Patrick Cool <[email protected]>, Ghent University
714
 */
715
function display_requirements(
716
    $installType,
717
    $badUpdatePath,
718
    $updatePath = '',
719
    $update_from_version_8 = []
720
) {
721
    global $_setting, $originalMemoryLimit;
722
723
    $dir = api_get_path(SYS_ARCHIVE_PATH).'temp/';
724
    $fileToCreate = 'test';
725
726
    $perms_dir = [0777, 0755, 0775, 0770, 0750, 0700];
727
    $perms_fil = [0666, 0644, 0664, 0660, 0640, 0600];
728
    $course_test_was_created = false;
729
    $dir_perm_verified = 0777;
730
731
    foreach ($perms_dir as $perm) {
732
        $r = @mkdir($dir, $perm);
733
        if (true === $r) {
734
            $dir_perm_verified = $perm;
735
            $course_test_was_created = true;
736
            break;
737
        }
738
    }
739
740
    $fil_perm_verified = 0666;
741
    $file_course_test_was_created = false;
742
    if (is_dir($dir)) {
743
        foreach ($perms_fil as $perm) {
744
            if (true == $file_course_test_was_created) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
745
                break;
746
            }
747
            $r = @touch($dir.'/'.$fileToCreate, $perm);
748
            if (true === $r) {
749
                $fil_perm_verified = $perm;
750
                $file_course_test_was_created = true;
751
            }
752
        }
753
    }
754
755
    @unlink($dir.'/'.$fileToCreate);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

755
    /** @scrutinizer ignore-unhandled */ @unlink($dir.'/'.$fileToCreate);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
756
    @rmdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for rmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

756
    /** @scrutinizer ignore-unhandled */ @rmdir($dir);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
757
758
    echo '<h2 class="install-title">'.display_step_sequence().get_lang('Requirements')."</h2>";
759
    echo '<div class="RequirementText">';
760
    echo '<strong>'.get_lang('Please read the following requirements thoroughly.').'</strong><br />';
761
    echo get_lang('For more details').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('Read the installation guide').'</a>.<br />'."\n";
762
763
    if ('update' == $installType) {
764
        echo get_lang('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 />';
765
    }
766
    echo '</div>';
767
768
    //  SERVER REQUIREMENTS
769
    echo '<h4 class="install-subtitle">'.get_lang('Server requirements').'</h4>';
770
    $timezone = checkPhpSettingExists('date.timezone');
771
    if (!$timezone) {
772
        echo "<div class='alert alert-warning'>
773
            <i class=\"fa fa-exclamation-triangle\" aria-hidden=\"true\"></i>&nbsp;".
774
            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>";
775
    }
776
777
    echo '<div class="install-requirement">'.get_lang('Server requirementsInfo').'</div>';
778
    echo '<div class="table-responsive">';
779
    echo '<table class="table table-bordered">
780
            <tr>
781
                <td class="requirements-item">'.get_lang('PHP version').' >= '.REQUIRED_PHP_VERSION.'</td>
782
                <td class="requirements-value">';
783
    if (version_compare(phpversion(), REQUIRED_PHP_VERSION, '>=') > 1) {
784
        echo '<strong class="text-danger">'.get_lang('PHP versionError').'</strong>';
785
    } else {
786
        echo '<strong class="text-success">'.get_lang('PHP versionOK').' '.phpversion().'</strong>';
787
    }
788
    echo '</td>
789
            </tr>
790
            <tr>
791
                <td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('Support').'</td>
792
                <td class="requirements-value">'.checkExtension('session', get_lang('Yes'), get_lang('Sessions extension not available')).'</td>
793
            </tr>
794
            <tr>
795
                <td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">pdo_mysql</a> '.get_lang('Support').'</td>
796
                <td class="requirements-value">'.checkExtension('pdo_mysql', get_lang('Yes'), get_lang('MySQL extension not available')).'</td>
797
            </tr>
798
            <tr>
799
                <td class="requirements-item"><a href="http://php.net/manual/en/book.zip.php" target="_blank">Zip</a> '.get_lang('Support').'</td>
800
                <td class="requirements-value">'.checkExtension('zip', get_lang('Yes'), get_lang('Extension not available')).'</td>
801
            </tr>
802
            <tr>
803
                <td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('Support').'</td>
804
                <td class="requirements-value">'.checkExtension('zlib', get_lang('Yes'), get_lang('Zlib extension not available')).'</td>
805
            </tr>
806
            <tr>
807
                <td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('Support').'</td>
808
                <td class="requirements-value">'.checkExtension('pcre', get_lang('Yes'), get_lang('PCRE extension not available')).'</td>
809
            </tr>
810
            <tr>
811
                <td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('Support').'</td>
812
                <td class="requirements-value">'.checkExtension('xml', get_lang('Yes'), get_lang('No')).'</td>
813
            </tr>
814
            <tr>
815
                <td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('Support').'</td>
816
                <td class="requirements-value">'.checkExtension('intl', get_lang('Yes'), get_lang('No')).'</td>
817
            </tr>
818
               <tr>
819
                <td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('Support').'</td>
820
                <td class="requirements-value">'.checkExtension('json', get_lang('Yes'), get_lang('No')).'</td>
821
            </tr>
822
             <tr>
823
                <td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('Support').'</td>
824
                <td class="requirements-value">'.checkExtension('gd', get_lang('Yes'), get_lang('GD Extension not available')).'</td>
825
            </tr>
826
            <tr>
827
                <td class="requirements-item"><a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>'.get_lang('Support').'</td>
828
                <td class="requirements-value">'.checkExtension('curl', get_lang('Yes'), get_lang('No')).'</td>
829
            </tr>
830
            <tr>
831
                <td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('Support').'</td>
832
                <td class="requirements-value">'.checkExtension('mbstring', get_lang('Yes'), get_lang('MBString extension not available'), true).'</td>
833
            </tr>
834
           <tr>
835
                <td class="requirements-item"><a href="http://php.net/manual/en/book.exif.php" target="_blank">Exif</a> '.get_lang('Support').'</td>
836
                <td class="requirements-value">'.checkExtension('exif', get_lang('Yes'), get_lang('Exif extension not available'), true).'</td>
837
            </tr>
838
            <tr>
839
                <td class="requirements-item"><a href="http://php.net/opcache" target="_blank">Zend OpCache</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
840
                <td class="requirements-value">'.checkExtension('Zend OPcache', get_lang('Yes'), get_lang('No'), true, 'opcache.enable').'</td>
841
            </tr>
842
            <tr>
843
                <td class="requirements-item"><a href="http://php.net/apcu" target="_blank">APCu</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
844
                <td class="requirements-value">'.checkExtension('apcu', get_lang('Yes'), get_lang('No'), true, 'apc.enabled').'</td>
845
            </tr>
846
            <tr>
847
                <td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
848
                <td class="requirements-value">'.checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
849
            </tr>
850
            <tr>
851
                <td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
852
                <td class="requirements-value">'.checkExtension('ldap', get_lang('Yes'), get_lang('LDAP Extension not available'), true).'</td>
853
            </tr>
854
            <tr>
855
                <td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
856
                <td class="requirements-value">'.checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
857
            </tr>
858
        </table>';
859
    echo '</div>';
860
861
    // RECOMMENDED SETTINGS
862
    // Note: these are the settings for Joomla, does this also apply for Chamilo?
863
    // Note: also add upload_max_filesize here so that large uploads are possible
864
    echo '<h4 class="install-subtitle">'.get_lang('(recommended) settings').'</h4>';
865
    echo '<div class="install-requirement">'.get_lang('(recommended) settingsInfo').'</div>';
866
    echo '<div class="table-responsive">';
867
    echo '<table class="table table-bordered">
868
            <tr>
869
                <th>'.get_lang('Setting').'</th>
870
                <th>'.get_lang('(recommended)').'</th>
871
                <th>'.get_lang('Currently').'</th>
872
            </tr>
873
874
            <tr>
875
                <td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
876
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
877
                <td class="requirements-value">'.checkPhpSetting('display_errors', 'OFF').'</td>
878
            </tr>
879
            <tr>
880
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
881
                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
882
                <td class="requirements-value">'.checkPhpSetting('file_uploads', 'ON').'</td>
883
            </tr>
884
            <tr>
885
                <td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
886
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
887
                <td class="requirements-value">'.checkPhpSetting('session.auto_start', 'OFF').'</td>
888
            </tr>
889
            <tr>
890
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
891
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
892
                <td class="requirements-value">'.checkPhpSetting('short_open_tag', 'OFF').'</td>
893
            </tr>
894
            <tr>
895
                <td class="requirements-item"><a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
896
                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
897
                <td class="requirements-value">'.checkPhpSetting('session.cookie_httponly', 'ON').'</td>
898
            </tr>
899
            <tr>
900
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
901
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M', 'success').'</td>
902
                <td class="requirements-value">'.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'</td>
903
            </tr>
904
            <tr>
905
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
906
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_POST_MAX_SIZE.'M', 'success').'</td>
907
                <td class="requirements-value">'.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'</td>
908
            </tr>
909
            <tr>
910
                <td class="requirements-item"><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
911
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_MEMORY_LIMIT.'M', 'success').'</td>
912
                <td class="requirements-value">'.compare_setting_values($originalMemoryLimit, REQUIRED_MIN_MEMORY_LIMIT).'</td>
913
            </tr>
914
          </table>';
915
    echo '</div>';
916
917
    // DIRECTORY AND FILE PERMISSIONS
918
    echo '<h4 class="install-subtitle">'.get_lang('Directory and files permissions').'</h4>';
919
    echo '<div class="install-requirement">'.get_lang('Directory and files permissionsInfo').'</div>';
920
    echo '<div class="table-responsive">';
921
922
    $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified;
923
    $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified;
924
925
    $dir_perm = Display::label('0'.decoct($dir_perm_verified), 'info');
926
    $file_perm = Display::label('0'.decoct($fil_perm_verified), 'info');
927
928
    $oldConf = '';
929
    if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) {
930
        $oldConf = '<tr>
931
            <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'inc/conf</td>
932
            <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').'</td>
933
        </tr>';
934
    }
935
    $basePath = api_get_path(SYMFONY_SYS_PATH);
936
    echo '<table class="table table-bordered">
937
            '.$oldConf.'
938
            <tr>
939
                <td class="requirements-item">'.$basePath.'var/</td>
940
                <td class="requirements-value">'.check_writable($basePath.'var').'</td>
941
            </tr>
942
            <tr>
943
                <td class="requirements-item">'.$basePath.'.env.local</td>
944
                <td class="requirements-value">'.checkCanCreateFile($basePath.'.env.local').'</td>
945
            </tr>
946
            <tr>
947
                <td class="requirements-item">'.$basePath.'config/</td>
948
                <td class="requirements-value">'.check_writable($basePath.'config').'</td>
949
            </tr>
950
            <tr>
951
                <td class="requirements-item">'.get_lang('Permissions for new directories').'</td>
952
                <td class="requirements-value">'.$dir_perm.' </td>
953
            </tr>
954
            <tr>
955
                <td class="requirements-item">'.get_lang('Permissions for new files').'</td>
956
                <td class="requirements-value">'.$file_perm.' </td>
957
            </tr>
958
        </table>';
959
960
    echo '</div>';
961
962
    if ('update' === $installType && (empty($updatePath) || $badUpdatePath)) {
963
        if ($badUpdatePath) {
964
            ?>
965
            <div class="alert alert-warning">
966
                <?php echo get_lang('Error'); ?>!<br />
967
                Chamilo <?php echo implode('|', $update_from_version_8).' '.get_lang('has not been found in that directory'); ?>.
968
            </div>
969
        <?php
970
        } else {
971
            echo '<br />';
972
        } ?>
973
            <div class="row">
974
                <div class="col-md-12">
975
                    <p><?php echo get_lang('Old version\'s root path'); ?>:
976
                        <input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath)) ? htmlentities($updatePath) : ''; ?>" />
977
                    </p>
978
                    <p>
979
                        <div class="btn-group">
980
                            <button type="submit" class="btn btn-secondary" name="step1" value="<?php echo get_lang('Back'); ?>" >
981
                                <em class="fa fa-backward"> <?php echo get_lang('Back'); ?></em>
982
                            </button>
983
                            <input type="hidden" name="is_executable" id="is_executable" value="-" />
984
                            <button type="submit" class="btn btn-success" name="<?php echo isset($_POST['step2_update_6']) ? 'step2_update_6' : 'step2_update_8'; ?>" value="<?php echo get_lang('Next'); ?> &gt;" >
985
                                <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
986
                            </button>
987
                        </div>
988
                    </p>
989
                </div>
990
            </div>
991
        <?php
992
    } else {
993
        $error = false;
994
        // First, attempt to set writing permissions if we don't have them yet
995
        //$perm = api_get_permissions_for_new_directories();
996
        $perm = octdec('0777');
997
        //$perm_file = api_get_permissions_for_new_files();
998
        $perm_file = octdec('0666');
999
        $notWritable = [];
1000
1001
        $checked_writable = api_get_path(SYS_PUBLIC_PATH);
1002
        if (!is_writable($checked_writable)) {
1003
            $notWritable[] = $checked_writable;
1004
            @chmod($checked_writable, $perm);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1004
            /** @scrutinizer ignore-unhandled */ @chmod($checked_writable, $perm);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1005
        }
1006
1007
        if (false == $course_test_was_created) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1008
            error_log('Installer: Could not create test course - Make sure permissions are fine.');
1009
            $error = true;
1010
        }
1011
1012
        $checked_writable = api_get_path(CONFIGURATION_PATH).'configuration.php';
1013
        if (file_exists($checked_writable) && !is_writable($checked_writable)) {
1014
            $notWritable[] = $checked_writable;
1015
            @chmod($checked_writable, $perm_file);
1016
        }
1017
1018
        // Second, if this fails, report an error
1019
        //--> The user would have to adjust the permissions manually
1020
        if (count($notWritable) > 0) {
1021
            error_log('Installer: At least one needed directory or file is not writeable');
1022
            $error = true; ?>
1023
            <div class="text-danger">
1024
                <h3 class="text-center"><?php echo get_lang('Warning !'); ?></h3>
1025
                <p>
1026
                    <?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>'); ?>
1027
                </p>
1028
            </div>
1029
            <?php
1030
            echo '<ul>';
1031
            foreach ($notWritable as $value) {
1032
                echo '<li class="text-danger">'.$value.'</li>';
1033
            }
1034
            echo '</ul>';
1035
        } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
1036
            // Check wether a Chamilo configuration file already exists.
1037
            echo '<div class="alert alert-warning"><h4><center>';
1038
            echo get_lang('Warning !ExistingLMSInstallationDetected');
1039
            echo '</center></h4></div>';
1040
        }
1041
1042
        $deprecated = [
1043
            api_get_path(SYS_CODE_PATH).'exercice/',
1044
            api_get_path(SYS_CODE_PATH).'newscorm/',
1045
            api_get_path(SYS_PLUGIN_PATH).'ticket/',
1046
            api_get_path(SYS_PLUGIN_PATH).'skype/',
1047
        ];
1048
        $deprecatedToRemove = [];
1049
        foreach ($deprecated as $deprecatedDirectory) {
1050
            if (!is_dir($deprecatedDirectory)) {
1051
                continue;
1052
            }
1053
            $deprecatedToRemove[] = $deprecatedDirectory;
1054
        }
1055
1056
        if (count($deprecatedToRemove) > 0) {
1057
            ?>
1058
            <p class="text-danger"><?php echo get_lang('Warning !ForDeprecatedDirectoriesForUpgrade'); ?></p>
1059
            <ul>
1060
                <?php foreach ($deprecatedToRemove as $deprecatedDirectory) {
1061
                ?>
1062
                    <li class="text-danger"><?php echo $deprecatedDirectory; ?></li>
1063
                <?php
1064
            } ?>
1065
            </ul>
1066
            <?php
1067
        }
1068
1069
        // And now display the choice buttons (go back or install)?>
1070
        <p align="center" style="padding-top:15px">
1071
            <button type="submit" name="step1" class="btn btn-default" onclick="javascript: window.location='index.php'; return false;" value="<?php echo get_lang('Previous'); ?>" >
1072
                <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1073
            </button>
1074
            <button type="submit" name="step2_install" class="btn btn-success" value="<?php echo get_lang("New installation"); ?>" <?php if ($error) {
1075
            echo 'disabled="disabled"';
1076
        } ?> >
1077
                <em class="fa fa-forward"> </em> <?php echo get_lang('New installation'); ?>
1078
            </button>
1079
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
1080
            <button type="submit" class="btn btn-default" <?php echo !$error ?: 'disabled="disabled"'; ?> name="step2_update_8" value="Upgrade from Chamilo 1.9.x">
1081
                <em class="fa fa-forward" aria-hidden="true"></em> <?php echo get_lang('Upgrade Chamilo LMS version'); ?>
1082
            </button>
1083
            </p>
1084
        <?php
1085
    }
1086
}
1087
1088
/**
1089
 * Displays the license (GNU GPL) as step 2, with
1090
 * - an "I accept" button named step3 to proceed to step 3;
1091
 * - a "Back" button named step1 to go back to the first step.
1092
 */
1093
function display_license_agreement()
1094
{
1095
    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Licence').'</h2>';
1096
    echo '<p>'.get_lang('Chamilo is free software distributed under the GNU General Public licence (GPL).').'</p>';
1097
    echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('Printable version').'</a></p>';
1098
    echo '</div>'; ?>
1099
    <div class="form-group">
1100
        <pre style="overflow: auto; height: 200px; margin-top: 5px;">
1101
            <?php echo api_htmlentities(@file_get_contents(api_get_path(SYMFONY_SYS_PATH).'documentation/license.txt')); ?>
1102
        </pre>
1103
    </div>
1104
    <div class="form-group form-check">
1105
        <input type="checkbox" name="accept" id="accept_licence" value="1">
1106
        <label for="accept_licence"><?php echo get_lang('I Accept'); ?></label>
1107
    </div>
1108
    <div class="row">
1109
        <div class="col-md-12">
1110
            <p class="alert alert-info"><?php echo 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.'); ?></p>
1111
        </div>
1112
    </div>
1113
1114
    <!-- Contact information form -->
1115
    <div class="section-parameters">
1116
        <a href="javascript://" class = "advanced_parameters" >
1117
        <span id="img_plus_and_minus">&nbsp;<i class="fa fa-eye" aria-hidden="true"></i>&nbsp;<?php echo get_lang('Contact information'); ?></span>
1118
        </a>
1119
    </div>
1120
1121
    <div id="id_contact_form" style="display:block">
1122
        <div class="normal-message"><?php echo get_lang('Contact informationDescription'); ?></div>
1123
        <div id="contact_registration">
1124
            <p><?php echo get_contact_registration_form(); ?></p><br />
1125
        </div>
1126
    </div>
1127
    <div class="text-center">
1128
    <button type="submit" class="btn btn-default" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" >
1129
        <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1130
    </button>
1131
    <input type="hidden" name="is_executable" id="is_executable" value="-" />
1132
    <button type="submit" id="license-next" class="btn btn-success" name="step3" onclick="javascript: if(!document.getElementById('accept_licence').checked) { alert('<?php echo get_lang('You must accept the licence'); ?>');return false;}" value="<?php echo get_lang('Next'); ?> &gt;" >
1133
        <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1134
    </button>
1135
    </div>
1136
    <?php
1137
}
1138
1139
/**
1140
 * Get contact registration form.
1141
 */
1142
function get_contact_registration_form()
1143
{
1144
    $html = '
1145
   <div class="form-horizontal">
1146
    <div class="panel panel-default">
1147
    <div class="panel-body">
1148
    <div id="div_sent_information"></div>
1149
    <div class="form-group row">
1150
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Name').'</label>
1151
            <div class="col-sm-9"><input id="person_name" class="form-control" type="text" name="person_name" size="30" /></div>
1152
    </div>
1153
    <div class="form-group row">
1154
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('e-mail').'</label>
1155
            <div class="col-sm-9"><input id="person_email" class="form-control" type="text" name="person_email" size="30" /></div>
1156
    </div>
1157
    <div class="form-group row">
1158
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your company\'s name').'</label>
1159
            <div class="col-sm-9"><input id="company_name" class="form-control" type="text" name="company_name" size="30" /></div>
1160
    </div>
1161
    <div class="form-group row">
1162
        <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your company\'s activity').'</label>
1163
        <div class="col-sm-9">
1164
            <select class="selectpicker show-tick" name="company_activity" id="company_activity" >
1165
                <option value="">--- '.get_lang('Select one').' ---</option>
1166
                <Option value="Advertising/Marketing/PR">Advertising/Marketing/PR</Option><Option value="Agriculture/Forestry">Agriculture/Forestry</Option>
1167
                <Option value="Architecture">Architecture</Option><Option value="Banking/Finance">Banking/Finance</Option>
1168
                <Option value="Biotech/Pharmaceuticals">Biotech/Pharmaceuticals</Option><Option value="Business Equipment">Business Equipment</Option>
1169
                <Option value="Business Services">Business Services</Option><Option value="Construction">Construction</Option>
1170
                <Option value="Consulting/Research">Consulting/Research</Option><Option value="Education">Education</Option>
1171
                <Option value="Engineering">Engineering</Option><Option value="Environmental">Environmental</Option>
1172
                <Option value="Government">Government</Option><Option value="Healthcare">Health Care</Option>
1173
                <Option value="Hospitality/Lodging/Travel">Hospitality/Lodging/Travel</Option><Option value="Insurance">Insurance</Option>
1174
                <Option value="Legal">Legal</Option><Option value="Manufacturing">Manufacturing</Option>
1175
                <Option value="Media/Entertainment">Media/Entertainment</Option><Option value="Mortgage">Mortgage</Option>
1176
                <Option value="Non-Profit">Non-Profit</Option><Option value="Real Estate">Real Estate</Option>
1177
                <Option value="Restaurant">Restaurant</Option><Option value="Retail">Retail</Option>
1178
                <Option value="Shipping/Transportation">Shipping/Transportation</Option>
1179
                <Option value="Technology">Technology</Option><Option value="Telecommunications">Telecommunications</Option>
1180
                <Option value="Other">Other</Option>
1181
            </select>
1182
        </div>
1183
    </div>
1184
1185
    <div class="form-group row">
1186
        <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your job\'s description').'</label>
1187
        <div class="col-sm-9">
1188
            <select class="selectpicker show-tick" name="person_role" id="person_role" >
1189
                <option value="">--- '.get_lang('Select one').' ---</option>
1190
                <Option value="Administration">Administration</Option><Option value="CEO/President/ Owner">CEO/President/ Owner</Option>
1191
                <Option value="CFO">CFO</Option><Option value="CIO/CTO">CIO/CTO</Option>
1192
                <Option value="Consultant">Consultant</Option><Option value="Customer Service">Customer Service</Option>
1193
                <Option value="Engineer/Programmer">Engineer/Programmer</Option><Option value="Facilities/Operations">Facilities/Operations</Option>
1194
                <Option value="Finance/ Accounting Manager">Finance/ Accounting Manager</Option><Option value="Finance/ Accounting Staff">Finance/ Accounting Staff</Option>
1195
                <Option value="General Manager">General Manager</Option><Option value="Human Resources">Human Resources</Option>
1196
                <Option value="IS/IT Management">IS/IT Management</Option><Option value="IS/ IT Staff">IS/ IT Staff</Option>
1197
                <Option value="Marketing Manager">Marketing Manager</Option><Option value="Marketing Staff">Marketing Staff</Option>
1198
                <Option value="Partner/Principal">Partner/Principal</Option><Option value="Purchasing Manager">Purchasing Manager</Option>
1199
                <Option value="Sales/ Business Dev. Manager">Sales/ Business Dev. Manager</Option><Option value="Sales/ Business Dev.">Sales/ Business Dev.</Option>
1200
                <Option value="Vice President/Senior Manager">Vice President/Senior Manager</Option><Option value="Other">Other</Option>
1201
            </select>
1202
        </div>
1203
    </div>
1204
1205
    <div class="form-group row">
1206
        <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Your company\'s home country').'</label>
1207
        <div class="col-sm-9">'.get_countries_list_from_array(true).'</div>
1208
    </div>
1209
    <div class="form-group row">
1210
        <label class="col-sm-3">'.get_lang('Company city').'</label>
1211
        <div class="col-sm-9">
1212
                <input type="text" class="form-control" id="company_city" name="company_city" size="30" />
1213
        </div>
1214
    </div>
1215
    <div class="form-group row">
1216
        <label class="col-sm-3">'.get_lang('Preferred contact language').'</label>
1217
        <div class="col-sm-9">
1218
            <select class="selectpicker show-tick" id="language" name="language">
1219
                <option value="bulgarian">Bulgarian</option>
1220
                <option value="indonesian">Bahasa Indonesia</option>
1221
                <option value="bosnian">Bosanski</option>
1222
                <option value="german">Deutsch</option>
1223
                <option selected="selected" value="english">English</option>
1224
                <option value="spanish">Spanish</option>
1225
                <option value="french">Français</option>
1226
                <option value="italian">Italian</option>
1227
                <option value="hungarian">Magyar</option>
1228
                <option value="dutch">Nederlands</option>
1229
                <option value="brazilian">Português do Brasil</option>
1230
                <option value="portuguese">Português europeu</option>
1231
                <option value="slovenian">Slovenčina</option>
1232
            </select>
1233
        </div>
1234
    </div>
1235
1236
    <div class="form-group row">
1237
        <label class="col-sm-3">'.get_lang('Do you have the power to take financial decisions on behalf of your company?').'</label>
1238
        <div class="col-sm-9">
1239
            <div class="radio">
1240
                <label>
1241
                    <input type="radio" name="financial_decision" id="financial_decision1" value="1" checked /> '.get_lang('Yes').'
1242
                </label>
1243
            </div>
1244
            <div class="radio">
1245
                <label>
1246
                    <input type="radio" name="financial_decision" id="financial_decision2" value="0" /> '.get_lang('No').'
1247
                </label>
1248
            </div>
1249
        </div>
1250
    </div>
1251
    <div class="clear"></div>
1252
    <div class="form-group row">
1253
            <div class="col-sm-3">&nbsp;</div>
1254
            <div class="col-sm-9"><button type="button" class="btn btn-default" onclick="javascript:send_contact_information();" value="'.get_lang('Send information').'" ><em class="fa fa-floppy-o"></em> '.get_lang('Send information').'</button> <span id="loader-button"></span></div>
1255
    </div>
1256
    <div class="form-group row">
1257
            <div class="col-sm-3">&nbsp;</div>
1258
            <div class="col-sm-9"><span class="form_required">*</span><small>'.get_lang('Mandatory field').'</small></div>
1259
    </div></div></div>
1260
    </div>';
1261
1262
    return $html;
1263
}
1264
1265
/**
1266
 * Displays a parameter in a table row.
1267
 * Used by the display_database_settings_form function.
1268
 *
1269
 * @param   string  Type of install
1270
 * @param   string  Name of parameter
1271
 * @param   string  Field name (in the HTML form)
1272
 * @param   string  Field value
1273
 * @param   string  Extra notice (to show on the right side)
1274
 * @param   bool Whether to display in update mode
1275
 * @param   string  Additional attribute for the <tr> element
1276
 */
1277
function displayDatabaseParameter(
1278
    $installType,
1279
    $parameterName,
1280
    $formFieldName,
1281
    $parameterValue,
1282
    $extra_notice,
1283
    $displayWhenUpdate = true,
1284
    $tr_attribute = ''
1285
) {
1286
    //echo "<tr ".$tr_attribute.">";
1287
    echo "<label class='col-sm-4'>$parameterName</label>";
1288
1289
    if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) {
1290
        echo '<input
1291
                type="hidden"
1292
                name="'.$formFieldName.'"
1293
                id="'.$formFieldName.'"
1294
                value="'.api_htmlentities($parameterValue).'" />'.$parameterValue;
1295
    } else {
1296
        $inputType = 'dbPassForm' === $formFieldName ? 'password' : 'text';
1297
1298
        //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on
1299
        $maxLength = 'dbPrefixForm' === $formFieldName ? '15' : MAX_FORM_FIELD_LENGTH;
1300
        if (INSTALL_TYPE_UPDATE == $installType) {
1301
            echo '<input
1302
                type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'"
1303
                value="'.api_htmlentities($parameterValue).'" />';
1304
            echo api_htmlentities($parameterValue);
1305
        } else {
1306
            echo '<div class="col-sm-5">
1307
                    <input
1308
                        type="'.$inputType.'"
1309
                        class="form-control"
1310
                        size="'.DATABASE_FORM_FIELD_DISPLAY_LENGTH.'"
1311
                        maxlength="'.$maxLength.'"
1312
                        name="'.$formFieldName.'"
1313
                        id="'.$formFieldName.'"
1314
                        value="'.api_htmlentities($parameterValue).'" />
1315
                  </div>';
1316
            echo '<div class="col-sm-3">'.$extra_notice.'</div>';
1317
        }
1318
    }
1319
}
1320
1321
/**
1322
 * Displays step 3 - a form where the user can enter the installation settings
1323
 * regarding the databases - login and password, names, prefixes, single
1324
 * or multiple databases, tracking or not...
1325
 *
1326
 * @param string $installType
1327
 * @param string $dbHostForm
1328
 * @param string $dbUsernameForm
1329
 * @param string $dbPassForm
1330
 * @param string $dbNameForm
1331
 * @param int    $dbPortForm
1332
 * @param string $installationProfile
1333
 */
1334
function display_database_settings_form(
1335
    $installType,
1336
    $dbHostForm,
1337
    $dbUsernameForm,
1338
    $dbPassForm,
1339
    $dbNameForm,
1340
    $dbPortForm = 3306,
1341
    $installationProfile = ''
1342
) {
1343
    if ('update' === $installType) {
1344
        global $_configuration;
1345
        $dbHostForm = $_configuration['db_host'];
1346
        $dbUsernameForm = $_configuration['db_user'];
1347
        $dbPassForm = $_configuration['db_password'];
1348
        $dbNameForm = $_configuration['main_database'];
1349
        $dbPortForm = isset($_configuration['db_port']) ? $_configuration['db_port'] : '';
1350
1351
        echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Database settings').'</h2></div>';
1352
        echo '<div class="RequirementContent">';
1353
        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!');
1354
        echo '</div>';
1355
    } else {
1356
        echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Database settings').'</h2></div>';
1357
        echo '<div class="RequirementContent">';
1358
        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.');
1359
        echo '</div>';
1360
    } ?>
1361
    <div class="panel panel-default">
1362
        <div class="panel-body">
1363
        <div class="form-group row">
1364
            <label class="col-sm-4"><?php echo get_lang('Database Host'); ?> </label>
1365
            <?php if ('update' === $installType) {
1366
        ?>
1367
            <div class="col-sm-5">
1368
                <input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?>
1369
            </div>
1370
            <div class="col-sm-3"></div>
1371
            <?php
1372
    } else {
1373
        ?>
1374
            <div class="col-sm-5">
1375
                <input type="text" class="form-control" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" />
1376
            </div>
1377
            <div class="col-sm-3"><?php echo get_lang('ex.').' localhost'; ?></div>
1378
            <?php
1379
    } ?>
1380
        </div>
1381
        <div class="form-group row">
1382
            <label class="col-sm-4"><?php echo get_lang('Port'); ?> </label>
1383
            <?php if ('update' === $installType) {
1384
        ?>
1385
            <div class="col-sm-5">
1386
                <input type="hidden" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" /><?php echo $dbPortForm; ?>
1387
            </div>
1388
            <div class="col-sm-3"></div>
1389
            <?php
1390
    } else {
1391
        ?>
1392
            <div class="col-sm-5">
1393
                <input type="text" class="form-control" size="25" maxlength="50" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" />
1394
            </div>
1395
            <div class="col-sm-3"><?php echo get_lang('ex.').' 3306'; ?></div>
1396
            <?php
1397
    }
1398
            echo '</div><div class="form-group row">';
1399
            //database user username
1400
            $example_login = get_lang('ex.').' root';
1401
            displayDatabaseParameter(
1402
                $installType,
1403
                get_lang('Database Login'),
1404
                'dbUsernameForm',
1405
                $dbUsernameForm,
1406
                $example_login
1407
            );
1408
            echo '</div><div class="form-group row">';
1409
            //database user password
1410
            $example_password = get_lang('ex.').' '.api_generate_password();
1411
            displayDatabaseParameter($installType, get_lang('Database Password'), 'dbPassForm', $dbPassForm, $example_password);
1412
            echo '</div><div class="form-group row">';
1413
            // Database Name fix replace weird chars
1414
            if (INSTALL_TYPE_UPDATE != $installType) {
1415
                $dbNameForm = str_replace(['-', '*', '$', ' ', '.'], '', $dbNameForm);
1416
            }
1417
            displayDatabaseParameter(
1418
                $installType,
1419
                get_lang('Main Chamilo database (DB)'),
1420
                'dbNameForm',
1421
                $dbNameForm,
1422
                '&nbsp;',
1423
                null,
1424
                'id="optional_param1"'
1425
                );
1426
        echo '</div>';
1427
        if (INSTALL_TYPE_UPDATE != $installType) {                    ?>
1428
        <div class="form-group row">
1429
            <div class="col-sm-4"></div>
1430
            <div class="col-sm-8">
1431
            <button type="submit" class="btn btn-primary" name="step3" value="step3">
1432
                <em class="fa fa-refresh"> </em>
1433
                <?php echo get_lang('Check database connection'); ?>
1434
            </button>
1435
            </div>
1436
        </div>
1437
        <?php
1438
                } ?>
1439
1440
        </div>
1441
    </div>
1442
    <?php
1443
        $database_exists_text = '';
1444
    $manager = null;
1445
    try {
1446
        if ('update' === $installType) {
1447
            /** @var \Database $manager */
1448
            $manager = connectToDatabase(
1449
                $dbHostForm,
1450
                $dbUsernameForm,
1451
                $dbPassForm,
1452
                $dbNameForm,
1453
                $dbPortForm
1454
            );
1455
1456
            $connection = $manager->getConnection();
1457
            $connection->connect();
1458
            $schemaManager = $connection->getSchemaManager();
1459
1460
            // Test create/alter/drop table
1461
            $table = 'zXxTESTxX_'.mt_rand(0, 1000);
1462
            $sql = "CREATE TABLE $table (id INT AUTO_INCREMENT NOT NULL, name varchar(255), PRIMARY KEY(id))";
1463
            $connection->query($sql);
1464
            $tableCreationWorks = false;
1465
            $tableDropWorks = false;
1466
            if ($schemaManager->tablesExist($table)) {
1467
                $sql = "ALTER TABLE $table ADD COLUMN name2 varchar(140) ";
1468
                $connection->query($sql);
1469
                $schemaManager->dropTable($table);
1470
                $tableDropWorks = false === $schemaManager->tablesExist($table);
1471
            }
1472
        } else {
1473
            $manager = connectToDatabase(
1474
                $dbHostForm,
1475
                $dbUsernameForm,
1476
                $dbPassForm,
1477
                null,
1478
                $dbPortForm
1479
            );
1480
1481
            $schemaManager = $manager->getConnection()->getSchemaManager();
1482
            $databases = $schemaManager->listDatabases();
1483
            if (in_array($dbNameForm, $databases)) {
1484
                $database_exists_text = '<div class="alert alert-warning">'.
1485
                get_lang('A database with the same name <b>already exists</b>.').'</div>';
1486
            }
1487
        }
1488
    } catch (Exception $e) {
1489
        $database_exists_text = $e->getMessage();
1490
        $manager = false;
1491
    }
1492
1493
    if ($manager && $manager->getConnection()->isConnected()): ?>
1494
        <?php echo $database_exists_text; ?>
1495
        <div id="db_status" class="alert alert-success">
1496
            Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br/>
1497
            Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br/>
1498
            Database driver: <strong><?php echo $manager->getConnection()->getDriver()->getName(); ?></strong><br/>
1499
            <?php
1500
                if ('update' === $installType) {
1501
                    echo get_lang('CreateTableWorks').' <strong>Ok</strong>';
1502
                    echo '<br/ >';
1503
                    echo get_lang('AlterTableWorks').' <strong>Ok</strong>';
1504
                    echo '<br/ >';
1505
                    echo get_lang('DropColumnWorks').' <strong>Ok</strong>';
1506
                } ?>
1507
        </div>
1508
    <?php else: ?>
1509
        <div id="db_status" class="alert alert-danger">
1510
            <p><?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.'); ?></strong></p>
1511
            <code><?php echo $database_exists_text; ?></code>
1512
        </div>
1513
    <?php endif; ?>
1514
1515
   <div class="btn-group" role="group">
1516
       <button type="submit" name="step2"
1517
               class="btn btn-secondary float-right" value="&lt; <?php echo get_lang('Previous'); ?>" >
1518
           <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1519
       </button>
1520
       <input type="hidden" name="is_executable" id="is_executable" value="-" />
1521
       <?php if ($manager) {
1522
                    ?>
1523
           <button type="submit" class="btn btn-success" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1524
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1525
           </button>
1526
       <?php
1527
                } else {
1528
                    ?>
1529
           <button
1530
                   disabled="disabled"
1531
                   type="submit" class="btn btn-success disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1532
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1533
           </button>
1534
       <?php
1535
                } ?>
1536
   </div>
1537
    <?php
1538
}
1539
1540
function panel($content = null, $title = null, $id = null, $style = null)
1541
{
1542
    $html = '';
1543
    if (empty($style)) {
1544
        $style = 'default';
1545
    }
1546
    if (!empty($title)) {
1547
        $panelTitle = Display::div($title, ['class' => 'panel-heading']);
1548
        $panelBody = Display::div($content, ['class' => 'panel-body']);
1549
        $panelParent = Display::div($panelTitle.$panelBody, ['id' => $id, 'class' => 'panel panel-'.$style]);
1550
    } else {
1551
        $panelBody = Display::div($html, ['class' => 'panel-body']);
1552
        $panelParent = Display::div($panelBody, ['id' => $id, 'class' => 'panel panel-'.$style]);
1553
    }
1554
    $html .= $panelParent;
1555
1556
    return $html;
1557
}
1558
1559
/**
1560
 * Displays a parameter in a table row.
1561
 * Used by the display_configuration_settings_form function.
1562
 *
1563
 * @param string $installType
1564
 * @param string $parameterName
1565
 * @param string $formFieldName
1566
 * @param string $parameterValue
1567
 * @param string $displayWhenUpdate
1568
 *
1569
 * @return string
1570
 */
1571
function display_configuration_parameter(
1572
    $installType,
1573
    $parameterName,
1574
    $formFieldName,
1575
    $parameterValue,
1576
    $displayWhenUpdate = 'true'
1577
) {
1578
    $html = '<div class="form-group row">';
1579
    $html .= '<label class="col-sm-6 control-label">'.$parameterName.'</label>';
1580
    if (INSTALL_TYPE_UPDATE == $installType && $displayWhenUpdate) {
1581
        $html .= '<input type="hidden" name="'.$formFieldName.'" value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />'.$parameterValue;
1582
    } else {
1583
        $html .= '<div class="col-sm-6"><input class="form-control" type="text" size="'.FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.MAX_FORM_FIELD_LENGTH.'" name="'.$formFieldName.'" value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />'."</div>";
1584
    }
1585
    $html .= "</div>";
1586
1587
    return $html;
1588
}
1589
1590
/**
1591
 * Displays step 4 of the installation - configuration settings about Chamilo itself.
1592
 *
1593
 * @param string $installType
1594
 * @param string $urlForm
1595
 * @param string $languageForm
1596
 * @param string $emailForm
1597
 * @param string $adminFirstName
1598
 * @param string $adminLastName
1599
 * @param string $adminPhoneForm
1600
 * @param string $campusForm
1601
 * @param string $institutionForm
1602
 * @param string $institutionUrlForm
1603
 * @param string $encryptPassForm
1604
 * @param bool   $allowSelfReg
1605
 * @param bool   $allowSelfRegProf
1606
 * @param string $loginForm
1607
 * @param string $passForm
1608
 */
1609
function display_configuration_settings_form(
1610
    $installType,
1611
    $urlForm,
1612
    $languageForm,
1613
    $emailForm,
1614
    $adminFirstName,
1615
    $adminLastName,
1616
    $adminPhoneForm,
1617
    $campusForm,
1618
    $institutionForm,
1619
    $institutionUrlForm,
1620
    $encryptPassForm,
1621
    $allowSelfReg,
1622
    $allowSelfRegProf,
1623
    $loginForm,
1624
    $passForm
1625
) {
1626
    if ('update' !== $installType && empty($languageForm)) {
1627
        $languageForm = $_SESSION['install_language'];
1628
    }
1629
    echo '<div class="RequirementHeading">';
1630
    echo "<h2>".display_step_sequence().get_lang("ConfigurationSettings")."</h2>";
1631
    echo '</div>';
1632
1633
    // Parameter 1: administrator's login
1634
    $html = '';
1635
    $html .= display_configuration_parameter(
1636
        $installType,
1637
        get_lang('Administrator login'),
1638
        'loginForm',
1639
        $loginForm,
1640
        'update' == $installType
1641
    );
1642
1643
    // Parameter 2: administrator's password
1644
    if ('update' !== $installType) {
1645
        $html .= display_configuration_parameter(
1646
            $installType,
1647
            get_lang('Administrator password (<font color="red">you may want to change this</font>)'),
1648
            'passForm',
1649
            $passForm,
1650
            false
1651
        );
1652
    }
1653
1654
    // Parameters 3 and 4: administrator's names
1655
    $html .= display_configuration_parameter(
1656
        $installType,
1657
        get_lang('Administrator first name'),
1658
        'adminFirstName',
1659
        $adminFirstName
1660
    );
1661
    $html .= display_configuration_parameter($installType, get_lang('Administrator last name'), 'adminLastName', $adminLastName);
1662
1663
    // Parameter 3: administrator's email
1664
    $html .= display_configuration_parameter($installType, get_lang('Admin-mail'), 'emailForm', $emailForm);
1665
1666
    // Parameter 6: administrator's telephone
1667
    $html .= display_configuration_parameter($installType, get_lang('Administrator telephone'), 'adminPhoneForm', $adminPhoneForm);
1668
    echo panel($html, get_lang('Administrator'), 'administrator');
1669
1670
    //First parameter: language
1671
    $html = '<div class="form-group row">';
1672
    $html .= '<label class="col-sm-6 control-label">'.get_lang('Main language')."</label>";
1673
    if ('update' === $installType) {
1674
        $html .= '<input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES).'" />'.$languageForm;
1675
    } else {
1676
        $html .= '<div class="col-sm-6">';
1677
        $html .= display_language_selection_box('languageForm', $languageForm);
1678
        $html .= '</div>';
1679
    }
1680
    $html .= "</div>";
1681
1682
    // Second parameter: Chamilo URL
1683
    $html .= '<div class="form-group row">';
1684
    $html .= '<label class="col-sm-6 control-label">'.get_lang('Chamilo URL').get_lang('Required field').'</label>';
1685
1686
    if ('update' === $installType) {
1687
        $html .= api_htmlentities($urlForm, ENT_QUOTES)."\n";
1688
    } else {
1689
        $html .= '<div class="col-sm-6">';
1690
        $html .= '<input class="form-control" type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES).'" />';
1691
        $html .= '</div>';
1692
    }
1693
    $html .= '</div>';
1694
1695
    // Parameter 9: campus name
1696
    $html .= display_configuration_parameter(
1697
        $installType,
1698
        get_lang('Your portal name'),
1699
        'campusForm',
1700
        $campusForm
1701
    );
1702
1703
    // Parameter 10: institute (short) name
1704
    $html .= display_configuration_parameter(
1705
        $installType,
1706
        get_lang('Your company short name'),
1707
        'institutionForm',
1708
        $institutionForm
1709
    );
1710
1711
    // Parameter 11: institute (short) name
1712
    $html .= display_configuration_parameter(
1713
        $installType,
1714
        get_lang('URL of this company'),
1715
        'institutionUrlForm',
1716
        $institutionUrlForm
1717
    );
1718
1719
    $html .= '<div class="form-group row">
1720
            <label class="col-sm-6 control-label">'.get_lang("Encryption method").'</label>
1721
        <div class="col-sm-6">';
1722
    if ('update' === $installType) {
1723
        $html .= '<input type="hidden" name="encryptPassForm" value="'.$encryptPassForm.'" />'.$encryptPassForm;
1724
    } else {
1725
        $html .= '<div class="checkbox">
1726
                    <label>
1727
                        <input  type="radio" name="encryptPassForm" value="bcrypt" id="encryptPass1" '.('bcrypt' == $encryptPassForm ? 'checked="checked" ' : '').'/> bcrypt
1728
                    </label>';
1729
1730
        $html .= '<label>
1731
                        <input  type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" '.('sha1' == $encryptPassForm ? 'checked="checked" ' : '').'/> sha1
1732
                    </label>';
1733
1734
        $html .= '<label>
1735
                        <input type="radio" name="encryptPassForm" value="md5" id="encryptPass0" '.('md5' == $encryptPassForm ? 'checked="checked" ' : '').'/> md5
1736
                    </label>';
1737
1738
        $html .= '<label>
1739
                        <input type="radio" name="encryptPassForm" value="none" id="encryptPass2" '.('none' == $encryptPassForm ? 'checked="checked" ' : '').'/>'.get_lang('none').'
1740
                    </label>';
1741
        $html .= '</div>';
1742
    }
1743
    $html .= '</div></div>';
1744
1745
    $html .= '<div class="form-group row">
1746
            <label class="col-sm-6 control-label">'.get_lang('Allow self-registration').'</label>
1747
            <div class="col-sm-6">';
1748
    if ('update' === $installType) {
1749
        if ('true' == $allowSelfReg) {
1750
            $label = get_lang('Yes');
1751
        } elseif ('false' == $allowSelfReg) {
1752
            $label = get_lang('No');
1753
        } else {
1754
            $label = get_lang('After approval');
1755
        }
1756
        $html .= '<input type="hidden" name="allowSelfReg" value="'.$allowSelfReg.'" />'.$label;
1757
    } else {
1758
        $html .= '<div class="control-group">';
1759
        $html .= '<label class="checkbox-inline">
1760
                        <input type="radio" name="allowSelfReg" value="true" id="allowSelfReg1" '.('true' == $allowSelfReg ? 'checked="checked" ' : '').' /> '.get_lang('Yes').'
1761
                    </label>';
1762
        $html .= '<label class="checkbox-inline">
1763
                        <input type="radio" name="allowSelfReg" value="false" id="allowSelfReg0" '.('false' == $allowSelfReg ? '' : 'checked="checked" ').' /> '.get_lang('No').'
1764
                    </label>';
1765
        $html .= '<label class="checkbox-inline">
1766
                    <input type="radio" name="allowSelfReg" value="approval" id="allowSelfReg2" '.('approval' == $allowSelfReg ? '' : 'checked="checked" ').' /> '.get_lang('After approval').'
1767
                </label>';
1768
        $html .= '</div>';
1769
    }
1770
    $html .= '</div>';
1771
    $html .= '</div>';
1772
1773
    $html .= '<div class="form-group row">';
1774
    $html .= '<label class="col-sm-6 control-label">'.get_lang('Allow self-registrationProf').'</label>
1775
        <div class="col-sm-6">';
1776
    if ('update' === $installType) {
1777
        if ('true' === $allowSelfRegProf) {
1778
            $label = get_lang('Yes');
1779
        } else {
1780
            $label = get_lang('No');
1781
        }
1782
        $html .= '<input type="hidden" name="allowSelfRegProf" value="'.$allowSelfRegProf.'" />'.$label;
1783
    } else {
1784
        $html .= '<div class="control-group">
1785
                <label class="checkbox-inline">
1786
                    <input type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" '.($allowSelfRegProf ? 'checked="checked" ' : '').'/>
1787
                '.get_lang('Yes').'
1788
                </label>';
1789
        $html .= '<label class="checkbox-inline">
1790
                    <input type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" '.($allowSelfRegProf ? '' : 'checked="checked" ').' />
1791
                   '.get_lang('No').'
1792
                </label>';
1793
        $html .= '</div>';
1794
    }
1795
    $html .= '</div>
1796
    </div>';
1797
1798
    echo panel($html, get_lang('Portal'), 'platform'); ?>
1799
    <div class='btn-group'>
1800
        <button type="submit" class="btn btn-secondary pull-right" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" ><em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?></button>
1801
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
1802
        <button class="btn btn-success" type="submit" name="step5">
1803
            <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1804
        </button>
1805
    </div>
1806
    <?php
1807
}
1808
1809
/**
1810
 * After installation is completed (step 6), this message is displayed.
1811
 */
1812
function display_after_install_message()
1813
{
1814
    $container = Container::$container;
1815
    $trans = $container->get('translator');
1816
    $html = '<div class="RequirementContent">'.
1817
        $trans->trans(
1818
            '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>';
1819
    $html .= '<div class="alert alert-warning">';
1820
    $html .= '<strong>'.$trans->trans('Security advice').'</strong>';
1821
    $html .= ': ';
1822
    $html .= sprintf($trans->trans(
1823
        '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/');
1824
    $html .= '</div></form>
1825
    <br />
1826
    <a class="btn btn-success btn-block" href="../../">
1827
        '.$trans->trans('Go to your newly created portal.').'
1828
    </a>';
1829
1830
    return $html;
1831
}
1832
1833
/**
1834
 * This function return countries list from array (hardcoded).
1835
 *
1836
 * @param bool $combo (Optional) True for returning countries list with select html
1837
 *
1838
 * @return array|string countries list
1839
 */
1840
function get_countries_list_from_array($combo = false)
1841
{
1842
    $a_countries = [
1843
        "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
1844
        "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
1845
        "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",
1846
        "Denmark", "Djibouti", "Dominica", "Dominican Republic",
1847
        "East Timor (Timor Timur)", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
1848
        "Fiji", "Finland", "France",
1849
        "Gabon", "Gambia, The", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana",
1850
        "Haiti", "Honduras", "Hungary",
1851
        "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy",
1852
        "Jamaica", "Japan", "Jordan",
1853
        "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan",
1854
        "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
1855
        "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Morocco", "Mozambique", "Myanmar",
1856
        "Namibia", "Nauru", "Nepa", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway",
1857
        "Oman",
1858
        "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal",
1859
        "Qatar",
1860
        "Romania", "Russia", "Rwanda",
1861
        "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",
1862
        "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu",
1863
        "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan",
1864
        "Vanuatu", "Vatican City", "Venezuela", "Vietnam",
1865
        "Yemen",
1866
        "Zambia", "Zimbabwe",
1867
    ];
1868
    if ($combo) {
1869
        $country_select = '<select class="selectpicker show-tick" id="country" name="country">';
1870
        $country_select .= '<option value="">--- '.get_lang('Select one').' ---</option>';
1871
        foreach ($a_countries as $country) {
1872
            $country_select .= '<option value="'.$country.'">'.$country.'</option>';
1873
        }
1874
        $country_select .= '</select>';
1875
1876
        return $country_select;
1877
    }
1878
1879
    return $a_countries;
1880
}
1881
1882
/**
1883
 * Lock settings that can't be changed in other portals.
1884
 */
1885
function lockSettings()
1886
{
1887
    $settings = api_get_locked_settings();
1888
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1889
    foreach ($settings as $setting) {
1890
        $sql = "UPDATE $table SET access_url_locked = 1 WHERE variable  = '$setting'";
1891
        Database::query($sql);
1892
    }
1893
}
1894
1895
/**
1896
 * Update dir values.
1897
 */
1898
function updateDirAndFilesPermissions()
1899
{
1900
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1901
    $permissions_for_new_directories = isset($_SESSION['permissions_for_new_directories']) ? $_SESSION['permissions_for_new_directories'] : 0770;
1902
    $permissions_for_new_files = isset($_SESSION['permissions_for_new_files']) ? $_SESSION['permissions_for_new_files'] : 0660;
1903
    // use decoct() to store as string
1904
    Database::update(
1905
        $table,
1906
        ['selected_value' => '0'.decoct($permissions_for_new_directories)],
1907
        ['variable = ?' => 'permissions_for_new_directories']
1908
    );
1909
1910
    Database::update(
1911
        $table,
1912
        ['selected_value' => '0'.decoct($permissions_for_new_files)],
1913
        ['variable = ?' => 'permissions_for_new_files']
1914
    );
1915
1916
    if (isset($_SESSION['permissions_for_new_directories'])) {
1917
        unset($_SESSION['permissions_for_new_directories']);
1918
    }
1919
1920
    if (isset($_SESSION['permissions_for_new_files'])) {
1921
        unset($_SESSION['permissions_for_new_files']);
1922
    }
1923
}
1924
1925
/**
1926
 * @param $current_value
1927
 * @param $wanted_value
1928
 *
1929
 * @return string
1930
 */
1931
function compare_setting_values($current_value, $wanted_value)
1932
{
1933
    $current_value_string = $current_value;
1934
    $current_value = (float) $current_value;
1935
    $wanted_value = (float) $wanted_value;
1936
1937
    if ($current_value >= $wanted_value) {
1938
        return Display::label($current_value_string, 'success');
1939
    }
1940
1941
    return Display::label($current_value_string, 'important');
1942
}
1943
1944
/**
1945
 * Save settings values.
1946
 *
1947
 * @param string $organizationName
1948
 * @param string $organizationUrl
1949
 * @param string $siteName
1950
 * @param string $adminEmail
1951
 * @param string $adminLastName
1952
 * @param string $adminFirstName
1953
 * @param string $language
1954
 * @param string $allowRegistration
1955
 * @param string $allowTeacherSelfRegistration
1956
 * @param string $installationProfile          The name of an installation profile file in main/install/profiles/
1957
 */
1958
function installSettings(
1959
    $organizationName,
1960
    $organizationUrl,
1961
    $siteName,
1962
    $adminEmail,
1963
    $adminLastName,
1964
    $adminFirstName,
1965
    $language,
1966
    $allowRegistration,
1967
    $allowTeacherSelfRegistration,
1968
    $installationProfile = ''
1969
) {
1970
    error_log('installSettings');
1971
    $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false';
1972
1973
    $settings = [
1974
        'institution' => $organizationName,
1975
        'institution_url' => $organizationUrl,
1976
        'site_name' => $siteName,
1977
        'administrator_email' => $adminEmail,
1978
        'administrator_surname' => $adminLastName,
1979
        'administrator_name' => $adminFirstName,
1980
        'platform_language' => $language,
1981
        'allow_registration' => $allowRegistration,
1982
        'allow_registration_as_teacher' => $allowTeacherSelfRegistration,
1983
    ];
1984
1985
    foreach ($settings as $variable => $value) {
1986
        $sql = "UPDATE settings_current
1987
                SET selected_value = '$value'
1988
                WHERE variable = '$variable'";
1989
        Database::query($sql);
1990
    }
1991
    installProfileSettings($installationProfile);
1992
}
1993
1994
/**
1995
 * Executes DB changes based in the classes defined in
1996
 * src/CoreBundle/Migrations/Schema/*.
1997
 *
1998
 * @param string $chamiloVersion
1999
 *
2000
 * @throws \Doctrine\DBAL\DBALException
2001
 *
2002
 * @return bool
2003
 */
2004
function migrate($chamiloVersion, EntityManager $manager)
2005
{
2006
    $debug = true;
2007
    $connection = $manager->getConnection();
2008
    $config = new Doctrine\Migrations\Configuration\Configuration($connection);
2009
    // Table name that will store migrations log (will be created automatically,
2010
    // default name is: doctrine_migration_versions)
2011
    $config->setMigrationsTableName('version');
2012
    // Namespace of your migration classes, do not forget escape slashes, do not add last slash
2013
    $config->setMigrationsNamespace('Chamilo\CoreBundle\Migrations\Schema\V'.$chamiloVersion);
2014
    // Directory where your migrations are located
2015
    $versionPath = api_get_path(SYS_PATH).'src/CoreBundle/Migrations/Schema/V'.$chamiloVersion;
2016
    error_log("Reading files from dir: $versionPath");
2017
    $config->setMigrationsDirectory($versionPath);
2018
    // Load your migrations
2019
    $config->registerMigrationsFromDirectory($config->getMigrationsDirectory());
2020
    $versions = $config->getMigrations();
2021
2022
    foreach ($versions as $version) {
2023
        $version->getMigration()->setEntityManager($manager);
2024
    }
2025
2026
    $to = null; // if $to == null then schema will be migrated to latest version
2027
    echo '<pre>';
2028
    try {
2029
        $migration = new Doctrine\Migrations\Migrator($config);
2030
        // Execute migration!
2031
        $migratedSQL = $migration->migrate($to);
2032
2033
        if ($debug) {
2034
            foreach ($migratedSQL as $version => $sqlList) {
2035
                echo "VERSION: $version<br>";
2036
                echo '----------------------------------------------<br />';
2037
                $total = count($sqlList);
2038
                error_log("VERSION: $version");
2039
                error_log("# queries: $total");
2040
                $counter = 1;
2041
                foreach ($sqlList as $sql) {
2042
                    echo "<code>$sql</code><br>";
2043
                    error_log("$counter/$total : $sql");
2044
                    $counter++;
2045
                }
2046
            }
2047
2048
            echo "<br>DONE!<br>";
2049
        }
2050
2051
        return true;
2052
    } catch (Exception $ex) {
2053
        if ($debug) {
2054
            echo "ERROR: {$ex->getMessage()}<br>";
2055
2056
            return false;
2057
        }
2058
    }
2059
2060
    echo '</pre>';
2061
2062
    return false;
2063
}
2064
2065
/**
2066
 * @throws \Doctrine\DBAL\DBALException
2067
 */
2068
function fixIds(EntityManager $em)
2069
{
2070
    $connection = $em->getConnection();
2071
    $database = new Database();
2072
    $database->setManager($em);
2073
    $debug = true;
2074
    if ($debug) {
2075
        error_log('fixIds');
2076
    }
2077
2078
    // Create temporary indexes to increase speed of the following operations
2079
    // Adding and removing indexes will usually take much less time than
2080
    // the execution without indexes of the queries in this function, particularly
2081
    // for large tables
2082
    $sql = "ALTER TABLE c_document ADD INDEX tmpidx_doc(c_id, id)";
2083
    $connection->executeQuery($sql);
2084
    $sql = "ALTER TABLE c_student_publication ADD INDEX tmpidx_stud (c_id, id)";
2085
    $connection->executeQuery($sql);
2086
    $sql = "ALTER TABLE c_quiz ADD INDEX tmpidx_quiz (c_id, id)";
2087
    $connection->executeQuery($sql);
2088
    $sql = "ALTER TABLE c_item_property ADD INDEX tmpidx_ip (to_group_id)";
2089
    $connection->executeQuery($sql);
2090
2091
    $sql = "SELECT * FROM c_lp_item";
2092
    $result = $connection->fetchAll($sql);
2093
    foreach ($result as $item) {
2094
        $courseId = $item['c_id'];
2095
        $iid = isset($item['iid']) ? intval($item['iid']) : 0;
2096
        $ref = isset($item['ref']) ? intval($item['ref']) : 0;
2097
        $sql = null;
2098
2099
        $newId = '';
2100
2101
        switch ($item['item_type']) {
2102
            case TOOL_LINK:
2103
                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref";
2104
                $data = $connection->fetchAssoc($sql);
2105
                if ($data) {
2106
                    $newId = $data['iid'];
2107
                }
2108
                break;
2109
            case TOOL_STUDENTPUBLICATION:
2110
                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2111
                $data = $connection->fetchAssoc($sql);
2112
                if ($data) {
2113
                    $newId = $data['iid'];
2114
                }
2115
                break;
2116
            case TOOL_QUIZ:
2117
                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2118
                $data = $connection->fetchAssoc($sql);
2119
                if ($data) {
2120
                    $newId = $data['iid'];
2121
                }
2122
                break;
2123
            case TOOL_DOCUMENT:
2124
                $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2125
                $data = $connection->fetchAssoc($sql);
2126
                if ($data) {
2127
                    $newId = $data['iid'];
2128
                }
2129
                break;
2130
            case TOOL_FORUM:
2131
                $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND forum_id = $ref";
2132
                $data = $connection->fetchAssoc($sql);
2133
                if ($data) {
2134
                    $newId = $data['iid'];
2135
                }
2136
                break;
2137
            case 'thread':
2138
                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
2139
                $data = $connection->fetchAssoc($sql);
2140
                if ($data) {
2141
                    $newId = $data['iid'];
2142
                }
2143
                break;
2144
        }
2145
2146
        if (!empty($sql) && !empty($newId) && !empty($iid)) {
2147
            $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid";
2148
            $connection->executeQuery($sql);
2149
        }
2150
    }
2151
2152
    // Set NULL if session = 0
2153
    $sql = "UPDATE c_item_property SET session_id = NULL WHERE session_id = 0";
2154
    $connection->executeQuery($sql);
2155
2156
    // Set NULL if group = 0
2157
    $sql = "UPDATE c_item_property SET to_group_id = NULL WHERE to_group_id = 0";
2158
    $connection->executeQuery($sql);
2159
2160
    // Set NULL if insert_user_id = 0
2161
    $sql = "UPDATE c_item_property SET insert_user_id = NULL WHERE insert_user_id = 0";
2162
    $connection->executeQuery($sql);
2163
2164
    // Delete session data of sessions that don't exist.
2165
    $sql = "DELETE FROM c_item_property
2166
            WHERE session_id IS NOT NULL AND session_id NOT IN (SELECT id FROM session)";
2167
    $connection->executeQuery($sql);
2168
2169
    // Delete group data of groups that don't exist.
2170
    $sql = "DELETE FROM c_item_property
2171
            WHERE to_group_id <> 0 AND to_group_id IS NOT NULL AND to_group_id NOT IN (SELECT DISTINCT iid FROM c_group_info)";
2172
    $connection->executeQuery($sql);
2173
    // This updates the group_id with c_group_info.iid instead of c_group_info.id
2174
2175
    if ($debug) {
2176
        error_log('update iids');
2177
    }
2178
2179
    $groupTableToFix = [
2180
        'c_group_rel_user',
2181
        'c_group_rel_tutor',
2182
        'c_permission_group',
2183
        'c_role_group',
2184
        'c_survey_invitation',
2185
        'c_attendance_calendar_rel_group',
2186
    ];
2187
2188
    foreach ($groupTableToFix as $table) {
2189
        $sql = "SELECT * FROM $table";
2190
        $result = $connection->fetchAll($sql);
2191
        foreach ($result as $item) {
2192
            $iid = $item['iid'];
2193
            $courseId = $item['c_id'];
2194
            $groupId = intval($item['group_id']);
2195
2196
            // Fix group id
2197
            if (!empty($groupId)) {
2198
                $sql = "SELECT * FROM c_group_info
2199
                        WHERE c_id = $courseId AND id = $groupId
2200
                        LIMIT 1";
2201
                $data = $connection->fetchAssoc($sql);
2202
                if (!empty($data)) {
2203
                    $newGroupId = $data['iid'];
2204
                    $sql = "UPDATE $table SET group_id = $newGroupId
2205
                            WHERE iid = $iid";
2206
                    $connection->executeQuery($sql);
2207
                } else {
2208
                    // The group does not exists clean this record
2209
                    $sql = "DELETE FROM $table WHERE iid = $iid";
2210
                    $connection->executeQuery($sql);
2211
                }
2212
            }
2213
        }
2214
    }
2215
2216
    // Fix c_item_property
2217
    if ($debug) {
2218
        error_log('update c_item_property');
2219
    }
2220
2221
    $sql = "SELECT * FROM course";
2222
    $courseList = $connection->fetchAll($sql);
2223
    if ($debug) {
2224
        error_log('Getting course list');
2225
    }
2226
2227
    $totalCourse = count($courseList);
2228
    $counter = 0;
2229
2230
    foreach ($courseList as $courseData) {
2231
        $courseId = $courseData['id'];
2232
        if ($debug) {
2233
            error_log('Updating course: '.$courseData['code']);
2234
        }
2235
2236
        $sql = "SELECT * FROM c_item_property WHERE c_id = $courseId";
2237
        $result = $connection->fetchAll($sql);
2238
        foreach ($result as $item) {
2239
            $sessionId = intval($item['session_id']);
2240
            $groupId = intval($item['to_group_id']);
2241
            $iid = $item['iid'];
2242
            $ref = $item['ref'];
2243
2244
            // Fix group id
2245
            // Commented group id is already fixed in Version20150603181728.php
2246
            /*if (!empty($groupId)) {
2247
                $sql = "SELECT * FROM c_group_info
2248
                        WHERE c_id = $courseId AND id = $groupId";
2249
                $data = $connection->fetchAssoc($sql);
2250
                if (!empty($data)) {
2251
                    $newGroupId = $data['iid'];
2252
                    $sql = "UPDATE c_item_property SET to_group_id = $newGroupId
2253
                            WHERE iid = $iid";
2254
                    $connection->executeQuery($sql);
2255
                } else {
2256
                    // The group does not exists clean this record
2257
                    $sql = "DELETE FROM c_item_property WHERE iid = $iid";
2258
                    $connection->executeQuery($sql);
2259
                }
2260
            }*/
2261
2262
            $sql = '';
2263
            $newId = '';
2264
            switch ($item['tool']) {
2265
                case TOOL_LINK:
2266
                    $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
2267
                    break;
2268
                case TOOL_STUDENTPUBLICATION:
2269
                    $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2270
                    break;
2271
                case TOOL_QUIZ:
2272
                    $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2273
                    break;
2274
                case TOOL_DOCUMENT:
2275
                    $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2276
                    break;
2277
                case TOOL_FORUM:
2278
                    $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND id = $ref";
2279
                    break;
2280
                case 'thread':
2281
                    $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND id = $ref";
2282
                    break;
2283
            }
2284
2285
            if (!empty($sql) && !empty($newId)) {
2286
                $data = $connection->fetchAssoc($sql);
2287
                if (isset($data['iid'])) {
2288
                    $newId = $data['iid'];
2289
                }
2290
                $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid";
2291
                error_log($sql);
2292
                $connection->executeQuery($sql);
2293
            }
2294
        }
2295
2296
        if ($debug) {
2297
            // Print a status in the log once in a while
2298
            error_log("Course process #$counter/$totalCourse");
2299
        }
2300
        $counter++;
2301
    }
2302
2303
    if ($debug) {
2304
        error_log('update gradebook_link');
2305
    }
2306
2307
    // Fix gradebook_link
2308
    $sql = "SELECT * FROM gradebook_link";
2309
    $result = $connection->fetchAll($sql);
2310
    foreach ($result as $item) {
2311
        $courseCode = $item['course_code'];
2312
        $categoryId = (int) $item['category_id'];
2313
2314
        $sql = "SELECT * FROM course WHERE code = '$courseCode'";
2315
        $courseInfo = $connection->fetchAssoc($sql);
2316
        if (empty($courseInfo)) {
2317
            continue;
2318
        }
2319
2320
        $courseId = $courseInfo['id'];
2321
2322
        $ref = $item['ref_id'];
2323
        $iid = $item['id'];
2324
2325
        $sql = '';
2326
        switch ($item['type']) {
2327
            case LINK_LEARNPATH:
2328
                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
2329
                break;
2330
            case LINK_STUDENTPUBLICATION:
2331
                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2332
                break;
2333
            case LINK_EXERCISE:
2334
                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2335
                break;
2336
            case LINK_ATTENDANCE:
2337
                //$sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2338
                break;
2339
            case LINK_FORUM_THREAD:
2340
                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
2341
                break;
2342
        }
2343
2344
        if (!empty($sql)) {
2345
            $data = $connection->fetchAssoc($sql);
2346
            if (isset($data) && isset($data['iid'])) {
2347
                $newId = $data['iid'];
2348
                $sql = "UPDATE gradebook_link SET ref_id = $newId
2349
                        WHERE id = $iid AND course_code = '$courseCode' AND category_id = $categoryId ";
2350
                $connection->executeQuery($sql);
2351
            }
2352
        }
2353
    }
2354
2355
    if ($debug) {
2356
        error_log('update groups');
2357
    }
2358
2359
    $sql = 'SELECT * FROM groups';
2360
    $result = $connection->executeQuery($sql);
2361
    $groups = $result->fetchAll();
2362
    $oldGroups = [];
2363
    if (!empty($groups)) {
2364
        foreach ($groups as $group) {
2365
            if (empty($group['name'])) {
2366
                continue;
2367
            }
2368
2369
            $params = [
2370
                'name' => $group['name'],
2371
                'description' => $group['description'],
2372
                'group_type' => 1,
2373
                'picture' => $group['picture_uri'],
2374
                'url' => $group['url'],
2375
                'visibility' => $group['visibility'],
2376
                'updated_at' => $group['updated_on'],
2377
                'created_at' => $group['created_on'],
2378
            ];
2379
            $connection->insert('usergroup', $params);
2380
            $id = $connection->lastInsertId('id');
2381
            $oldGroups[$group['id']] = $id;
2382
        }
2383
    }
2384
2385
    if (!empty($oldGroups)) {
2386
        error_log('Moving group files');
2387
        foreach ($oldGroups as $oldId => $newId) {
2388
            $path = get_group_picture_path_by_id(
2389
                $oldId,
2390
                'system'
2391
            );
2392
2393
            if (!empty($path)) {
2394
                $newPath = str_replace(
2395
                    "groups/$oldId/",
2396
                    "groups/$newId/",
2397
                    $path['dir']
2398
                );
2399
                $command = "mv {$path['dir']} $newPath ";
2400
                error_log("Executing $command");
2401
                system($command);
2402
            }
2403
        }
2404
2405
        $sql = "SELECT * FROM group_rel_user";
2406
        $result = $connection->executeQuery($sql);
2407
        $dataList = $result->fetchAll();
2408
2409
        if (!empty($dataList)) {
2410
            foreach ($dataList as $data) {
2411
                if (isset($oldGroups[$data['group_id']])) {
2412
                    $data['group_id'] = $oldGroups[$data['group_id']];
2413
                    $userId = $data['user_id'];
2414
2415
                    $sql = "SELECT id FROM user WHERE user_id = $userId";
2416
                    $userResult = $connection->executeQuery($sql);
2417
                    $userInfo = $userResult->fetch();
2418
                    if (empty($userInfo)) {
2419
                        continue;
2420
                    }
2421
2422
                    $sql = "INSERT INTO usergroup_rel_user (usergroup_id, user_id, relation_type)
2423
                            VALUES ('{$data['group_id']}', '{$userId}', '{$data['relation_type']}')";
2424
                    $connection->executeQuery($sql);
2425
                }
2426
            }
2427
        }
2428
2429
        $sql = "SELECT * FROM group_rel_group";
2430
        $result = $connection->executeQuery($sql);
2431
        $dataList = $result->fetchAll();
2432
2433
        if (!empty($dataList)) {
2434
            foreach ($dataList as $data) {
2435
                if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
2436
                    $data['group_id'] = $oldGroups[$data['group_id']];
2437
                    $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
2438
                    $sql = "INSERT INTO usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
2439
                            VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
2440
                    $connection->executeQuery($sql);
2441
                }
2442
            }
2443
        }
2444
2445
        $sql = "SELECT * FROM announcement_rel_group";
2446
        $result = $connection->executeQuery($sql);
2447
        $dataList = $result->fetchAll();
2448
2449
        if (!empty($dataList)) {
2450
            foreach ($dataList as $data) {
2451
                if (isset($oldGroups[$data['group_id']])) {
2452
                    // Deleting relation
2453
                    $sql = "DELETE FROM announcement_rel_group WHERE group_id = {$data['group_id']}";
2454
                    $connection->executeQuery($sql);
2455
2456
                    // Add new relation
2457
                    $data['group_id'] = $oldGroups[$data['group_id']];
2458
                    $sql = "INSERT INTO announcement_rel_group(group_id, announcement_id)
2459
                            VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
2460
                    $connection->executeQuery($sql);
2461
                }
2462
            }
2463
        }
2464
2465
        $sql = "SELECT * FROM group_rel_tag";
2466
        $result = $connection->executeQuery($sql);
2467
        $dataList = $result->fetchAll();
2468
        if (!empty($dataList)) {
2469
            foreach ($dataList as $data) {
2470
                if (isset($oldGroups[$data['group_id']])) {
2471
                    $data['group_id'] = $oldGroups[$data['group_id']];
2472
                    $sql = "INSERT INTO usergroup_rel_tag (tag_id, usergroup_id)
2473
                            VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
2474
                    $connection->executeQuery($sql);
2475
                }
2476
            }
2477
        }
2478
    }
2479
2480
    if ($debug) {
2481
        error_log('update extra fields');
2482
    }
2483
2484
    // Extra fields
2485
    $extraFieldTables = [
2486
        ExtraField::USER_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_USER_FIELD),
2487
        ExtraField::COURSE_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
2488
        //ExtraField::LP_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_LP_FIELD),
2489
        ExtraField::SESSION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
2490
        //ExtraField::CALENDAR_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
2491
        //ExtraField::QUESTION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
2492
        //ExtraField::USER_FIELD_TYPE => //Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD),
2493
    ];
2494
2495
    foreach ($extraFieldTables as $type => $table) {
2496
        $sql = "SELECT * FROM $table ";
2497
        if ($debug) {
2498
            error_log($sql);
2499
        }
2500
        $result = $connection->query($sql);
2501
        $fields = $result->fetchAll();
2502
2503
        foreach ($fields as $field) {
2504
            if ($debug) {
2505
                error_log("Loading field: ".$field['field_variable']);
2506
            }
2507
            $originalId = $field['id'];
2508
2509
            $params = [
2510
                'extra_field_type' => $type,
2511
                'variable' => $field['field_variable'],
2512
                'field_type' => $field['field_type'],
2513
                'display_text' => $field['field_display_text'],
2514
                'default_value' => $field['field_default_value'],
2515
                'field_order' => $field['field_order'],
2516
                'visible' => $field['field_visible'],
2517
                'changeable' => $field['field_changeable'],
2518
                'filter' => $field['field_filter'],
2519
            ];
2520
2521
            $connection->insert('extra_field', $params);
2522
            $newExtraFieldId = $connection->lastInsertId();
2523
2524
            $values = [];
2525
            $handlerId = null;
2526
            switch ($type) {
2527
                case ExtraField::USER_FIELD_TYPE:
2528
                    $optionTable = Database::get_main_table(
2529
                        TABLE_MAIN_USER_FIELD_OPTIONS
2530
                    );
2531
                    $valueTable = Database::get_main_table(
2532
                        TABLE_MAIN_USER_FIELD_VALUES
2533
                    );
2534
                    $handlerId = 'user_id';
2535
                    break;
2536
                case ExtraField::COURSE_FIELD_TYPE:
2537
                    $optionTable = Database::get_main_table(
2538
                        TABLE_MAIN_COURSE_FIELD_OPTIONS
2539
                    );
2540
                    $valueTable = Database::get_main_table(
2541
                        TABLE_MAIN_COURSE_FIELD_VALUES
2542
                    );
2543
                    $handlerId = 'c_id';
2544
                    break;
2545
                case ExtraField::SESSION_FIELD_TYPE:
2546
                    $optionTable = Database::get_main_table(
2547
                        TABLE_MAIN_SESSION_FIELD_OPTIONS
2548
                    );
2549
                    $valueTable = Database::get_main_table(
2550
                        TABLE_MAIN_SESSION_FIELD_VALUES
2551
                    );
2552
                    $handlerId = 'session_id';
2553
                    break;
2554
            }
2555
2556
            if (!empty($optionTable)) {
2557
                $sql = "SELECT * FROM $optionTable WHERE field_id = $originalId ";
2558
                $result = $connection->query($sql);
2559
                $options = $result->fetchAll();
2560
2561
                foreach ($options as $option) {
2562
                    $params = [
2563
                        'display_text' => $option['option_display_text'],
2564
                        'field_id' => $newExtraFieldId,
2565
                        'option_order' => $option['option_order'],
2566
                        'option_value' => $option['option_value'],
2567
                    ];
2568
                    $connection->insert('extra_field_options', $params);
2569
                }
2570
2571
                $sql = "SELECT * FROM $valueTable WHERE field_id = $originalId ";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $valueTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
2572
                $result = $connection->query($sql);
2573
                $values = $result->fetchAll();
2574
                if ($debug) {
2575
                    error_log("Fetch all values for field");
2576
                }
2577
            }
2578
2579
            if (!empty($values)) {
2580
                if ($debug) {
2581
                    error_log("Saving field value in new table");
2582
                }
2583
                $k = 0;
2584
                foreach ($values as $value) {
2585
                    if (isset($value[$handlerId])) {
2586
                        // Insert without the use of the entity as it reduces
2587
                        // speed to 2 records per second (much too slow)
2588
                        $params = [
2589
                            'field_id' => $newExtraFieldId,
2590
                            'value' => $value['field_value'],
2591
                            'item_id' => $value[$handlerId],
2592
                        ];
2593
                        $connection->insert('extra_field_values', $params);
2594
                        if ($debug && (0 == $k % 10000)) {
2595
                            error_log("Saving field $k");
2596
                        }
2597
                        $k++;
2598
                    }
2599
                }
2600
            }
2601
        }
2602
    }
2603
2604
    if ($debug) {
0 ignored issues
show
introduced by
$debug is of type mixed, thus it always evaluated to true.
Loading history...
2605
        error_log('Remove index');
2606
    }
2607
2608
    // Drop temporary indexes added to increase speed of this function's queries
2609
    $sql = "ALTER TABLE c_document DROP INDEX tmpidx_doc";
2610
    $connection->executeQuery($sql);
2611
    $sql = "ALTER TABLE c_student_publication DROP INDEX tmpidx_stud";
2612
    $connection->executeQuery($sql);
2613
    $sql = "ALTER TABLE c_quiz DROP INDEX tmpidx_quiz";
2614
    $connection->executeQuery($sql);
2615
    $sql = "ALTER TABLE c_item_property DROP INDEX tmpidx_ip";
2616
    $connection->executeQuery($sql);
2617
2618
    if ($debug) {
2619
        error_log('Finish fixId function');
2620
    }
2621
2622
    fixLpId($connection, true);
2623
}
2624
2625
/**
2626
 * @param \Doctrine\DBAL\Connection $connection
2627
 * @param $debug
2628
 *
2629
 * @throws \Doctrine\DBAL\DBALException
2630
 */
2631
function fixLpId($connection, $debug)
2632
{
2633
    if ($debug) {
2634
        error_log('Fix lp.id lp.iids');
2635
    }
2636
2637
    $sql = 'SELECT id, title, code FROM course';
2638
    $result = $connection->query($sql);
2639
    $courses = $result->fetchAll();
2640
2641
    $sql = 'SELECT id FROM session';
2642
    $result = $connection->query($sql);
2643
    $sessions = $result->fetchAll();
2644
2645
    $tblCLp = Database::get_course_table(TABLE_LP_MAIN);
2646
    $tblCLpItem = Database::get_course_table(TABLE_LP_ITEM);
2647
    $toolTable = Database::get_course_table(TABLE_TOOL_LIST);
2648
2649
    if (!empty($sessions)) {
2650
        $sessions = array_column($sessions, 'id');
2651
        $sessions[] = 0;
2652
    } else {
2653
        $sessions = [0];
2654
    }
2655
2656
    foreach ($courses as $course) {
2657
        $courseId = $course['id'];
2658
        $sql = "SELECT * FROM $tblCLp WHERE c_id = $courseId AND iid <> id ORDER by iid";
2659
        $result = $connection->query($sql);
2660
        if ($debug) {
2661
            error_log('-------------');
2662
            error_log("Entering Lps in course #$courseId");
2663
            error_log($sql);
2664
        }
2665
        $lpList = $result->fetchAll();
2666
        $myOnlyLpList = [];
2667
        if (!empty($lpList)) {
2668
            foreach ($lpList as $lpInfo) {
2669
                $oldId = $lpInfo['id'];
2670
                $sql = "SELECT * FROM $tblCLpItem WHERE c_id = $courseId AND lp_id = $oldId ORDER by iid";
2671
                $result = $connection->query($sql);
2672
                $items = $result->fetchAll();
2673
                $lpInfo['lp_list'] = $items;
2674
                $myOnlyLpList[] = $lpInfo;
2675
            }
2676
        }
2677
2678
        if (!empty($myOnlyLpList)) {
2679
            foreach ($myOnlyLpList as $lpInfo) {
2680
                $lpIid = $lpInfo['iid'];
2681
                $oldId = $lpInfo['id'];
2682
                $items = $lpInfo['lp_list'];
2683
2684
                if (empty($items)) {
2685
                    continue;
2686
                }
2687
                $itemList = [];
2688
                foreach ($items as $subItem) {
2689
                    $itemList[$subItem['id']] = $subItem['iid'];
2690
                }
2691
                $variablesToFix = [
2692
                    'parent_item_id',
2693
                    'next_item_id',
2694
                    'prerequisite',
2695
                    'previous_item_id',
2696
                ];
2697
2698
                foreach ($sessions as $sessionId) {
2699
                    $correctLink = "lp/lp_controller.php?action=view&lp_id=$lpIid&id_session=$sessionId";
2700
                    $link = "newscorm/lp_controller.php?action=view&lp_id=$oldId&id_session=$sessionId";
2701
                    $secondLink = "lp/lp_controller.php?action=view&lp_id=$oldId&id_session=$sessionId";
2702
                    $sql = "UPDATE $toolTable
2703
                        SET link = '$correctLink'
2704
                        WHERE c_id = $courseId AND (link = '$link' OR link ='$secondLink')";
2705
                    $connection->query($sql);
2706
                }
2707
2708
                foreach ($items as $item) {
2709
                    $itemIid = $item['iid'];
2710
                    $itemId = $item['id'];
2711
                    foreach ($variablesToFix as $variable) {
2712
                        if (!empty($item[$variable]) && isset($itemList[$item[$variable]])) {
2713
                            $newId = $itemList[$item[$variable]];
2714
                            $sql = "UPDATE $tblCLpItem SET $variable = $newId
2715
                                    WHERE iid = $itemIid AND c_id = $courseId AND lp_id = $oldId";
2716
                            $connection->query($sql);
2717
                        }
2718
                    }
2719
2720
                    if ('document' == $item['item_type'] && !empty($item['path'])) {
2721
                        $oldDocumentId = $item['path'];
2722
                        $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $oldDocumentId";
2723
                        $result = $connection->query($sql);
2724
                        $document = $result->fetch();
2725
                        if (!empty($document)) {
2726
                            $newDocumentId = $document['iid'];
2727
                            if (!empty($newDocumentId)) {
2728
                                $sql = "UPDATE $tblCLpItem SET path = $newDocumentId
2729
                                    WHERE iid = $itemIid AND c_id = $courseId";
2730
                                $connection->query($sql);
2731
                                if ($debug) {
2732
                                    //error_log("Fix document: ");
2733
                                    //error_log($sql);
2734
                                }
2735
                            }
2736
                        }
2737
                    }
2738
2739
                    // c_lp_view
2740
                    $sql = "UPDATE c_lp_view SET last_item = $itemIid
2741
                            WHERE c_id = $courseId AND last_item = $itemId AND lp_id = $oldId";
2742
                    $connection->query($sql);
2743
2744
                    // c_lp_item_view
2745
                    $sql = "UPDATE c_lp_item_view SET lp_item_id = $itemIid
2746
                            WHERE c_id = $courseId AND lp_item_id = $itemId";
2747
                    $connection->query($sql);
2748
2749
                    // Update track_exercises
2750
                    $sql = "UPDATE track_e_exercises SET orig_lp_item_id = $itemIid
2751
                            WHERE c_id = $courseId AND orig_lp_id = $oldId AND orig_lp_item_id = $itemId";
2752
                    $connection->query($sql);
2753
2754
                    // c_forum_thread
2755
                    $sql = "UPDATE c_forum_thread SET lp_item_id = $itemIid
2756
                            WHERE c_id = $courseId AND lp_item_id = $itemId";
2757
                    $connection->query($sql);
2758
2759
                    // orig_lp_item_view_id
2760
                    $sql = "SELECT * FROM c_lp_view
2761
                            WHERE c_id = $courseId AND lp_id = $oldId";
2762
                    $result = $connection->query($sql);
2763
                    $itemViewList = $result->fetchAll();
2764
                    if ($itemViewList) {
2765
                        foreach ($itemViewList as $itemView) {
2766
                            $userId = $itemView['user_id'];
2767
                            $oldItemViewId = $itemView['id'];
2768
                            $newItemView = $itemView['iid'];
2769
2770
                            if (empty($oldItemViewId)) {
2771
                                continue;
2772
                            }
2773
2774
                            $sql = "UPDATE track_e_exercises
2775
                                SET orig_lp_item_view_id = $newItemView
2776
                                WHERE
2777
                                  c_id = $courseId AND
2778
                                  orig_lp_id = $oldId AND
2779
                                  orig_lp_item_id = $itemIid AND
2780
                                  orig_lp_item_view_id = $oldItemViewId AND
2781
                                  exe_user_id = $userId
2782
                                  ";
2783
                            $connection->query($sql);
2784
2785
                            /*$sql = "UPDATE c_lp_item_view
2786
                                    SET lp_view_id = $newItemView
2787
                                    WHERE
2788
                                      lp_view_id = $oldItemViewId AND
2789
                                      c_id = $courseId
2790
                                  ";
2791
                            $connection->query($sql);*/
2792
                        }
2793
                    }
2794
2795
                    $sql = "UPDATE $tblCLpItem SET lp_id = $lpIid
2796
                            WHERE c_id = $courseId AND lp_id = $oldId AND id = $itemId";
2797
                    $connection->query($sql);
2798
2799
                    $sql = "UPDATE $tblCLpItem SET id = iid
2800
                            WHERE c_id = $courseId AND lp_id = $oldId AND id = $itemId";
2801
                    $connection->query($sql);
2802
                }
2803
2804
                $sql = "UPDATE c_lp_view SET lp_id = $lpIid WHERE c_id = $courseId AND lp_id = $oldId";
2805
                $connection->query($sql);
2806
2807
                $sql = "UPDATE c_forum_forum SET lp_id = $lpIid WHERE c_id = $courseId AND lp_id = $oldId";
2808
                $connection->query($sql);
2809
2810
                // Update track_exercises.
2811
                $sql = "UPDATE track_e_exercises SET orig_lp_id = $lpIid
2812
                        WHERE c_id = $courseId AND orig_lp_id = $oldId";
2813
                $connection->query($sql);
2814
2815
                $sql = "UPDATE $tblCLp SET id = iid WHERE c_id = $courseId AND id = $oldId ";
2816
                $connection->query($sql);
2817
            }
2818
        }
2819
    }
2820
2821
    if ($debug) {
2822
        error_log('END Fix lp.id lp.iids');
2823
    }
2824
}
2825
2826
/**
2827
 * @param string $distFile
2828
 * @param string $envFile
2829
 * @param array  $params
2830
 */
2831
function updateEnvFile($distFile, $envFile, $params)
2832
{
2833
    $requirements = [
2834
        'DATABASE_HOST',
2835
        'DATABASE_PORT',
2836
        'DATABASE_NAME',
2837
        'DATABASE_USER',
2838
        'DATABASE_PASSWORD',
2839
        'APP_INSTALLED',
2840
        'APP_ENCRYPT_METHOD',
2841
    ];
2842
2843
    foreach ($requirements as $requirement) {
2844
        if (!isset($params['{{'.$requirement.'}}'])) {
2845
            throw new \Exception("The parameter $requirement is needed in order to edit the .env.local file");
2846
        }
2847
    }
2848
2849
    $contents = file_get_contents($distFile);
2850
    $contents = str_replace(array_keys($params), array_values($params), $contents);
2851
    file_put_contents($envFile, $contents);
2852
    error_log("File env saved here: $envFile");
2853
}
2854
2855
/**
2856
 * @param SymfonyContainer $container
2857
 * @param EntityManager    $manager
2858
 */
2859
function installGroups($container, $manager)
2860
{
2861
    // Creating fos_group (groups and roles)
2862
    $groups = [
2863
        [
2864
            'code' => 'ADMIN',
2865
            'title' => 'Administrators',
2866
            'roles' => ['ROLE_ADMIN'],
2867
        ],
2868
        [
2869
            'code' => 'STUDENT',
2870
            'title' => 'Students',
2871
            'roles' => ['ROLE_STUDENT'],
2872
        ],
2873
        [
2874
            'code' => 'TEACHER',
2875
            'title' => 'Teachers',
2876
            'roles' => ['ROLE_TEACHER'],
2877
        ],
2878
        [
2879
            'code' => 'RRHH',
2880
            'title' => 'Human resources manager',
2881
            'roles' => ['ROLE_RRHH'],
2882
        ],
2883
        [
2884
            'code' => 'SESSION_MANAGER',
2885
            'title' => 'Session',
2886
            'roles' => ['ROLE_SESSION_MANAGER'],
2887
        ],
2888
        [
2889
            'code' => 'QUESTION_MANAGER',
2890
            'title' => 'Question manager',
2891
            'roles' => ['ROLE_QUESTION_MANAGER'],
2892
        ],
2893
        [
2894
            'code' => 'STUDENT_BOSS',
2895
            'title' => 'Student boss',
2896
            'roles' => ['ROLE_STUDENT_BOSS'],
2897
        ],
2898
        [
2899
            'code' => 'INVITEE',
2900
            'title' => 'Invitee',
2901
            'roles' => ['ROLE_INVITEE'],
2902
        ],
2903
    ];
2904
    $repo = $manager->getRepository('ChamiloCoreBundle:Group');
2905
    foreach ($groups as $groupData) {
2906
        $criteria = ['code' => $groupData['code']];
2907
        $groupExists = $repo->findOneBy($criteria);
2908
        if (!$groupExists) {
2909
            $group = new Group($groupData['title']);
2910
            $group
2911
                ->setCode($groupData['code']);
2912
2913
            foreach ($groupData['roles'] as $role) {
2914
                $group->addRole($role);
2915
            }
2916
            $manager->persist($group);
2917
        }
2918
    }
2919
    $manager->flush();
2920
}
2921
2922
function installTools($container, $manager, $upgrade = false)
2923
{
2924
    error_log('installTools');
2925
    // Install course tools (table "tool")
2926
    $toolChain = $container->get(ToolChain::class);
2927
    $toolChain->createTools($manager);
2928
}
2929
2930
/**
2931
 * @param SymfonyContainer $container
2932
 * @param EntityManager    $manager
2933
 * @param bool             $upgrade
2934
 */
2935
function installSchemas($container, $manager, $upgrade = false)
2936
{
2937
    error_log('installSchemas');
2938
    $settingsManager = $container->get('chamilo.settings.manager');
2939
2940
    $urlRepo = $container->get('Chamilo\CoreBundle\Repository\AccessUrlRepository');
2941
    $accessUrl = $urlRepo->find(1);
2942
    if (!$accessUrl) {
2943
        $em = $urlRepo->getEntityManager();
2944
2945
        // Creating AccessUrl
2946
        $accessUrl = new AccessUrl();
2947
        $accessUrl
2948
            ->setUrl('http://localhost/')
2949
            ->setDescription('')
2950
            ->setActive(1)
2951
            ->setCreatedBy(1)
2952
        ;
2953
        $em->persist($accessUrl);
2954
        $em->flush();
2955
    }
2956
2957
    if ($upgrade) {
2958
        $settingsManager->updateSchemas($accessUrl);
2959
    } else {
2960
        // Installing schemas (filling settings_current table)
2961
        $settingsManager->installSchemas($accessUrl);
2962
    }
2963
}
2964
2965
/**
2966
 * @param SymfonyContainer $container
2967
 */
2968
function upgradeWithContainer($container)
2969
{
2970
    Container::setContainer($container);
2971
    Container::setLegacyServices($container, false);
2972
    error_log('setLegacyServices');
2973
    $manager = Database::getManager();
2974
    installGroups($container, $manager);
2975
    error_log('installGroups');
2976
    // @todo check if adminId = 1
2977
    installTools($container, $manager, true);
2978
    installSchemas($container, $manager, true);
2979
}
2980
2981
/**
2982
 * After the schema was created (table creation), the function adds
2983
 * admin/platform information.
2984
 *
2985
 * @param \Psr\Container\ContainerInterface $container
2986
 * @param string                            $sysPath
2987
 * @param string                            $encryptPassForm
2988
 * @param string                            $passForm
2989
 * @param string                            $adminLastName
2990
 * @param string                            $adminFirstName
2991
 * @param string                            $loginForm
2992
 * @param string                            $emailForm
2993
 * @param string                            $adminPhoneForm
2994
 * @param string                            $languageForm
2995
 * @param string                            $institutionForm
2996
 * @param string                            $institutionUrlForm
2997
 * @param string                            $siteName
2998
 * @param string                            $allowSelfReg
2999
 * @param string                            $allowSelfRegProf
3000
 * @param string                            $installationProfile Installation profile, if any was provided
3001
 */
3002
function finishInstallationWithContainer(
3003
    $container,
3004
    $sysPath,
3005
    $encryptPassForm,
3006
    $passForm,
3007
    $adminLastName,
3008
    $adminFirstName,
3009
    $loginForm,
3010
    $emailForm,
3011
    $adminPhoneForm,
3012
    $languageForm,
3013
    $institutionForm,
3014
    $institutionUrlForm,
3015
    $siteName,
3016
    $allowSelfReg,
3017
    $allowSelfRegProf,
3018
    $installationProfile = ''
3019
) {
3020
    error_log('finishInstallationWithContainer');
3021
    $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYMFONY_SYS_PATH);
3022
    Container::setContainer($container);
3023
    Container::setLegacyServices($container, false);
3024
    error_log('setLegacyServices');
3025
3026
    $manager = Database::getManager();
3027
    $connection = $manager->getConnection();
3028
    $trans = $container->get('translator');
3029
    $sql = getVersionTable();
3030
3031
    // Add version table
3032
    $connection->executeQuery($sql);
3033
3034
    error_log("Create $sql ");
3035
3036
    // Add tickets defaults
3037
    $ticketProject = new TicketProject();
3038
    $ticketProject
3039
        ->setId(1)
3040
        ->setName('Ticket System')
3041
        ->setInsertUserId(1);
3042
3043
    $manager->persist($ticketProject);
3044
3045
    $categories = [
3046
        $trans->trans('Enrollment') => $trans->trans('Tickets about enrollment'),
3047
        $trans->trans('General information') => $trans->trans('Tickets about general information'),
3048
        $trans->trans('Requests and paperwork') => $trans->trans('Tickets about requests and paperwork'),
3049
        $trans->trans('Academic Incidents') => $trans->trans('Tickets about academic incidents, like exams, practices, tasks, etc.'),
3050
        $trans->trans('Virtual campus') => $trans->trans('Tickets about virtual campus'),
3051
        $trans->trans('Online evaluation') => $trans->trans('Tickets about online evaluation'),
3052
    ];
3053
3054
    $i = 1;
3055
    foreach ($categories as $category => $description) {
3056
        // Online evaluation requires a course
3057
        $ticketCategory = new TicketCategory();
3058
        $ticketCategory
3059
            ->setId($i)
3060
            ->setName($category)
3061
            ->setDescription($description)
3062
            ->setProject($ticketProject)
3063
            ->setInsertUserId(1);
3064
3065
        $isRequired = 6 == $i;
3066
        $ticketCategory->setCourseRequired($isRequired);
3067
3068
        $manager->persist($ticketCategory);
3069
        $i++;
3070
    }
3071
3072
    // Default Priorities
3073
    $defaultPriorities = [
3074
        TicketManager::PRIORITY_NORMAL => $trans->trans('Normal'),
3075
        TicketManager::PRIORITY_HIGH => $trans->trans('High'),
3076
        TicketManager::PRIORITY_LOW => $trans->trans('Low'),
3077
    ];
3078
3079
    $i = 1;
3080
    foreach ($defaultPriorities as $code => $priority) {
3081
        $ticketPriority = new TicketPriority();
3082
        $ticketPriority
3083
            ->setId($i)
3084
            ->setName($priority)
3085
            ->setCode($code)
3086
            ->setInsertUserId(1);
3087
3088
        $manager->persist($ticketPriority);
3089
        $i++;
3090
    }
3091
    error_log("Save ticket data");
3092
    $manager->flush();
3093
3094
    $table = Database::get_main_table(TABLE_TICKET_STATUS);
3095
3096
    // Default status
3097
    $defaultStatus = [
3098
        TicketManager::STATUS_NEW => $trans->trans('New'),
3099
        TicketManager::STATUS_PENDING => $trans->trans('Pending'),
3100
        TicketManager::STATUS_UNCONFIRMED => $trans->trans('Unconfirmed'),
3101
        TicketManager::STATUS_CLOSE => $trans->trans('Close'),
3102
        TicketManager::STATUS_FORWARDED => $trans->trans('Forwarded'),
3103
    ];
3104
3105
    $i = 1;
3106
    foreach ($defaultStatus as $code => $status) {
3107
        $attributes = [
3108
            'id' => $i,
3109
            'code' => $code,
3110
            'name' => $status,
3111
        ];
3112
        Database::insert($table, $attributes);
3113
        $i++;
3114
    }
3115
3116
    installGroups($container, $manager);
3117
3118
    error_log('Inserting data.sql');
3119
    // Inserting default data
3120
    $data = file_get_contents($sysPath.'public/main/install/data.sql');
3121
    $result = $manager->getConnection()->prepare($data);
3122
    $result->execute();
3123
    $result->closeCursor();
3124
3125
    UserManager::setPasswordEncryption($encryptPassForm);
3126
3127
    error_log('user creation - admin');
3128
3129
    // Create admin user.
3130
    $adminId = UserManager::create_user(
3131
        $adminFirstName,
3132
        $adminLastName,
3133
        1,
3134
        $emailForm,
3135
        $loginForm,
3136
        $passForm,
3137
        'ADMIN',
3138
        $languageForm,
3139
        $adminPhoneForm,
3140
        '',
3141
        PLATFORM_AUTH_SOURCE,
3142
        '',
3143
        1,
3144
        0,
3145
        null,
3146
        '',
3147
        false,
3148
        true,
3149
        '',
3150
        false,
3151
        '',
3152
        0,
3153
        [],
3154
        '',
3155
        false,
3156
        false
3157
    );
3158
    error_log('user creation - anon');
3159
    // Create anonymous user.
3160
    $anonId = UserManager::create_user(
3161
        'Joe',
3162
        'Anonymous',
3163
        6,
3164
        'anonymous@localhost',
3165
        'anon',
3166
        'anon',
3167
        'anonymous',
3168
        $languageForm,
3169
        '',
3170
        '',
3171
        PLATFORM_AUTH_SOURCE,
3172
        '',
3173
        1,
3174
        0,
3175
        null,
3176
        '',
3177
        false,
3178
        false,
3179
        '',
3180
        false,
3181
        '',
3182
        $adminId,
3183
        [],
3184
        '',
3185
        false,
3186
        false
3187
    );
3188
    $userManager = $container->get('Chamilo\CoreBundle\Repository\UserRepository');
3189
    $urlRepo = $container->get('Chamilo\CoreBundle\Repository\AccessUrlRepository');
3190
3191
    installTools($container, $manager, false);
3192
3193
    /** @var User $admin */
3194
    $admin = $userManager->find($adminId);
3195
3196
    // Login as admin
3197
    $token = new UsernamePasswordToken(
3198
        $admin,
3199
        $admin->getPassword(),
3200
        'public',
3201
        $admin->getRoles()
3202
    );
3203
    $container->get('security.token_storage')->setToken($token);
3204
3205
    $userManager->addUserToResourceNode($adminId, $adminId);
3206
    $userManager->addUserToResourceNode($anonId, $adminId);
3207
    $manager->flush();
3208
3209
    installSchemas($container, $manager, false);
3210
    $accessUrl = $urlRepo->find(1);
3211
3212
    UrlManager::add_user_to_url($adminId, $adminId);
3213
    UrlManager::add_user_to_url($anonId, $adminId);
3214
3215
    $branch = new BranchSync();
3216
    $branch->setBranchName('localhost');
3217
    $branch->setUrl($accessUrl);
3218
    $manager->persist($branch);
3219
    $manager->flush();
3220
3221
    // Set default language
3222
    Database::update(
3223
        Database::get_main_table(TABLE_MAIN_LANGUAGE),
3224
        ['available' => 1],
3225
        ['dokeos_folder = ?' => $languageForm]
3226
    );
3227
3228
    // Install settings
3229
    installSettings(
3230
        $institutionForm,
3231
        $institutionUrlForm,
3232
        $siteName,
3233
        $emailForm,
3234
        $adminLastName,
3235
        $adminFirstName,
3236
        $languageForm,
3237
        $allowSelfReg,
3238
        $allowSelfRegProf,
3239
        $installationProfile
3240
    );
3241
3242
    lockSettings();
3243
    updateDirAndFilesPermissions();
3244
}
3245
3246
/**
3247
 * Creates 'version' table.
3248
 */
3249
function createVersionTable()
3250
{
3251
    $sql = getVersionTable();
3252
    Database::query($sql);
3253
}
3254
3255
/**
3256
 * Get version creation table query.
3257
 *
3258
 * @return string
3259
 */
3260
function getVersionTable()
3261
{
3262
    return 'CREATE TABLE IF NOT EXISTS version (id int unsigned NOT NULL AUTO_INCREMENT, version varchar(20), PRIMARY KEY(id), UNIQUE(version));';
3263
}
3264
3265
/**
3266
 * Update settings based on installation profile defined in a JSON file.
3267
 *
3268
 * @param string $installationProfile The name of the JSON file in main/install/profiles/ folder
3269
 *
3270
 * @return bool false on failure (no bad consequences anyway, just ignoring profile)
3271
 */
3272
function installProfileSettings($installationProfile = '')
3273
{
3274
    if (empty($installationProfile)) {
3275
        return false;
3276
    }
3277
    $jsonPath = api_get_path(SYS_PATH).'main/install/profiles/'.$installationProfile.'.json';
3278
    // Make sure the path to the profile is not hacked
3279
    if (!Security::check_abs_path($jsonPath, api_get_path(SYS_PATH).'main/install/profiles/')) {
3280
        return false;
3281
    }
3282
    if (!is_file($jsonPath)) {
3283
        return false;
3284
    }
3285
    if (!is_readable($jsonPath)) {
3286
        return false;
3287
    }
3288
    if (!function_exists('json_decode')) {
3289
        // The php-json extension is not available. Ignore profile.
3290
        return false;
3291
    }
3292
    $json = file_get_contents($jsonPath);
3293
    $params = json_decode($json);
3294
    if (false === $params or null === $params) {
3295
        return false;
3296
    }
3297
    $settings = $params->params;
3298
    if (!empty($params->parent)) {
3299
        installProfileSettings($params->parent);
3300
    }
3301
3302
    $tblSettings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
3303
3304
    foreach ($settings as $id => $param) {
3305
        $conditions = ['variable = ? ' => $param->variable];
3306
3307
        if (!empty($param->subkey)) {
3308
            $conditions['AND subkey = ? '] = $param->subkey;
3309
        }
3310
3311
        Database::update(
3312
            $tblSettings,
3313
            ['selected_value' => $param->selected_value],
3314
            $conditions
3315
        );
3316
    }
3317
3318
    return true;
3319
}
3320
3321
/**
3322
 * Quick function to remove a directory with its subdirectories.
3323
 *
3324
 * @param $dir
3325
 */
3326
function rrmdir($dir)
3327
{
3328
    if (is_dir($dir)) {
3329
        $objects = scandir($dir);
3330
        foreach ($objects as $object) {
3331
            if ("." != $object && ".." != $object) {
3332
                if ("dir" == filetype($dir."/".$object)) {
3333
                    @rrmdir($dir."/".$object);
0 ignored issues
show
Bug introduced by
Are you sure the usage of rrmdir($dir . '/' . $object) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for rrmdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

3333
                    /** @scrutinizer ignore-unhandled */ @rrmdir($dir."/".$object);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3334
                } else {
3335
                    @unlink($dir."/".$object);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

3335
                    /** @scrutinizer ignore-unhandled */ @unlink($dir."/".$object);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3336
                }
3337
            }
3338
        }
3339
        reset($objects);
3340
        rmdir($dir);
3341
    }
3342
}
3343
3344
/**
3345
 * @param        $id
3346
 * @param string $type
3347
 * @param bool   $preview
3348
 * @param bool   $anonymous
3349
 *
3350
 * @throws \Doctrine\DBAL\DBALException
3351
 *
3352
 * @return array
3353
 */
3354
function get_group_picture_path_by_id($id, $type = 'web', $preview = false, $anonymous = false)
3355
{
3356
    switch ($type) {
3357
        case 'system': // Base: absolute system path.
3358
            $base = api_get_path(SYS_UPLOAD_PATH);
3359
            break;
3360
        case 'web': // Base: absolute web path.
3361
        default:
3362
            $base = api_get_path(WEB_UPLOAD_PATH);
3363
            break;
3364
    }
3365
3366
    $noPicturePath = ['dir' => $base.'img/', 'file' => 'unknown.jpg'];
3367
3368
    if (empty($id) || empty($type)) {
3369
        return $anonymous ? $noPicturePath : ['dir' => '', 'file' => ''];
3370
    }
3371
3372
    $id = intval($id);
3373
3374
    //$group_table = Database::get_main_table(TABLE_MAIN_GROUP);
3375
    $group_table = 'groups';
3376
    $sql = "SELECT picture_uri FROM $group_table WHERE id=".$id;
3377
    $res = Database::query($sql);
3378
3379
    if (!Database::num_rows($res)) {
3380
        return $anonymous ? $noPicturePath : ['dir' => '', 'file' => ''];
3381
    }
3382
3383
    $user = Database::fetch_array($res);
3384
    $picture_filename = trim($user['picture_uri']);
3385
3386
    if ('true' === api_get_setting('split_users_upload_directory')) {
3387
        if (!empty($picture_filename)) {
3388
            $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
3389
        } elseif ($preview) {
3390
            $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
3391
        } else {
3392
            $dir = $base.'groups/'.$id.'/';
3393
        }
3394
    } else {
3395
        $dir = $base.'groups/'.$id.'/';
3396
    }
3397
3398
    if (empty($picture_filename) && $anonymous) {
3399
        return $noPicturePath;
3400
    }
3401
3402
    return ['dir' => $dir, 'file' => $picture_filename];
3403
}
3404
3405
/**
3406
 * Control the different steps of the migration through a big switch.
3407
 *
3408
 * @param string        $fromVersion
3409
 * @param EntityManager $manager
3410
 * @param bool          $processFiles
3411
 *
3412
 * @throws \Doctrine\DBAL\DBALException
3413
 *
3414
 * @return bool Always returns true except if the process is broken
3415
 */
3416
function migrateSwitch($fromVersion, $manager, $processFiles = true)
3417
{
3418
    error_log('Starting migration process from '.$fromVersion.' ('.date('Y-m-d H:i:s').')');
3419
3420
    echo '<a class="btn btn-secondary" href="javascript:void(0)" id="details_button">'.get_lang('Details').'</a><br />';
3421
    echo '<div id="details" style="display:none">';
3422
3423
    $connection = $manager->getConnection();
3424
3425
    $database = new Database();
3426
    $database->setManager($manager);
3427
3428
    switch ($fromVersion) {
3429
        case '1.11.0':
3430
        case '1.11.1':
3431
        case '1.11.2':
3432
        case '1.11.4':
3433
        case '1.11.6':
3434
        case '1.11.8':
3435
        case '1.11.10':
3436
        case '1.11.12':
3437
        case '1.11.14':
3438
            $database = new Database();
3439
            $database->setManager($manager);
3440
            // Migrate using the migration files located in:
3441
            // src/Chamilo/CoreBundle/Migrations/Schema/V111
3442
            $result = migrate(200, $manager);
3443
3444
            if ($result) {
3445
                error_log('Migrations files were executed ('.date('Y-m-d H:i:s').')');
3446
                $sql = "UPDATE settings_current SET selected_value = '2.0.0' WHERE variable = 'chamilo_database_version'";
3447
                $connection->executeQuery($sql);
3448
                if ($processFiles) {
3449
                    error_log('Update config files');
3450
                    $fromVersionShort = '1.11';
3451
                    include __DIR__.'/update-files-1.11.0-2.0.0.inc.php';
3452
                    // Only updates the configuration.inc.php with the new version
3453
                    include __DIR__.'/update-configuration.inc.php';
3454
                }
3455
                error_log('Upgrade 2.0.0 process concluded!  ('.date('Y-m-d H:i:s').')');
3456
            } else {
3457
                error_log('There was an error during running migrations. Check error.log');
3458
            }
3459
            break;
3460
        default:
3461
            break;
3462
    }
3463
3464
    echo '</div>';
3465
3466
    return true;
3467
}
3468
3469
/**
3470
 * @param \Doctrine\DBAL\Connection $connection
3471
 *
3472
 * @throws \Doctrine\DBAL\DBALException
3473
 */
3474
function fixPostGroupIds($connection)
3475
{
3476
    $connection->executeQuery("ALTER TABLE course_category MODIFY COLUMN auth_course_child VARCHAR(40) DEFAULT 'TRUE'");
3477
    error_log('Fix c_student_publication.post_group_id');
3478
3479
    // Fix post_group_id
3480
    $sql = "SELECT * FROM c_student_publication
3481
            WHERE (post_group_id <> 0 AND post_group_id is not null)";
3482
    $statement = $connection->executeQuery($sql);
3483
    $result = $statement->fetchAll();
3484
3485
    foreach ($result as $row) {
3486
        $groupId = $row['post_group_id'];
3487
        $courseId = $row['c_id'];
3488
        $workIid = $row['iid'];
3489
        $sql = "SELECT iid from c_group_info
3490
                WHERE c_id = $courseId AND id = $groupId";
3491
        $statement = $connection->executeQuery($sql);
3492
        $count = $statement->rowCount();
3493
        if ($count > 0) {
3494
            $rowGroup = $statement->fetch();
3495
            $newGroupId = $rowGroup['iid'];
3496
            if ($newGroupId == $groupId) {
3497
                continue;
3498
            }
3499
            if ($newGroupId) {
3500
                $sql = "UPDATE c_student_publication
3501
                        SET post_group_id = $newGroupId
3502
                        WHERE
3503
                            c_id = $courseId AND
3504
                            iid = $workIid
3505
                        ";
3506
                $connection->executeQuery($sql);
3507
            }
3508
        }
3509
    }
3510
3511
    error_log('End - Fix c_student_publication.post_group_id');
3512
3513
    // Delete c_student_publication from any session that doesn't exist anymore
3514
    $sql = "DELETE FROM c_student_publication
3515
            WHERE session_id NOT IN (SELECT id FROM session) AND (session_id <> 0 AND session_id is not null)";
3516
    $connection->executeQuery($sql);
3517
3518
    error_log('Fix work documents');
3519
    // Fix work documents that don't have c_item_property value
3520
    $sql = "SELECT * FROM c_student_publication WHERE parent_id IS NOT NULL";
3521
    $statement = $connection->executeQuery($sql);
3522
    $result = $statement->fetchAll();
3523
    foreach ($result as $row) {
3524
        $groupId = $row['post_group_id'];
3525
        $courseId = $row['c_id'];
3526
        $sessionId = $row['session_id'];
3527
        $workId = $row['id'];
3528
        $sessionCondition = " session_id = $sessionId";
3529
        if (empty($sessionId)) {
3530
            $sessionCondition = ' (session_id = 0 OR session_id IS NULL) ';
3531
        }
3532
        $sql = "SELECT * FROM c_item_property
3533
                WHERE
3534
                    c_id = $courseId AND
3535
                    tool = 'work' AND
3536
                    ref = $workId AND
3537
                    $sessionCondition ";
3538
        $itemInfo = $connection->fetchAssoc($sql);
3539
        if (empty($itemInfo)) {
3540
            $params = [
3541
                'c_id' => $courseId,
3542
                'to_group_id' => $groupId,
3543
                //'to_user_id' => null,
3544
                'insert_user_id' => 1,
3545
                'session_id' => $sessionId,
3546
                'tool' => 'work',
3547
                'insert_date' => api_get_utc_datetime(),
3548
                'lastedit_date' => api_get_utc_datetime(),
3549
                'ref' => $workId,
3550
                'lastedit_type' => 'visible',
3551
                'lastedit_user_id' => 1,
3552
                'visibility' => 1,
3553
            ];
3554
            $connection->insert('c_item_property', $params);
3555
            $id = $connection->lastInsertId();
3556
            $sql = "UPDATE c_item_property SET id = iid WHERE iid = $id";
3557
            $connection->executeQuery($sql);
3558
        }
3559
    }
3560
    error_log('End - Fix work documents');
3561
}
3562
3563
/**
3564
 * @return string
3565
 */
3566
function generateRandomToken()
3567
{
3568
    return hash('sha1', uniqid(mt_rand(), true));
3569
}
3570
3571
/**
3572
 * This function checks if the given file can be created or overwritten
3573
 *
3574
 * @param string $file     Full path to a file
3575
 *
3576
 * @return string   An HTML coloured label showing success or failure
3577
 */
3578
function checkCanCreateFile($file)
3579
{
3580
    if (file_exists($file)) {
3581
        if (is_writeable($file)) {
3582
            return Display::label(get_lang('Writable'), 'success');
3583
        } else {
3584
            return Display::label(get_lang('Not writable'), 'important');
3585
        }
3586
    } else {
3587
        $write = @file_put_contents($file, '');
3588
        if ($write) {
3589
            unlink($file);
3590
            return Display::label(get_lang('Writable'), 'success');
3591
        } else {
3592
            return Display::label(get_lang('Not writable'), 'important');
3593
        }
3594
    }
3595
}
3596