Completed
Push — 1.10.x ( ba0bf0...97c0d2 )
by Angel Fernando Quiroz
44:06
created

install.lib.php ➔ display_configuration_settings_form()   F

Complexity

Conditions 21
Paths 17952

Size

Total Lines 187
Code Lines 111

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 21
eloc 111
nc 17952
nop 15
dl 0
loc 187
rs 2

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Chamilo LMS
6
 * This file contains functions used by the install and upgrade scripts.
7
 *
8
 * Ideas for future additions:
9
 * - a function get_old_version_settings to retrieve the config file settings
10
 *   of older versions before upgrading.
11
 */
12
13
use Doctrine\ORM\EntityManager;
14
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField.

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...
15
use Chamilo\CoreBundle\Entity\ExtraFieldOptions;
16
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
17
18
/*      CONSTANTS */
19
define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
20
21
/**
22
 * This function detects whether the system has been already installed.
23
 * It should be used for prevention from second running the installation
24
 * script and as a result - destroying a production system.
25
 * @return bool     The detected result;
26
 * @author Ivan Tcholakov, 2010;
27
 */
28
function isAlreadyInstalledSystem()
29
{
30
    global $new_version, $_configuration;
31
32
    if (empty($new_version)) {
33
        return true; // Must be initialized.
34
    }
35
36
    $current_config_file = api_get_path(CONFIGURATION_PATH).'configuration.php';
37
    if (!file_exists($current_config_file)) {
38
        return false; // Configuration file does not exist, install the system.
39
    }
40
    require $current_config_file;
41
42
    $current_version = null;
43
    if (isset($_configuration['system_version'])) {
44
        $current_version = trim($_configuration['system_version']);
45
    }
46
47
    // If the current version is old, upgrading is assumed, the installer goes ahead.
48
    return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
49
}
50
51
/**
52
 * This function checks if a php extension exists or not and returns an HTML status string.
53
 *
54
 * @param   string  $extensionName Name of the PHP extension to be checked
55
 * @param   string  $returnSuccess Text to show when extension is available (defaults to 'Yes')
56
 * @param   string  $returnFailure Text to show when extension is available (defaults to 'No')
57
 * @param   boolean $optional Whether this extension is optional (then show unavailable text in orange rather than red)
58
 * @return  string  HTML string reporting the status of this extension. Language-aware.
59
 * @author  Christophe Gesch??
60
 * @author  Patrick Cool <[email protected]>, Ghent University
61
 * @author  Yannick Warnier <[email protected]>
62
 */
63
function checkExtension($extensionName, $returnSuccess = 'Yes', $returnFailure = 'No', $optional = false)
64
{
65
    if (extension_loaded($extensionName)) {
66
        return Display::label($returnSuccess, 'success');
67
    } else {
68
        if ($optional) {
69
            return Display::label($returnFailure, 'warning');
70
        } else {
71
            return Display::label($returnFailure, 'important');
72
        }
73
    }
74
}
75
76
/**
77
 * This function checks whether a php setting matches the recommended value
78
 * @param   string $phpSetting A PHP setting to check
79
 * @param   string  $recommendedValue A recommended value to show on screen
80
 * @param   mixed  $returnSuccess What to show on success
81
 * @param   mixed  $returnFailure  What to show on failure
82
 * @return  string  A label to show
83
 * @author Patrick Cool <[email protected]>, Ghent University
84
 */
85
function checkPhpSetting($phpSetting, $recommendedValue, $returnSuccess = false, $returnFailure = false)
86
{
87
    $currentPhpValue = getPhpSetting($phpSetting);
88
    if ($currentPhpValue == $recommendedValue) {
89
        return Display::label($currentPhpValue.' '.$returnSuccess, 'success');
90
    } else {
91
        return Display::label($currentPhpValue.' '.$returnSuccess, 'important');
92
    }
93
}
94
95
96
/**
97
 * This function return the value of a php.ini setting if not "" or if exists,
98
 * otherwise return false
99
 * @param   string  $phpSetting The name of a PHP setting
100
 * @return  mixed   The value of the setting, or false if not found
101
 */
102
function checkPhpSettingExists($phpSetting)
103
{
104
    if (ini_get($phpSetting) != "") {
105
        return ini_get($phpSetting);
106
    }
107
108
    return false;
109
}
110
111
/**
112
 * Returns a textual value ('ON' or 'OFF') based on a requester 2-state ini- configuration setting.
113
 *
114
 * @param string $val a php ini value
115
 * @return boolean: ON or OFF
0 ignored issues
show
Documentation introduced by
The doc-type boolean: could not be parsed: Unknown type name "boolean:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
116
 * @author Joomla <http://www.joomla.org>
117
 */
118
function getPhpSetting($val)
119
{
120
    return ini_get($val) == '1' ? 'ON' : 'OFF';
121
}
122
123
/**
124
 * This function returns a string "true" or "false" according to the passed parameter.
125
 *
126
 * @param integer  $var  The variable to present as text
127
 * @return  string  the string "true" or "false"
128
 * @author Christophe Gesch??
129
 */
130
function trueFalse($var)
131
{
132
    return $var ? 'true' : 'false';
133
}
134
135
/**
136
 * Removes memory and time limits as much as possible.
137
 */
138
function remove_memory_and_time_limits()
139
{
140
    if (function_exists('ini_set')) {
141
        ini_set('memory_limit', -1);
142
        ini_set('max_execution_time', 0);
143
        error_log('Update-db script: memory_limit set to -1', 0);
144
        error_log('Update-db script: max_execution_time 0', 0);
145
    } else {
146
        error_log('Update-db script: could not change memory and time limits', 0);
147
    }
148
}
149
150
/**
151
 * Detects browser's language.
152
 * @return string       Returns a language identificator, i.e. 'english', 'spanish', ...
153
 * @author Ivan Tcholakov, 2010
154
 */
155
function detect_browser_language()
156
{
157
    static $language_index = array(
158
        'ar' => 'arabic',
159
        'ast' => 'asturian',
160
        'bg' => 'bulgarian',
161
        'bs' => 'bosnian',
162
        'ca' => 'catalan',
163
        'zh' => 'simpl_chinese',
164
        'zh-tw' => 'trad_chinese',
165
        'cs' => 'czech',
166
        'da' => 'danish',
167
        'prs' => 'dari',
168
        'de' => 'german',
169
        'el' => 'greek',
170
        'en' => 'english',
171
        'es' => 'spanish',
172
        'eo' => 'esperanto',
173
        'eu' => 'basque',
174
        'fa' => 'persian',
175
        'fr' => 'french',
176
        'fur' => 'friulian',
177
        'gl' => 'galician',
178
        'ka' => 'georgian',
179
        'hr' => 'croatian',
180
        'he' => 'hebrew',
181
        'hi' => 'hindi',
182
        'id' => 'indonesian',
183
        'it' => 'italian',
184
        'ko' => 'korean',
185
        'lv' => 'latvian',
186
        'lt' => 'lithuanian',
187
        'mk' => 'macedonian',
188
        'hu' => 'hungarian',
189
        'ms' => 'malay',
190
        'nl' => 'dutch',
191
        'ja' => 'japanese',
192
        'no' => 'norwegian',
193
        'oc' => 'occitan',
194
        'ps' => 'pashto',
195
        'pl' => 'polish',
196
        'pt' => 'portuguese',
197
        'pt-br' => 'brazilian',
198
        'ro' => 'romanian',
199
        'qu' => 'quechua_cusco',
200
        'ru' => 'russian',
201
        'sk' => 'slovak',
202
        'sl' => 'slovenian',
203
        'sr' => 'serbian',
204
        'fi' => 'finnish',
205
        'sv' => 'swedish',
206
        'th' => 'thai',
207
        'tr' => 'turkish',
208
        'uk' => 'ukrainian',
209
        'vi' => 'vietnamese',
210
        'sw' => 'swahili',
211
        'yo' => 'yoruba'
212
    );
213
214
    $system_available_languages = & get_language_folder_list();
215
216
    $accept_languages = strtolower(str_replace('_', '-', $_SERVER['HTTP_ACCEPT_LANGUAGE']));
217
    foreach ($language_index as $code => $language) {
218
        if (strpos($accept_languages, $code) === 0) {
219
            if (!empty($system_available_languages[$language])) {
220
                return $language;
221
            }
222
        }
223
    }
224
225
    $user_agent = strtolower(str_replace('_', '-', $_SERVER['HTTP_USER_AGENT']));
226
    foreach ($language_index as $code => $language) {
227
        if (@preg_match("/[\[\( ]{$code}[;,_\-\)]/", $user_agent)) {
228
            if (!empty($system_available_languages[$language])) {
229
                return $language;
230
            }
231
        }
232
    }
233
234
    return 'english';
235
}
236
237
/*      FILESYSTEM RELATED FUNCTIONS */
238
239
/**
240
 * This function checks if the given folder is writable
241
 * @param   string  $folder Full path to a folder
242
 * @param   bool    $suggestion Whether to show a suggestion or not
243
 * @return  string
244
 */
245 View Code Duplication
function check_writable($folder, $suggestion = false)
246
{
247
    if (is_writable($folder)) {
248
        return Display::label(get_lang('Writable'), 'success');
249
    } else {
250
        if ($suggestion) {
251
            return Display::label(get_lang('NotWritable'), 'info');
252
        } else {
253
            return Display::label(get_lang('NotWritable'), 'important');
254
        }
255
    }
256
}
257
258
/**
259
 * This function checks if the given folder is readable
260
 * @param   string  $folder Full path to a folder
261
 * @param   bool    $suggestion Whether to show a suggestion or not
262
 *
263
 * @return  string
264
 */
265 View Code Duplication
function checkReadable($folder, $suggestion = false)
266
{
267
    if (is_readable($folder)) {
268
        return Display::label(get_lang('Readable'), 'success');
269
    } else {
270
        if ($suggestion) {
271
            return Display::label(get_lang('NotReadable'), 'info');
272
        } else {
273
            return Display::label(get_lang('NotReadable'), 'important');
274
        }
275
    }
276
}
277
278
/**
279
 * This function is similar to the core file() function, except that it
280
 * works with line endings in Windows (which is not the case of file())
281
 * @param   string  $filename
282
 *
283
 * @return  array   The lines of the file returned as an array
284
 */
285
function file_to_array($filename)
286
{
287
    if (!is_readable($filename) || is_dir($filename)) {
288
        return array();
289
    }
290
    $fp = fopen($filename, 'rb');
291
    $buffer = fread($fp, filesize($filename));
292
    fclose($fp);
293
294
    return explode('<br />', nl2br($buffer));
295
}
296
297
/**
298
 * We assume this function is called from install scripts that reside inside the install folder.
299
 */
300
function set_file_folder_permissions()
301
{
302
    @chmod('.', 0755); //set permissions on install dir
303
    @chmod('..', 0755); //set permissions on parent dir of install dir
304
}
305
306
/**
307
 * Add's a .htaccess file to the courses directory
308
 * @param string $url_append The path from your webroot to your chamilo root
309
 * @return bool Result of writing the file
310
 */
311
/*function write_courses_htaccess_file($url_append)
312
{
313
    $content = file_get_contents(dirname(__FILE__).'/'.COURSES_HTACCESS_FILENAME);
314
    $content = str_replace('{CHAMILO_URL_APPEND_PATH}', $url_append, $content);
315
    $fp = @fopen(api_get_path(SYS_COURSE_PATH).'.htaccess', 'w');
316
    if ($fp) {
317
        fwrite($fp, $content);
318
        return fclose($fp);
319
    }
320
    return false;
321
}*/
322
323
/**
324
 * Write the main system config file
325
 * @param string $path Path to the config file
326
 */
327
function write_system_config_file($path)
328
{
329
    global $dbHostForm;
330
    global $dbPortForm;
331
    global $dbUsernameForm;
332
    global $dbPassForm;
333
    global $dbNameForm;
334
    global $urlForm;
335
    global $pathForm;
336
    global $urlAppendPath;
337
    global $languageForm;
338
    global $encryptPassForm;
339
    global $session_lifetime;
340
    global $new_version;
341
    global $new_version_stable;
342
343
    $root_sys = api_add_trailing_slash(str_replace('\\', '/', realpath($pathForm)));
344
    $content = file_get_contents(dirname(__FILE__).'/'.SYSTEM_CONFIG_FILENAME);
345
346
    $config['{DATE_GENERATED}'] = date('r');
347
    $config['{DATABASE_HOST}'] = $dbHostForm;
348
    $config['{DATABASE_PORT}'] = $dbPortForm;
349
    $config['{DATABASE_USER}'] = $dbUsernameForm;
350
    $config['{DATABASE_PASSWORD}'] = $dbPassForm;
351
    $config['{DATABASE_MAIN}'] = $dbNameForm;
352
    $config['{ROOT_WEB}'] = $urlForm;
353
    $config['{ROOT_SYS}'] = $root_sys;
354
    $config['{URL_APPEND_PATH}'] = $urlAppendPath;
355
    $config['{PLATFORM_LANGUAGE}'] = $languageForm;
356
    $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
357
    $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm;
358
359
    $config['SESSION_LIFETIME'] = $session_lifetime;
360
    $config['{NEW_VERSION}'] = $new_version;
361
    $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable);
362
363
    foreach ($config as $key => $value) {
364
        $content = str_replace($key, $value, $content);
365
    }
366
367
    $fp = @ fopen($path, 'w');
368
369
    if (!$fp) {
370
        echo '<strong><font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
371
                        <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
372
                        You probably do not have write access on Chamilo root directory,
373
                        i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
374
                        Your problems can be related on two possible causes:<br />
375
                        <ul>
376
                          <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
377
                          <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>. If possible, try to switch it off.</li>
378
                        </ul>
379
                        <a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
380
                        Please go back to step 5.
381
                        <p><input type="submit" name="step5" value="&lt; Back" /></p>
382
                        </td></tr></table></form></body></html>';
383
        exit;
384
    }
385
386
    fwrite($fp, $content);
387
    fclose($fp);
388
}
389
390
/**
391
 * Returns a list of language directories.
392
 */
393
function & get_language_folder_list()
394
{
395
    static $result;
396
    if (!is_array($result)) {
397
        $result = array();
398
        $exceptions = array('.', '..', 'CVS', '.svn');
399
        $search       = array('_latin',   '_unicode',   '_corporate',   '_org'  , '_KM',   '_');
400
        $replace_with = array(' (Latin)', ' (unicode)', ' (corporate)', ' (org)', ' (KM)', ' ');
401
        $dirname = api_get_path(SYS_LANG_PATH);
402
        $handle = opendir($dirname);
403
        while ($entries = readdir($handle)) {
404
            if (in_array($entries, $exceptions)) {
405
                continue;
406
            }
407
            if (is_dir($dirname.$entries)) {
408
                if (is_file($dirname.$entries.'/install_disabled')) {
409
                    // Skip all languages that have this file present, just for
410
                    // the install process (languages incomplete)
411
                    continue;
412
                }
413
                $result[$entries] = ucwords(str_replace($search, $replace_with, $entries));
414
            }
415
        }
416
        closedir($handle);
417
        asort($result);
418
    }
419
    return $result;
420
}
421
422
/**
423
 * TODO: my_directory_to_array() - maybe within the main API there is already a suitable function?
424
 * @param   string  $directory  Full path to a directory
425
 * @return  array   A list of files and dirs in the directory
426
 */
427 View Code Duplication
function my_directory_to_array($directory)
428
{
429
    $array_items = array();
430
    if ($handle = opendir($directory)) {
431
        while (false !== ($file = readdir($handle))) {
432
            if ($file != "." && $file != "..") {
433
                if (is_dir($directory. "/" . $file)) {
434
                    $array_items = array_merge($array_items, my_directory_to_array($directory. '/' . $file));
435
                    $file = $directory . "/" . $file;
436
                    $array_items[] = preg_replace("/\/\//si", '/', $file);
437
                }
438
            }
439
        }
440
        closedir($handle);
441
    }
442
    return $array_items;
443
}
444
445
/**
446
 * This function returns the value of a parameter from the configuration file
447
 *
448
 * WARNING - this function relies heavily on global variables $updateFromConfigFile
449
 * and $configFile, and also changes these globals. This can be rewritten.
450
 *
451
 * @param   string  $param  the parameter of which the value is returned
452
 * @param   string  If we want to give the path rather than take it from POST
453
 * @return  string  the value of the parameter
454
 * @author Olivier Brouckaert
455
 * @author Reworked by Ivan Tcholakov, 2010
456
 */
457
function get_config_param($param, $updatePath = '')
458
{
459
    global $configFile, $updateFromConfigFile;
460
461
    // Look if we already have the queried parameter.
462
    if (is_array($configFile) && isset($configFile[$param])) {
463
        return $configFile[$param];
464
    }
465
    if (empty($updatePath) && !empty($_POST['updatePath'])) {
466
        $updatePath = $_POST['updatePath'];
467
    }
468
469
    if (empty($updatePath)) {
470
        $updatePath = api_get_path(SYS_PATH);
471
    }
472
    $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath)));
473
    $updateFromInstalledVersionFile = '';
474
475
    if (empty($updateFromConfigFile)) {
476
        // If update from previous install was requested,
477
        // try to recover config file from Chamilo 1.9.x
478
        if (file_exists($updatePath.'main/inc/conf/configuration.php')) {
479
            $updateFromConfigFile = 'main/inc/conf/configuration.php';
480
        } else {
481
            // Give up recovering.
482
            //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);
483
            return null;
484
        }
485
    }
486
487
    if (file_exists($updatePath.$updateFromConfigFile) &&
488
        !is_dir($updatePath.$updateFromConfigFile)
489
    ) {
490
        require $updatePath.$updateFromConfigFile;
491
        $config = new Zend\Config\Config($_configuration);
0 ignored issues
show
Bug introduced by
The variable $_configuration does not exist. Did you forget to declare it?

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

Loading history...
492
        return $config->get($param);
493
    }
494
495
    error_log('Config array could not be found in get_config_param()', 0);
496
    return null;
497
498
    /*if (file_exists($updatePath.$updateFromConfigFile)) {
499
        return $val;
500
    } else {
501
        error_log('Config array could not be found in get_config_param()', 0);
502
        return null;
503
    }*/
504
}
505
506
/*      DATABASE RELATED FUNCTIONS */
507
508
/**
509
 * Gets a configuration parameter from the database. Returns returns null on failure.
510
 * @param   string  $param Name of param we want
511
 * @return  mixed   The parameter value or null if not found
512
 */
513
function get_config_param_from_db($param = '')
514
{
515 View Code Duplication
    if (($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'")) !== false) {
516
        if (Database::num_rows($res) > 0) {
517
            $row = Database::fetch_array($res);
518
            return $row['selected_value'];
519
        }
520
    }
521
    return null;
522
}
523
524
/**
525
 * Connect to the database and returns the entity manager
526
 * @param string  $dbHostForm DB host
527
 * @param string  $dbUsernameForm DB username
528
 * @param string  $dbPassForm DB password
529
 * @param string  $dbNameForm DB name
530
 * @param int     $dbPortForm DB port
531
 *
532
 * @return EntityManager
533
 */
534
function connectToDatabase($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm, $dbPortForm = 3306)
535
{
536
    $dbParams = array(
537
        'driver' => 'pdo_mysql',
538
        'host' => $dbHostForm,
539
        'port' => $dbPortForm,
540
        'user' => $dbUsernameForm,
541
        'password' => $dbPassForm,
542
        'dbname' => $dbNameForm
543
    );
544
545
    $database = new \Database();
546
    $database->connect($dbParams);
547
548
    return $database->getManager();
549
}
550
551
/*      DISPLAY FUNCTIONS */
552
553
/**
554
 * This function prints class=active_step $current_step=$param
555
 * @param   int $param  A step in the installer process
556
 * @author Patrick Cool <[email protected]>, Ghent University
557
 */
558
function step_active($param)
559
{
560
    global $current_step;
561
    if ($param == $current_step) {
562
        echo 'class="current-step" ';
563
    }
564
}
565
566
/**
567
 * This function displays the Step X of Y -
568
 * @return  string  String that says 'Step X of Y' with the right values
569
 */
570
function display_step_sequence()
571
{
572
    global $current_step;
573
    return get_lang('Step'.$current_step).' &ndash; ';
574
}
575
576
/**
577
 * Displays a drop down box for selection the preferred language.
578
 */
579
function display_language_selection_box($name = 'language_list', $default_language = 'english')
580
{
581
    // Reading language list.
582
    $language_list = get_language_folder_list();
583
584
    /*
585
    // Reduction of the number of languages shown. Enable this fragment of code for customization purposes.
586
    // Modify the language list according to your preference. Don't exclude the 'english' item.
587
    $language_to_display = array('asturian', 'bulgarian', 'english', 'italian', 'french', 'slovenian', 'slovenian_unicode', 'spanish');
588
    foreach ($language_list as $key => & $value) {
589
        if (!in_array($key, $language_to_display)) {
590
            unset($language_list[$key]);
591
        }
592
    }
593
    */
594
595
    // Sanity checks due to the possibility for customizations.
596
    if (!is_array($language_list) || empty($language_list)) {
597
        $language_list = array('english' => 'English');
598
    }
599
600
    // Sorting again, if it is necessary.
601
    //asort($language_list);
602
603
    // More sanity checks.
604
    if (!array_key_exists($default_language, $language_list)) {
605
        if (array_key_exists('english', $language_list)) {
606
            $default_language = 'english';
607
        } else {
608
            $language_keys = array_keys($language_list);
609
            $default_language = $language_keys[0];
610
        }
611
    }
612
613
    // Displaying the box.
614
    $html = '';
615
    $html .= "\t\t<select class='selectpicker show-tick' name=\"$name\">\n";
616
    foreach ($language_list as $key => $value) {
617
        if ($key == $default_language) {
618
            $option_end = ' selected="selected">';
619
        } else {
620
            $option_end = '>';
621
        }
622
        $html .= "\t\t\t<option value=\"$key\"$option_end";
623
        $html .= $value;
624
        $html .= "</option>\n";
625
    }
626
    $html .= "\t\t</select>\n";
627
    return $html;
628
}
629
630
/**
631
 * This function displays a language dropdown box so that the installatioin
632
 * can be done in the language of the user
633
 */
634
function display_language_selection()
635
{ ?>
636
    <h2><?php get_lang('WelcomeToTheChamiloInstaller'); ?></h2>
637
    <div class="RequirementHeading">
638
        <h2><?php echo display_step_sequence(); ?>
639
            <?php echo get_lang('InstallationLanguage');?>
640
        </h2>
641
        <p><?php echo get_lang('PleaseSelectInstallationProcessLanguage'); ?>:</p>
642
        <form id="lang_form" method="post" action="<?php echo api_get_self(); ?>">
643
        <div class="form-group">
644
            <div class="col-sm-4">
645
                <?php echo display_language_selection_box('language_list', api_get_interface_language()); ?>
646
            </div>
647
            <div class="col-sm-6">
648
                <button type="submit" name="step1" class="btn btn-success" value="<?php echo get_lang('Next'); ?>">
649
                    <em class="fa fa-forward"> </em>
650
                    <?php echo get_lang('Next'); ?></button>
651
            </div>
652
        </div>
653
654
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
655
        </form>
656
657
    </div>
658
    <div class="RequirementHeading">
659
        <?php echo get_lang('YourLanguageNotThereContactUs'); ?>
660
    </div>
661
<?php
662
}
663
664
/**
665
 * This function displays the requirements for installing Chamilo.
666
 *
667
 * @param string $installType
668
 * @param boolean $badUpdatePath
669
 * @param boolean $badUpdatePath
670
 * @param string $updatePath The updatePath given (if given)
671
 * @param array $update_from_version_8 The different subversions from version 1.9
672
 *
673
 * @author unknow
674
 * @author Patrick Cool <[email protected]>, Ghent University
675
 */
676
function display_requirements(
677
    $installType,
678
    $badUpdatePath,
679
    $updatePath = '',
680
    $update_from_version_8 = array()
681
) {
682
    global $_setting;
683
    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Requirements')."</h2></div>";
684
    echo '<div class="RequirementText">';
685
    echo '<strong>'.get_lang('ReadThoroughly').'</strong><br />';
686
    echo get_lang('MoreDetails').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('ReadTheInstallationGuide').'</a>.<br />'."\n";
687
688
    if ($installType == 'update') {
689
        echo get_lang('IfYouPlanToUpgradeFromOlderVersionYouMightWantToHaveAlookAtTheChangelog').'<br />';
690
    }
691
    echo '</div>';
692
693
    //  SERVER REQUIREMENTS
694
    echo '<div class="RequirementHeading"><h4>'.get_lang('ServerRequirements').'</h4>';
695
696
    $timezone = checkPhpSettingExists("date.timezone");
697
    if (!$timezone) {
698
        echo "<div class='warning-message'>".
699
            Display::return_icon('warning.png', get_lang('Warning'), '', ICON_SIZE_MEDIUM).
700
            get_lang("DateTimezoneSettingNotSet")."</div>";
701
    }
702
703
    echo '<div class="RequirementText">'.get_lang('ServerRequirementsInfo').'</div>';
704
    echo '<div class="RequirementContent">';
705
    echo '<table class="table">
706
            <tr>
707
                <td class="requirements-item">'.get_lang('PHPVersion').' >= '.REQUIRED_PHP_VERSION.'</td>
708
                <td class="requirements-value">';
709
    if (phpversion() < REQUIRED_PHP_VERSION) {
710
        echo '<strong><font color="red">'.get_lang('PHPVersionError').'</font></strong>';
711
    } else {
712
        echo '<strong><font color="green">'.get_lang('PHPVersionOK'). ' '.phpversion().'</font></strong>';
713
    }
714
    echo '</td>
715
            </tr>
716
            <tr>
717
                <td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('support').'</td>
718
                <td class="requirements-value">'.checkExtension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')).'</td>
719
            </tr>
720
            <tr>
721
                <td class="requirements-item"><a href="http://php.net/manual/en/ref.pdo-mysql.php" target="_blank">pdo_mysql</a> '.get_lang('support').'</td>
722
                <td class="requirements-value">'.checkExtension('pdo_mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')).'</td>
723
            </tr>
724
            <tr>
725
                <td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('support').'</td>
726
                <td class="requirements-value">'.checkExtension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')).'</td>
727
            </tr>
728
            <tr>
729
                <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>
730
                <td class="requirements-value">'.checkExtension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')).'</td>
731
            </tr>
732
            <tr>
733
                <td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('support').'</td>
734
                <td class="requirements-value">'.checkExtension('xml', get_lang('Yes'), get_lang('No')).'</td>
735
            </tr>
736
            <tr>
737
                <td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('support').'</td>
738
                <td class="requirements-value">'.checkExtension('intl', get_lang('Yes'), get_lang('No')).'</td>
739
            </tr>
740
               <tr>
741
                <td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('support').'</td>
742
                <td class="requirements-value">'.checkExtension('json', get_lang('Yes'), get_lang('No')).'</td>
743
            </tr>
744
             <tr>
745
                <td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('support').'</td>
746
                <td class="requirements-value">'.checkExtension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')).'</td>
747
            </tr>
748
            <tr>
749
                <td class="requirements-item"><a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>'.get_lang('support').'</td>
750
                <td class="requirements-value">'.checkExtension('curl', get_lang('Yes'), get_lang('No')).'</td>
751
            </tr>
752
753
            <tr>
754
                <td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
755
                <td class="requirements-value">'.checkExtension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true).'</td>
756
            </tr>
757
            <tr>
758
                <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>
759
                <td class="requirements-value">'.checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
760
            </tr>
761
            <tr>
762
                <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>
763
                <td class="requirements-value">'.checkExtension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true).'</td>
764
            </tr>
765
            <tr>
766
                <td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('support').' ('.get_lang('Optional').')</td>
767
                <td class="requirements-value">'.checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
768
            </tr>
769
        </table>';
770
    echo '</div>';
771
    echo '</div>';
772
773
    // RECOMMENDED SETTINGS
774
    // Note: these are the settings for Joomla, does this also apply for Chamilo?
775
    // Note: also add upload_max_filesize here so that large uploads are possible
776
    echo '<div class="RequirementHeading"><h4>'.get_lang('RecommendedSettings').'</h4>';
777
    echo '<div class="RequirementText">'.get_lang('RecommendedSettingsInfo').'</div>';
778
    echo '<div class="RequirementContent">';
779
    echo '<table class="table">
780
            <tr>
781
                <th>'.get_lang('Setting').'</th>
782
                <th>'.get_lang('Recommended').'</th>
783
                <th>'.get_lang('Actual').'</th>
784
            </tr>
785
            <tr>
786
                <td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
787
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
788
                <td class="requirements-value">'.checkPhpSetting('safe_mode', 'OFF').'</td>
789
            </tr>
790
            <tr>
791
                <td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
792
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
793
                <td class="requirements-value">'.checkPhpSetting('display_errors', 'OFF').'</td>
794
            </tr>
795
            <tr>
796
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
797
                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
798
                <td class="requirements-value">'.checkPhpSetting('file_uploads', 'ON').'</td>
799
            </tr>
800
            <tr>
801
                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
802
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
803
                <td class="requirements-value">'.checkPhpSetting('magic_quotes_gpc', 'OFF').'</td>
804
            </tr>
805
            <tr>
806
                <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
807
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
808
                <td class="requirements-value">'.checkPhpSetting('magic_quotes_runtime', 'OFF').'</td>
809
            </tr>
810
            <tr>
811
                <td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
812
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
813
                <td class="requirements-value">'.checkPhpSetting('register_globals', 'OFF').'</td>
814
            </tr>
815
            <tr>
816
                <td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
817
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
818
                <td class="requirements-value">'.checkPhpSetting('session.auto_start', 'OFF').'</td>
819
            </tr>
820
            <tr>
821
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
822
                <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
823
                <td class="requirements-value">'.checkPhpSetting('short_open_tag', 'OFF').'</td>
824
            </tr>
825
            <tr>
826
                <td class="requirements-item"><a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
827
                <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
828
                <td class="requirements-value">'.checkPhpSetting('session.cookie_httponly', 'ON').'</td>
829
            </tr>
830
            <tr>
831
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
832
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M', 'success').'</td>
833
                <td class="requirements-value">'.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'</td>
834
            </tr>
835
            <tr>
836
                <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
837
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_POST_MAX_SIZE.'M', 'success').'</td>
838
                <td class="requirements-value">'.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'</td>
839
            </tr>
840
            <tr>
841
                <td class="requirements-item"><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
842
                <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_MEMORY_LIMIT.'M', 'success').'</td>
843
                <td class="requirements-value">'.compare_setting_values(ini_get('memory_limit'), REQUIRED_MIN_MEMORY_LIMIT).'</td>
844
            </tr>
845
          </table>';
846
    echo '  </div>';
847
    echo '</div>';
848
849
    // DIRECTORY AND FILE PERMISSIONS
850
    echo '<div class="RequirementHeading"><h4>'.get_lang('DirectoryAndFilePermissions').'</h4>';
851
    echo '<div class="RequirementText">'.get_lang('DirectoryAndFilePermissionsInfo').'</div>';
852
    echo '<div class="RequirementContent">';
853
854
    $course_attempt_name = '__XxTestxX__';
855
    $course_dir = api_get_path(SYS_COURSE_PATH).$course_attempt_name;
856
857
    //Just in case
858
    @unlink($course_dir.'/test.php');
859
    @rmdir($course_dir);
860
861
    $perms_dir = array(0777, 0755, 0775, 0770, 0750, 0700);
862
    $perms_fil = array(0666, 0644, 0664, 0660, 0640, 0600);
863
864
    $course_test_was_created = false;
865
866
    $dir_perm_verified = 0777;
867
    foreach ($perms_dir as $perm) {
868
        $r = @mkdir($course_dir, $perm);
869
        if ($r === true) {
870
            $dir_perm_verified = $perm;
871
            $course_test_was_created = true;
872
            break;
873
        }
874
    }
875
876
    $fil_perm_verified = 0666;
877
    $file_course_test_was_created = false;
878
879
    if (is_dir($course_dir)) {
880
        foreach ($perms_fil as $perm) {
881
            if ($file_course_test_was_created == true) {
882
                break;
883
            }
884
            $r = @touch($course_dir.'/test.php',$perm);
885
            if ($r === true) {
886
                $fil_perm_verified = $perm;
887
                if (check_course_script_interpretation($course_dir, $course_attempt_name, 'test.php')) {
888
                    $file_course_test_was_created = true;
889
                }
890
            }
891
        }
892
    }
893
894
    @unlink($course_dir.'/test.php');
895
    @rmdir($course_dir);
896
897
    $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified;
898
    $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified;
899
900
    $dir_perm = Display::label('0'.decoct($dir_perm_verified), 'info');
901
    $file_perm = Display::label('0'.decoct($fil_perm_verified), 'info');
902
903
    $courseTestLabel = Display::label(get_lang('No'), 'important');
904
905
    if ($course_test_was_created && $file_course_test_was_created) {
906
        $courseTestLabel = Display::label(get_lang('Yes'), 'success');
907
    }
908
909
    if ($course_test_was_created && !$file_course_test_was_created) {
910
        $courseTestLabel = Display::label(
911
            sprintf(
912
                get_lang('InstallWarningCouldNotInterpretPHP'),
913
                api_get_path(WEB_COURSE_PATH).$course_attempt_name.'/test.php'
914
            ),
915
            'warning'
916
        );
917
    }
918
919
    if (!$course_test_was_created && !$file_course_test_was_created) {
920
        $courseTestLabel = Display::label(get_lang('No'), 'important');
921
    }
922
923
    $oldConf = '';
924 View Code Duplication
    if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) {
925
        $oldConf = '<tr>
926
            <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'inc/conf</td>
927
            <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').'</td>
928
        </tr>';
929
    }
930
931
    echo '<table class="table">
932
            '.$oldConf.'
933
            <tr>
934
                <td class="requirements-item">'.api_get_path(SYS_APP_PATH).'</td>
935
                <td class="requirements-value">'.check_writable(api_get_path(SYS_APP_PATH)).'</td>
936
            </tr>
937
            <tr>
938
                <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'default_course_document/images/</td>
939
                <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'default_course_document/images/').'</td>
940
            </tr>
941
            <tr>
942
                <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'lang/</td>
943
                <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'lang/', true).' <br />('.get_lang('SuggestionOnlyToEnableSubLanguageFeature').')</td>
944
            </tr>
945
            <tr>
946
                <td class="requirements-item">'.api_get_path(SYS_PATH).'vendor/</td>
947
                <td class="requirements-value">'.checkReadable(api_get_path(SYS_PATH).'vendor').'</td>
948
            </tr>
949
            <tr>
950
                <td class="requirements-item">'.api_get_path(SYS_PUBLIC_PATH).'</td>
951
                <td class="requirements-value">'.check_writable(api_get_path(SYS_PUBLIC_PATH)).'</td>
952
            </tr>
953
            <tr>
954
                <td class="requirements-item">'.get_lang('CourseTestWasCreated').'</td>
955
                <td class="requirements-value">'.$courseTestLabel.' </td>
956
            </tr>
957
            <tr>
958
                <td class="requirements-item">'.get_lang('PermissionsForNewDirs').'</td>
959
                <td class="requirements-value">'.$dir_perm.' </td>
960
            </tr>
961
            <tr>
962
                <td class="requirements-item">'.get_lang('PermissionsForNewFiles').'</td>
963
                <td class="requirements-value">'.$file_perm.' </td>
964
            </tr>
965
            ';
966
    echo '    </table>';
967
    echo '  </div>';
968
    echo '</div>';
969
970
    if ($installType == 'update' && (empty($updatePath) || $badUpdatePath)) {
971
        if ($badUpdatePath) { ?>
972
            <div class="alert alert-warning">
973
                <?php echo get_lang('Error'); ?>!<br />
974
                Chamilo <?php echo implode('|', $update_from_version_8).' '.get_lang('HasNotBeenFoundInThatDir'); ?>.
975
            </div>
976
        <?php }
977
        else {
978
            echo '<br />';
979
        }
980
        ?>
981
            <div class="row">
982
                <div class="col-md-12">
983
                    <p><?php echo get_lang('OldVersionRootPath'); ?>:
984
                        <input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath)) ? htmlentities($updatePath) : api_get_path(SYS_SERVER_ROOT_PATH).'old_version/'; ?>" />
985
                    </p>
986
                    <p>
987
                        <button type="submit" class="btn btn-default" name="step1" value="<?php echo get_lang('Back'); ?>" >
988
                            <em class="fa fa-backward"> <?php echo get_lang('Back'); ?></em>
989
                        </button>
990
                        <input type="hidden" name="is_executable" id="is_executable" value="-" />
991
                        <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;" >
992
                            <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
993
                        </button>
994
                    </p>
995
                </div>
996
            </div>
997
998
        <?php
999
    } else {
1000
        $error = false;
1001
        // First, attempt to set writing permissions if we don't have them yet
1002
        $perm = api_get_permissions_for_new_directories();
1003
        $perm_file = api_get_permissions_for_new_files();
1004
1005
        $notWritable = array();
1006
1007
        $checked_writable = api_get_path(SYS_APP_PATH);
1008
        if (!is_writable($checked_writable)) {
1009
            $notWritable[] = $checked_writable;
1010
            @chmod($checked_writable, $perm);
1011
        }
1012
1013
        $checked_writable = api_get_path(SYS_PUBLIC_PATH);
1014
        if (!is_writable($checked_writable)) {
1015
            $notWritable[] = $checked_writable;
1016
            @chmod($checked_writable, $perm);
1017
        }
1018
1019
        $checked_writable = api_get_path(SYS_CODE_PATH).'default_course_document/images/';
1020
        if (!is_writable($checked_writable)) {
1021
            $notWritable[] = $checked_writable;
1022
            @chmod($checked_writable, $perm);
1023
        }
1024
1025
        if ($course_test_was_created == false) {
1026
            $error = true;
1027
        }
1028
1029
        $checked_writable = api_get_path(CONFIGURATION_PATH).'configuration.php';
1030
        if (file_exists($checked_writable) && !is_writable($checked_writable)) {
1031
            $notWritable[] = $checked_writable;
1032
            @chmod($checked_writable, $perm_file);
1033
        }
1034
1035
        // Second, if this fails, report an error
1036
1037
        //--> The user would have to adjust the permissions manually
1038
        if (count($notWritable) > 0) {
1039
            $error = true;
1040
            echo '<div class="error-message">';
1041
                echo '<center><h3>'.get_lang('Warning').'</h3></center>';
1042
                printf(get_lang('NoWritePermissionPleaseReadInstallGuide'), '</font>
1043
                <a href="../../documentation/installation_guide.html" target="blank">', '</a> <font color="red">');
1044
            echo '</div>';
1045
            echo '<ul>';
1046
            foreach ($notWritable as $value) {
1047
                echo '<li>'.$value.'</li>';
1048
            }
1049
            echo '</ul>';
1050
        } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
1051
            // Check wether a Chamilo configuration file already exists.
1052
            echo '<div class="alert alert-warning"><h4><center>';
1053
            echo get_lang('WarningExistingLMSInstallationDetected');
1054
            echo '</center></h4></div>';
1055
        }
1056
1057
        // And now display the choice buttons (go back or install)
1058
        ?>
1059
        <p align="center" style="padding-top:15px">
1060
        <button type="submit" name="step1" class="btn btn-default" onclick="javascript: window.location='index.php'; return false;" value="<?php echo get_lang('Previous'); ?>" >
1061
            <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1062
        </button>
1063
        <button type="submit" name="step2_install" class="btn btn-success" value="<?php echo get_lang("NewInstallation"); ?>" <?php if ($error) echo 'disabled="disabled"'; ?> >
1064
            <em class="fa fa-forward"> </em> <?php echo get_lang('NewInstallation'); ?>
1065
        </button>
1066
        <input type="hidden" name="is_executable" id="is_executable" value="-" />
1067
        <?php
1068
        // Real code
1069
        echo '<button type="submit" class="btn btn-default" name="step2_update_8" value="Upgrade from Chamilo 1.9.x"';
1070
        if ($error) echo ' disabled="disabled"';
1071
        echo ' ><em class="fa fa-forward"> </em> '.get_lang('UpgradeFromLMS19x').'</button>';
1072
1073
        echo '</p>';
1074
    }
1075
}
1076
1077
/**
1078
 * Displays the license (GNU GPL) as step 2, with
1079
 * - an "I accept" button named step3 to proceed to step 3;
1080
 * - a "Back" button named step1 to go back to the first step.
1081
 */
1082
1083
function display_license_agreement()
1084
{
1085
    echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Licence').'</h2>';
1086
    echo '<p>'.get_lang('LMSLicenseInfo').'</p>';
1087
    echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('PrintVers').'</a></p>';
1088
    echo '</div>';
1089
    ?>
1090
    <div class="row">
1091
        <div class="col-md-12">
1092
            <pre style="overflow: auto; height: 200px; margin-top: 5px;">
1093
                <?php echo api_htmlentities(@file_get_contents(api_get_path(SYS_PATH).'documentation/license.txt')); ?>
1094
            </pre>
1095
            <div class="checkbox">
1096
                <label>
1097
                    <input type="checkbox" name="accept" id="accept_licence" value="1" />
1098
                    <?php echo get_lang('IAccept'); ?>
1099
                </label>
1100
            </div>
1101
            <button type="submit" class="btn btn-default" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" >
1102
                <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1103
            </button>
1104
            <input type="hidden" name="is_executable" id="is_executable" value="-" />
1105
            <button type="submit" class="btn btn-success" name="step3" onclick="javascript: if(!document.getElementById('accept_licence').checked) { alert('<?php echo get_lang('YouMustAcceptLicence')?>');return false;}" value="<?php echo get_lang('Next'); ?> &gt;" >
1106
                <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1107
            </button>
1108
1109
        </div>
1110
    </div>
1111
    <div class="row">
1112
        <div class="col-md-12">
1113
            <p class="alert alert-info"><?php echo get_lang('LMSMediaLicense'); ?></p>
1114
        </div>
1115
    </div>
1116
1117
    <!-- Contact information form -->
1118
    <div>
1119
        <a href="javascript://" class = "advanced_parameters" >
1120
        <span id="img_plus_and_minus">&nbsp;<img src="<?php echo api_get_path(WEB_IMG_PATH) ?>div_hide.gif" alt="<?php echo get_lang('Hide') ?>" title="<?php echo get_lang('Hide')?>" style ="vertical-align:middle" />&nbsp;<?php echo get_lang('ContactInformation') ?></span>
1121
        </a>
1122
    </div>
1123
1124
    <div id="id_contact_form" style="display:block">
1125
        <div class="normal-message"><?php echo get_lang('ContactInformationDescription') ?></div>
1126
        <div id="contact_registration">
1127
            <p><?php echo get_contact_registration_form() ?></p><br />
1128
        </div>
1129
    </div>
1130
    <?php
1131
}
1132
1133
1134
/**
1135
 * Get contact registration form
1136
 */
1137
function get_contact_registration_form()
1138
{
1139
1140
    $html ='
1141
   <form class="form-horizontal">
1142
    <div class="panel panel-default">
1143
    <div class="panel-body">
1144
    <div id="div_sent_information"></div>
1145
    <div class="form-group">
1146
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Name').'</label>
1147
            <div class="col-sm-9"><input id="person_name" class="form-control" type="text" name="person_name" size="30" /></div>
1148
    </div>
1149
    <div class="form-group">
1150
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Email').'</label>
1151
            <div class="col-sm-9"><input id="person_email" class="form-control" type="text" name="person_email" size="30" /></div>
1152
    </div>
1153
    <div class="form-group">
1154
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyName').'</label>
1155
            <div class="col-sm-9"><input id="company_name" class="form-control" type="text" name="company_name" size="30" /></div>
1156
    </div>
1157
    <div class="form-group">
1158
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyActivity').'</label>
1159
            <div class="col-sm-9">
1160
                    <select class="selectpicker show-tick" name="company_activity" id="company_activity" >
1161
                            <option value="">--- '.get_lang('SelectOne').' ---</option>
1162
                            <Option value="Advertising/Marketing/PR">Advertising/Marketing/PR</Option><Option value="Agriculture/Forestry">Agriculture/Forestry</Option>
1163
                            <Option value="Architecture">Architecture</Option><Option value="Banking/Finance">Banking/Finance</Option>
1164
                            <Option value="Biotech/Pharmaceuticals">Biotech/Pharmaceuticals</Option><Option value="Business Equipment">Business Equipment</Option>
1165
                            <Option value="Business Services">Business Services</Option><Option value="Construction">Construction</Option>
1166
                            <Option value="Consulting/Research">Consulting/Research</Option><Option value="Education">Education</Option>
1167
                            <Option value="Engineering">Engineering</Option><Option value="Environmental">Environmental</Option>
1168
                            <Option value="Government">Government</Option><Option value="Healthcare">Health Care</Option>
1169
                            <Option value="Hospitality/Lodging/Travel">Hospitality/Lodging/Travel</Option><Option value="Insurance">Insurance</Option>
1170
                            <Option value="Legal">Legal</Option><Option value="Manufacturing">Manufacturing</Option>
1171
                            <Option value="Media/Entertainment">Media/Entertainment</Option><Option value="Mortgage">Mortgage</Option>
1172
                            <Option value="Non-Profit">Non-Profit</Option><Option value="Real Estate">Real Estate</Option>
1173
                            <Option value="Restaurant">Restaurant</Option><Option value="Retail">Retail</Option>
1174
                            <Option value="Shipping/Transportation">Shipping/Transportation</Option>
1175
                            <Option value="Technology">Technology</Option><Option value="Telecommunications">Telecommunications</Option>
1176
                            <Option value="Other">Other</Option>
1177
                    </select>
1178
            </div>
1179
    </div>
1180
1181
    <div class="form-group">
1182
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('PersonRole').'</label>
1183
            <div class="col-sm-9">
1184
                    <select class="selectpicker show-tick" name="person_role" id="person_role" >
1185
                            <option value="">--- '.get_lang('SelectOne').' ---</option>
1186
                            <Option value="Administration">Administration</Option><Option value="CEO/President/ Owner">CEO/President/ Owner</Option>
1187
                            <Option value="CFO">CFO</Option><Option value="CIO/CTO">CIO/CTO</Option>
1188
                            <Option value="Consultant">Consultant</Option><Option value="Customer Service">Customer Service</Option>
1189
                            <Option value="Engineer/Programmer">Engineer/Programmer</Option><Option value="Facilities/Operations">Facilities/Operations</Option>
1190
                            <Option value="Finance/ Accounting Manager">Finance/ Accounting Manager</Option><Option value="Finance/ Accounting Staff">Finance/ Accounting Staff</Option>
1191
                            <Option value="General Manager">General Manager</Option><Option value="Human Resources">Human Resources</Option>
1192
                            <Option value="IS/IT Management">IS/IT Management</Option><Option value="IS/ IT Staff">IS/ IT Staff</Option>
1193
                            <Option value="Marketing Manager">Marketing Manager</Option><Option value="Marketing Staff">Marketing Staff</Option>
1194
                            <Option value="Partner/Principal">Partner/Principal</Option><Option value="Purchasing Manager">Purchasing Manager</Option>
1195
                            <Option value="Sales/ Business Dev. Manager">Sales/ Business Dev. Manager</Option><Option value="Sales/ Business Dev.">Sales/ Business Dev.</Option>
1196
                            <Option value="Vice President/Senior Manager">Vice President/Senior Manager</Option><Option value="Other">Other</Option>
1197
                    </select>
1198
            </div>
1199
    </div>
1200
1201
    <div class="form-group">
1202
            <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyCountry').'</label>
1203
            <div class="col-sm-9">'.get_countries_list_from_array(true).'</div>
1204
    </div>
1205
    <div class="form-group">
1206
            <label class="col-sm-3">'.get_lang('CompanyCity').'</label>
1207
            <div class="col-sm-9">
1208
                    <input type="text" class="form-control" id="company_city" name="company_city" size="30" />
1209
            </div>
1210
    </div>
1211
    <div class="form-group">
1212
            <label class="col-sm-3">'.get_lang('WhichLanguageWouldYouLikeToUseWhenContactingYou').'</label>
1213
            <div class="col-sm-9">
1214
                    <select class="selectpicker show-tick" id="language" name="language">
1215
                            <option value="bulgarian">Bulgarian</option>
1216
                            <option value="indonesian">Bahasa Indonesia</option>
1217
                            <option value="bosnian">Bosanski</option>
1218
                            <option value="german">Deutsch</option>
1219
                            <option selected="selected" value="english">English</option>
1220
                            <option value="spanish">Spanish</option>
1221
                            <option value="french">Français</option>
1222
                            <option value="italian">Italian</option>
1223
                            <option value="hungarian">Magyar</option>
1224
                            <option value="dutch">Nederlands</option>
1225
                            <option value="brazilian">Português do Brasil</option>
1226
                            <option value="portuguese">Português europeu</option>
1227
                            <option value="slovenian">Slovenčina</option>
1228
                    </select>
1229
            </div>
1230
    </div>
1231
1232
    <div class="form-group">
1233
            <label class="col-sm-3">'.get_lang('HaveYouThePowerToTakeFinancialDecisions').'</label>
1234
            <div class="col-sm-9">
1235
                <div class="radio">
1236
                    <label>
1237
                        <input type="radio" name="financial_decision" id="financial_decision1" value="1" checked /> ' . get_lang('Yes') . '
1238
                    </label>
1239
                </div>
1240
                <div class="radio">
1241
                    <label>
1242
                        <input type="radio" name="financial_decision" id="financial_decision2" value="0" /> '.get_lang('No').'
1243
                    </label>
1244
                </div>
1245
            </div>
1246
    </div>
1247
    <div class="clear"></div>
1248
    <div class="form-group">
1249
            <div class="col-sm-3">&nbsp;</div>
1250
            <div class="col-sm-9"><button type="button" class="btn btn-default" onclick="javascript:send_contact_information();" value="'.get_lang('SendInformation').'" ><em class="fa fa-floppy-o"></em> '.get_lang('SendInformation').'</button></div>
1251
    </div>
1252
    <div class="form-group">
1253
            <div class="col-sm-3">&nbsp;</div>
1254
            <div class="col-sm-9"><span class="form_required">*</span><small>'.get_lang('FieldRequired').'</small></div>
1255
    </div></div></div>
1256
</form>';
1257
1258
    return $html;
1259
}
1260
1261
/**
1262
 * Displays a parameter in a table row.
1263
 * Used by the display_database_settings_form function.
1264
 * @param   string  Type of install
1265
 * @param   string  Name of parameter
1266
 * @param   string  Field name (in the HTML form)
1267
 * @param   string  Field value
1268
 * @param   string  Extra notice (to show on the right side)
1269
 * @param   boolean Whether to display in update mode
1270
 * @param   string  Additional attribute for the <tr> element
1271
 * @return  void    Direct output
1272
 */
1273
function displayDatabaseParameter(
1274
    $installType,
1275
    $parameterName,
1276
    $formFieldName,
1277
    $parameterValue,
1278
    $extra_notice,
1279
    $displayWhenUpdate = true,
1280
    $tr_attribute = ''
1281
) {
1282
    //echo "<tr ".$tr_attribute.">";
1283
    echo "<label class='col-sm-4'>$parameterName</label>";
1284
1285
    if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
1286
        echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />'.$parameterValue;
1287
    } else {
1288
        $inputType = $formFieldName == 'dbPassForm' ? 'password' : 'text';
1289
1290
        //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on
1291
        $maxLength = $formFieldName == 'dbPrefixForm' ? '15' : MAX_FORM_FIELD_LENGTH;
1292
        if ($installType == INSTALL_TYPE_UPDATE) {
1293
            echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />';
1294
            echo api_htmlentities($parameterValue);
1295
        } else {
1296
            echo '<div class="col-sm-5"><input type="' . $inputType . '" class="form-control" size="' . DATABASE_FORM_FIELD_DISPLAY_LENGTH . '" maxlength="' . $maxLength . '" name="' . $formFieldName . '" id="' . $formFieldName . '" value="' . api_htmlentities($parameterValue) . '" />' . "</div>";
1297
            echo '<div class="col-sm-3">' . $extra_notice . '</div>';
1298
        }
1299
1300
    }
1301
1302
}
1303
1304
/**
1305
 * Displays step 3 - a form where the user can enter the installation settings
1306
 * regarding the databases - login and password, names, prefixes, single
1307
 * or multiple databases, tracking or not...
1308
 * @param string $installType
1309
 * @param string $dbHostForm
1310
 * @param string $dbUsernameForm
1311
 * @param string $dbPassForm
1312
 * @param string $dbNameForm
1313
 * @param int    $dbPortForm
1314
 * @param string $installationProfile
1315
 */
1316
function display_database_settings_form(
1317
    $installType,
1318
    $dbHostForm,
1319
    $dbUsernameForm,
1320
    $dbPassForm,
1321
    $dbNameForm,
1322
    $dbPortForm = 3306,
1323
    $installationProfile = ''
1324
) {
1325
    if ($installType == 'update') {
1326
        global $_configuration;
1327
        $dbHostForm = $_configuration['db_host'];
1328
        $dbUsernameForm = $_configuration['db_user'];
1329
        $dbPassForm = $_configuration['db_password'];
1330
        $dbNameForm = $_configuration['main_database'];
1331
        $dbPortForm = isset($_configuration['db_port']) ? $_configuration['db_port'] : '';
1332
1333
        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
1334
        echo '<div class="RequirementContent">';
1335
        echo get_lang('DBSettingUpgradeIntro');
1336
        echo '</div>';
1337
    } else {
1338
        echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
1339
        echo '<div class="RequirementContent">';
1340
        echo get_lang('DBSettingIntro');
1341
        echo '</div>';
1342
    }
1343
    ?>
1344
    <div class="panel panel-default">
1345
        <div class="panel-body">
1346
        <div class="form-group">
1347
            <label class="col-sm-4"><?php echo get_lang('DBHost'); ?> </label>
1348 View Code Duplication
            <?php if ($installType == 'update'){ ?>
1349
            <div class="col-sm-5">
1350
                <input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?>
1351
            </div>
1352
            <div class="col-sm-3"></div>
1353
            <?php }else{ ?>
1354
            <div class="col-sm-5">
1355
                <input type="text" class="form-control" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" />
1356
            </div>
1357
            <div class="col-sm-3"><?php echo get_lang('EG').' localhost'; ?></div>
1358
            <?php } ?>
1359
        </div>
1360
        <div class="form-group">
1361
            <label class="col-sm-4"><?php echo get_lang('DBPort'); ?> </label>
1362 View Code Duplication
            <?php if ($installType == 'update'){ ?>
1363
            <div class="col-sm-5">
1364
                <input type="hidden" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" /><?php echo $dbPortForm; ?>
1365
            </div>
1366
            <div class="col-sm-3"></div>
1367
            <?php }else{ ?>
1368
            <div class="col-sm-5">
1369
                <input type="text" class="form-control" size="25" maxlength="50" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" />
1370
            </div>
1371
            <div class="col-sm-3"><?php echo get_lang('EG').' 3306'; ?></div>
1372
            <?php } ?>
1373
        </div>
1374
        <div class="form-group">
1375
            <?php
1376
                //database user username
1377
                $example_login = get_lang('EG').' root';
1378
                displayDatabaseParameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
1379
            ?>
1380
        </div>
1381
        <div class="form-group">
1382
            <?php
1383
            //database user password
1384
            $example_password = get_lang('EG').' '.api_generate_password();
1385
            displayDatabaseParameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
1386
1387
            ?>
1388
        </div>
1389
        <div class="form-group">
1390
            <?php
1391
            //Database Name fix replace weird chars
1392
            if ($installType != INSTALL_TYPE_UPDATE) {
1393
                $dbNameForm = str_replace(array('-','*', '$', ' ', '.'), '', $dbNameForm);
1394
            }
1395
1396
            displayDatabaseParameter(
1397
                $installType,
1398
                get_lang('MainDB'),
1399
                'dbNameForm',
1400
                $dbNameForm,
1401
                '&nbsp;',
1402
                null,
1403
                'id="optional_param1"'
1404
                );
1405
            ?>
1406
        </div>
1407
       <?php if ($installType != INSTALL_TYPE_UPDATE) { ?>
1408
        <div class="form-group">
1409
            <div class="col-sm-3"></div>
1410
            <div class="col-sm-9">
1411
            <button type="submit" class="btn btn-primary" name="step3" value="step3">
1412
                <em class="fa fa-refresh"> </em>
1413
                <?php echo get_lang('CheckDatabaseConnection'); ?>
1414
            </button>
1415
            </div>
1416
        </div>
1417
        <?php } ?>
1418
1419
        </div>
1420
    </div>
1421
1422
        <?php
1423
1424
        $database_exists_text = '';
1425
        $manager = null;
1426
        try {
1427
            $manager = connectToDatabase(
1428
                $dbHostForm,
1429
                $dbUsernameForm,
1430
                $dbPassForm,
1431
                null,
1432
                $dbPortForm
1433
            );
1434
            $databases = $manager->getConnection()->getSchemaManager()->listDatabases();
1435
            if (in_array($dbNameForm, $databases)) {
1436
                $database_exists_text = '<div class="alert alert-warning">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>';
1437
            }
1438
        } catch (Exception $e) {
1439
            $database_exists_text = $e->getMessage();
1440
        }
1441
1442
        if ($manager->getConnection()->isConnected()): ?>
1443
1444
            <?php echo $database_exists_text ?>
1445
            <div id="db_status" class="alert alert-success">
1446
                Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br />
1447
                Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br />
1448
                Database driver: <strong><?php echo $manager->getConnection()->getDriver()->getName(); ?></strong><br />
1449
1450
            </div>
1451
1452
        <?php else: ?>
1453
1454
            <?php echo $database_exists_text ?>
1455
            <div id="db_status" style="float:left;" class="alert alert-danger">
1456
                <div style="float:left;">
1457
                    <?php echo get_lang('FailedConectionDatabase'); ?></strong>
1458
                </div>
1459
            </div>
1460
1461
        <?php endif; ?>
1462
   <div class="form-group">
1463
       <div class="col-sm-6">
1464
           <button type="submit" name="step2" class="btn btn-default pull-right" value="&lt; <?php echo get_lang('Previous'); ?>" >
1465
               <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
1466
           </button>
1467
       </div>
1468
      <div class="col-sm-6">
1469
       <input type="hidden" name="is_executable" id="is_executable" value="-" />
1470
       <?php if ($manager) { ?>
1471
           <button type="submit"  class="btn btn-success" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1472
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1473
           </button>
1474
       <?php } else { ?>
1475
           <button disabled="disabled" type="submit" class="btn btn-success disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
1476
               <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
1477
           </button>
1478
       <?php } ?>
1479
      </div>
1480
   </div>
1481
1482
    <?php
1483
}
1484
function panel($content = null, $title = null, $id = null, $style = null) {
1485
    $html = '';
1486
    if (empty($style)) {
1487
        $style = 'default';
1488
    }
1489
    if (!empty($title)) {
1490
        $panelTitle = Display::div($title, array('class' => 'panel-heading'));
1491
        $panelBody = Display::div($content, array('class' => 'panel-body'));
1492
        $panelParent = Display::div($panelTitle . $panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
1493
    } else {
1494
        $panelBody = Display::div($html, array('class' => 'panel-body'));
1495
        $panelParent = Display::div($panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
1496
    }
1497
    $html .= $panelParent;
1498
    return $html;
1499
}
1500
/**
1501
 * Displays a parameter in a table row.
1502
 * Used by the display_configuration_settings_form function.
1503
 * @param string $installType
1504
 * @param string $parameterName
1505
 * @param string $formFieldName
1506
 * @param string $parameterValue
1507
 * @param string $displayWhenUpdate
1508
 */
1509
function display_configuration_parameter(
1510
    $installType,
1511
    $parameterName,
1512
    $formFieldName,
1513
    $parameterValue,
1514
    $displayWhenUpdate = 'true'
1515
) {
1516
    $html = '<div class="form-group">';
1517
    $html .= '<label class="col-sm-6 control-label">' . $parameterName . '</label>';
1518
    if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
1519
        $html .= '<input type="hidden" name="' . $formFieldName . '" value="'. api_htmlentities($parameterValue, ENT_QUOTES). '" />' . $parameterValue;
1520
    } else {
1521
        $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>";
1522
    }
1523
    $html .= "</div>";
1524
    return $html;
1525
}
1526
1527
/**
1528
 * Displays step 4 of the installation - configuration settings about Chamilo itself.
1529
 * @param string $installType
1530
 * @param string $urlForm
1531
 * @param string $languageForm
1532
 * @param string $emailForm
1533
 * @param string $adminFirstName
1534
 * @param string $adminLastName
1535
 * @param string $adminPhoneForm
1536
 * @param string $campusForm
1537
 * @param string $institutionForm
1538
 * @param string $institutionUrlForm
1539
 * @param string $encryptPassForm
1540
 * @param bool $allowSelfReg
1541
 * @param bool $allowSelfRegProf
1542
 * @param string $loginForm
1543
 * @param string $passForm
1544
 */
1545
function display_configuration_settings_form(
1546
    $installType,
1547
    $urlForm,
1548
    $languageForm,
1549
    $emailForm,
1550
    $adminFirstName,
1551
    $adminLastName,
1552
    $adminPhoneForm,
1553
    $campusForm,
1554
    $institutionForm,
1555
    $institutionUrlForm,
1556
    $encryptPassForm,
1557
    $allowSelfReg,
1558
    $allowSelfRegProf,
1559
    $loginForm,
1560
    $passForm
1561
) {
1562
    if ($installType != 'update' && empty($languageForm)) {
1563
        $languageForm = $_SESSION['install_language'];
1564
    }
1565
    echo '<div class="RequirementHeading">';
1566
    echo "<h2>" . display_step_sequence() . get_lang("CfgSetting") . "</h2>";
1567
    echo '</div>';
1568
1569
    echo '<p>'.get_lang('ConfigSettingsInfo').' <strong>app/config/configuration.php</strong></p>';
1570
1571
    // Parameter 1: administrator's login
1572
1573
    $html = '';
1574
1575
    $html .= display_configuration_parameter($installType, get_lang('AdminLogin'), 'loginForm', $loginForm, $installType == 'update');
1576
1577
    // Parameter 2: administrator's password
1578
    if ($installType != 'update') {
1579
        $html .= display_configuration_parameter($installType, get_lang('AdminPass'), 'passForm', $passForm, false);
1580
    }
1581
1582
    // Parameters 3 and 4: administrator's names
1583
1584
    $html .=  display_configuration_parameter($installType, get_lang('AdminFirstName'), 'adminFirstName', $adminFirstName);
1585
    $html .=  display_configuration_parameter($installType, get_lang('AdminLastName'), 'adminLastName', $adminLastName);
1586
1587
    //Parameter 3: administrator's email
1588
    $html .=  display_configuration_parameter($installType, get_lang('AdminEmail'), 'emailForm', $emailForm);
1589
1590
    //Parameter 6: administrator's telephone
1591
    $html .=  display_configuration_parameter($installType, get_lang('AdminPhone'), 'adminPhoneForm', $adminPhoneForm);
1592
1593
1594
    echo panel($html, get_lang('Administrator'), 'administrator');
1595
1596
1597
    //echo '<table class="table">';
1598
1599
    //First parameter: language
1600
    $html = '<div class="form-group">';
1601
    $html .= '<label class="col-sm-6 control-label">'.get_lang('MainLang')."</label>";
1602
    if ($installType == 'update') {
1603
        $html .= '<input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES).'" />'.$languageForm;
1604
1605
    } else { // new installation
1606
        $html .= '<div class="col-sm-6">';
1607
        $html .= display_language_selection_box('languageForm', $languageForm);
1608
        $html .= '</div>';
1609
    }
1610
    $html.= "</div>";
1611
1612
1613
    //Second parameter: Chamilo URL
1614
    $html .= '<div class="form-group">';
1615
    $html .= '<label class="col-sm-6 control-label">'.get_lang('ChamiloURL') .get_lang('ThisFieldIsRequired').'</label>';
1616
1617
1618
1619
    if ($installType == 'update') {
1620
        $html .= api_htmlentities($urlForm, ENT_QUOTES)."\n";
1621
    } else {
1622
        $html .= '<div class="col-sm-6">';
1623
        $html .= '<input class="form-control" type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES).'" />';
1624
        $html .= '</div>';
1625
    }
1626
    $html .= '</div>';
1627
1628
    //Parameter 9: campus name
1629
    $html .= display_configuration_parameter($installType, get_lang('CampusName'), 'campusForm', $campusForm);
1630
1631
    //Parameter 10: institute (short) name
1632
    $html .= display_configuration_parameter($installType, get_lang('InstituteShortName'), 'institutionForm', $institutionForm);
1633
1634
    //Parameter 11: institute (short) name
1635
    $html .= display_configuration_parameter($installType, get_lang('InstituteURL'), 'institutionUrlForm', $institutionUrlForm);
1636
1637
1638
    $html .= '<div class="form-group">
1639
            <label class="col-sm-6 control-label">' . get_lang("EncryptMethodUserPass") . '</label>
1640
        <div class="col-sm-6">';
1641
    if ($installType == 'update') {
1642
        $html .= '<input type="hidden" name="encryptPassForm" value="'. $encryptPassForm .'" />'. $encryptPassForm;
1643
    } else {
1644
1645
        $html .= '<div class="checkbox">
1646
                    <label>
1647
                        <input  type="radio" name="encryptPassForm" value="bcrypt" id="encryptPass1" '. ($encryptPassForm == 'bcrypt' ? 'checked="checked" ':'') .'/> bcrypt
1648
                    </label>';
1649
1650
        $html .= '<label>
1651
                        <input  type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" '. ($encryptPassForm == 'sha1' ? 'checked="checked" ':'') .'/> sha1
1652
                    </label>';
1653
1654
        $html .= '<label>
1655
                        <input type="radio" name="encryptPassForm" value="md5" id="encryptPass0" '. ($encryptPassForm == 'md5' ? 'checked="checked" ':'') .'/> md5
1656
                    </label>';
1657
1658
        $html .= '<label>
1659
                        <input type="radio" name="encryptPassForm" value="none" id="encryptPass2" '. ($encryptPassForm == 'none' ? 'checked="checked" ':'') .'/>'. get_lang('None').'
1660
                    </label>';
1661
        $html .= '</div>';
1662
    }
1663
    $html .= '</div></div>';
1664
1665
    $html .= '<div class="form-group">
1666
            <label class="col-sm-6 control-label">' . get_lang('AllowSelfReg') . '</label>
1667
            <div class="col-sm-6">';
1668
    if ($installType == 'update') {
1669
        if ($allowSelfReg == 'true') {
1670
            $label = get_lang('Yes');
1671
        } elseif ($allowSelfReg == 'false') {
1672
            $label = get_lang('No');
1673
        } else {
1674
            $label = get_lang('AfterApproval');
1675
        }
1676
        $html .= '<input type="hidden" name="allowSelfReg" value="'. $allowSelfReg .'" />'. $label;
1677
    } else {
1678
        $html .= '<div class="control-group">';
1679
        $html .= '<label class="checkbox-inline">
1680
                        <input type="radio" name="allowSelfReg" value="1" id="allowSelfReg1" '. ($allowSelfReg == 'true' ? 'checked="checked" ' : '') . ' /> '. get_lang('Yes') .'
1681
                    </label>';
1682
        $html .= '<label class="checkbox-inline">
1683
                        <input type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" '. ($allowSelfReg == 'false' ? '' : 'checked="checked" ') .' /> '. get_lang('No') .'
1684
                    </label>';
1685
         $html .= '<label class="checkbox-inline">
1686
                    <input type="radio" name="allowSelfReg" value="0" id="allowSelfReg0" '. ($allowSelfReg == 'approval' ? '' : 'checked="checked" ') .' /> '. get_lang('AfterApproval') .'
1687
                </label>';
1688
        $html .= '</div>';
1689
    }
1690
    $html .= '</div>';
1691
    $html .= '</div>';
1692
1693
    $html .= '<div class="form-group">';
1694
    $html .= '<label class="col-sm-6 control-label">'. get_lang('AllowSelfRegProf') .'</label>
1695
        <div class="col-sm-6">';
1696
    if ($installType == 'update') {
1697
        if ($allowSelfRegProf == 'true') {
1698
            $label = get_lang('Yes');
1699
        } else {
1700
            $label = get_lang('No');
1701
        }
1702
        $html .= '<input type="hidden" name="allowSelfRegProf" value="'. $allowSelfRegProf.'" />'. $label;
1703
    } else {
1704
        $html .= '<div class="control-group">
1705
                <label class="checkbox-inline">
1706
                    <input type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" '. ($allowSelfRegProf ? 'checked="checked" ' : '') .'/>
1707
                ' . get_lang('Yes') .'
1708
                </label>';
1709
        $html .= '<label class="checkbox-inline">
1710
                    <input type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" '. ($allowSelfRegProf ? '' : 'checked="checked" ') .' />
1711
                   '. get_lang('No') .'
1712
                </label>';
1713
        $html .= '</div>';
1714
    }
1715
    $html .= '</div>
1716
    </div>';
1717
1718
    echo panel($html, get_lang('Platform'), 'platform');
1719
 ?>
1720
    <div class='form-group'>
1721
        <div class="col-sm-6">
1722
            <button type="submit" class="btn btn-default pull-right" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" ><em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?></button>
1723
            <input type="hidden" name="is_executable" id="is_executable" value="-" />
1724
        </div>
1725
        <div class="col-sm-6">
1726
            <button class="btn btn-success" type="submit" name="step5" value="<?php echo get_lang('Next'); ?> &gt;" ><em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?></button>
1727
        </div>
1728
    </div>
1729
1730
    <?php
1731
}
1732
1733
/**
1734
 * After installation is completed (step 6), this message is displayed.
1735
 * @param string $installType
1736
 */
1737
function display_after_install_message($installType)
1738
{
1739
    echo '<div class="RequirementContent">'.get_lang('FirstUseTip').'</div>';
1740
    echo '<div class="alert alert-warning">';
1741
    echo '<strong>'.get_lang('SecurityAdvice').'</strong>';
1742
    echo ': ';
1743
    printf(get_lang('ToProtectYourSiteMakeXReadOnlyAndDeleteY'), 'app/config/', 'main/install/');
1744
    echo '</div>';
1745
    ?></form>
1746
    <br />
1747
    <a class="btn btn-success btn-large btn-install" href="../../index.php">
1748
        <?php echo get_lang('GoToYourNewlyCreatedPortal'); ?>
1749
    </a>
1750
    <?php
1751
}
1752
1753
/**
1754
 * This function return countries list from array (hardcoded)
1755
 * @param   bool  $combo  (Optional) True for returning countries list with select html
1756
 * @return  array|string countries list
1757
 */
1758
function get_countries_list_from_array($combo = false)
1759
{
1760
    $a_countries = array(
1761
        "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
1762
        "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
1763
        "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",
1764
        "Denmark", "Djibouti", "Dominica", "Dominican Republic",
1765
        "East Timor (Timor Timur)", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
1766
        "Fiji", "Finland", "France",
1767
        "Gabon", "Gambia, The", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana",
1768
        "Haiti", "Honduras", "Hungary",
1769
        "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy",
1770
        "Jamaica", "Japan", "Jordan",
1771
        "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan",
1772
        "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
1773
        "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Morocco", "Mozambique", "Myanmar",
1774
        "Namibia", "Nauru", "Nepa", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway",
1775
        "Oman",
1776
        "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland","Portugal",
1777
        "Qatar",
1778
        "Romania", "Russia", "Rwanda",
1779
        "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",
1780
        "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu",
1781
        "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan",
1782
        "Vanuatu", "Vatican City", "Venezuela", "Vietnam",
1783
        "Yemen",
1784
        "Zambia", "Zimbabwe"
1785
    );
1786
1787
    $country_select = '';
1788
    if ($combo) {
1789
        $country_select = '<select class="selectpicker show-tick" id="country" name="country">';
1790
        $country_select .= '<option value="">--- '.get_lang('SelectOne').' ---</option>';
1791
        foreach ($a_countries as $country) {
1792
            $country_select .= '<option value="'.$country.'">'.$country.'</option>';
1793
        }
1794
        $country_select .= '</select>';
1795
        return $country_select;
1796
    }
1797
1798
    return $a_countries;
1799
}
1800
1801
/**
1802
 * Lock settings that can't be changed in other portals
1803
 */
1804
function lockSettings()
1805
{
1806
    $access_url_locked_settings = api_get_locked_settings();
1807
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1808
    foreach ($access_url_locked_settings as $setting) {
1809
        $sql = "UPDATE $table SET access_url_locked = 1 WHERE variable  = '$setting'";
1810
        Database::query($sql);
1811
    }
1812
}
1813
1814
/**
1815
 * Update dir values
1816
 */
1817
function updateDirAndFilesPermissions()
1818
{
1819
    $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1820
    $permissions_for_new_directories = isset($_SESSION['permissions_for_new_directories']) ? $_SESSION['permissions_for_new_directories'] : 0770;
1821
    $permissions_for_new_files = isset($_SESSION['permissions_for_new_files']) ? $_SESSION['permissions_for_new_files'] : 0660;
1822
    // use decoct() to store as string
1823
    $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_directories) . "'
1824
              WHERE variable  = 'permissions_for_new_directories'";
1825
    Database::query($sql);
1826
1827
    $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_files) . "' WHERE variable  = 'permissions_for_new_files'";
1828
    Database::query($sql);
1829
1830
    if (isset($_SESSION['permissions_for_new_directories'])) {
1831
        unset($_SESSION['permissions_for_new_directories']);
1832
    }
1833
1834
    if (isset($_SESSION['permissions_for_new_files'])) {
1835
        unset($_SESSION['permissions_for_new_files']);
1836
    }
1837
}
1838
1839
/**
1840
 * @param $current_value
1841
 * @param $wanted_value
1842
 * @return string
1843
 */
1844
function compare_setting_values($current_value, $wanted_value)
1845
{
1846
    $current_value_string = $current_value;
1847
    $current_value = (float)$current_value;
1848
    $wanted_value = (float)$wanted_value;
1849
1850
    if ($current_value >= $wanted_value) {
1851
        return Display::label($current_value_string, 'success');
1852
    } else {
1853
        return Display::label($current_value_string, 'important');
1854
    }
1855
}
1856
1857
/**
1858
 * @param $course_dir
1859
 * @param $course_attempt_name
1860
 * @param string $file
1861
 * @return bool
1862
 */
1863
function check_course_script_interpretation($course_dir, $course_attempt_name, $file = 'test.php')
1864
{
1865
    $output = false;
1866
    //Write in file
1867
    $file_name = $course_dir.'/'.$file;
1868
    $content = '<?php echo "123"; exit;';
1869
1870
    if (is_writable($file_name)) {
1871
        if ($handler = @fopen($file_name, "w")) {
1872
            //write content
1873
            if (fwrite($handler, $content)) {
1874
                $sock_errno = '';
1875
                $sock_errmsg = '';
1876
                $url = api_get_path(WEB_PATH).'app/courses/'.$course_attempt_name.'/'.$file;
1877
1878
                $parsed_url = parse_url($url);
1879
                //$scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] : ''; //http
1880
                $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1881
                // Patch if the host is the default host and is used through
1882
                // the IP address (sometimes the host is not taken correctly
1883
                // in this case)
1884
                if (empty($host) && !empty($_SERVER['HTTP_HOST'])) {
1885
                    $host = $_SERVER['HTTP_HOST'];
1886
                    $url = preg_replace('#:///#', '://'.$host.'/', $url);
1887
                }
1888
                $path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
1889
                $port = isset($parsed_url['port']) ? $parsed_url['port'] : '80';
1890
1891
                //Check fsockopen (doesn't work with https)
1892
                if ($fp = @fsockopen(str_replace('http://', '', $url), -1, $sock_errno, $sock_errmsg, 60)) {
1893
                    $out  = "GET $path HTTP/1.1\r\n";
1894
                    $out .= "Host: $host\r\n";
1895
                    $out .= "Connection: Close\r\n\r\n";
1896
1897
                    fwrite($fp, $out);
1898
                    while (!feof($fp)) {
1899
                        $result = str_replace("\r\n", '',fgets($fp, 128));
1900
                        if (!empty($result) && $result == '123') {
1901
                            $output = true;
1902
                        }
1903
                    }
1904
                    fclose($fp);
1905
                    //Check allow_url_fopen
1906
                } elseif (ini_get('allow_url_fopen')) {
1907
                    if ($fp = @fopen($url, 'r')) {
1908
                        while ($result = fgets($fp, 1024)) {
1909
                            if (!empty($result) && $result == '123') {
1910
                                $output = true;
1911
                            }
1912
                        }
1913
                        fclose($fp);
1914
                    }
1915
                    // Check if has support for cURL
1916
                } elseif (function_exists('curl_init')) {
1917
                    $ch = curl_init();
1918
                    curl_setopt($ch, CURLOPT_HEADER, 0);
1919
                    curl_setopt($ch, CURLOPT_URL, $url);
1920
                    //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1921
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1922
                    $result = curl_exec ($ch);
1923
                    if (!empty($result) && $result == '123') {
1924
                        $output = true;
1925
                    }
1926
                    curl_close($ch);
1927
                }
1928
            }
1929
            @fclose($handler);
1930
        }
1931
    }
1932
1933
    return $output;
1934
}
1935
1936
/**
1937
 * Save settings values
1938
 *
1939
 * @param string $organizationName
1940
 * @param string $organizationUrl
1941
 * @param string $siteName
1942
 * @param string $adminEmail
1943
 * @param string $adminLastName
1944
 * @param string $adminFirstName
1945
 * @param string $language
1946
 * @param string $allowRegistration
1947
 * @param string $allowTeacherSelfRegistration
1948
 * @param string $installationProfile The name of an installation profile file in main/install/profiles/
1949
 */
1950
function installSettings(
1951
    $organizationName,
1952
    $organizationUrl,
1953
    $siteName,
1954
    $adminEmail,
1955
    $adminLastName,
1956
    $adminFirstName,
1957
    $language,
1958
    $allowRegistration,
1959
    $allowTeacherSelfRegistration,
1960
    $installationProfile = ''
1961
) {
1962
    $allowRegistration = $allowRegistration ? 'true' : 'false';
1963
    $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false';
1964
1965
    // Use PHP 5.3 to avoid issue with weird peripherical auto-installers like travis-ci
1966
    $settings = array(
1967
        'Institution' => $organizationName,
1968
        'InstitutionUrl' => $organizationUrl,
1969
        'siteName' => $siteName,
1970
        'emailAdministrator' => $adminEmail,
1971
        'administratorSurname' => $adminLastName,
1972
        'administratorName' => $adminFirstName,
1973
        'platformLanguage' => $language,
1974
        'allow_registration' => $allowRegistration,
1975
        'allow_registration_as_teacher' => $allowTeacherSelfRegistration,
1976
    );
1977
1978
    foreach ($settings as $variable => $value) {
1979
        $sql = "UPDATE settings_current
1980
                SET selected_value = '$value'
1981
                WHERE variable = '$variable'";
1982
        Database::query($sql);
1983
    }
1984
    installProfileSettings($installationProfile);
1985
}
1986
1987
/**
1988
 * Executes DB changes based in the classes defined in
1989
 * src/Chamilo/CoreBundle/Migrations/Schema/*
1990
 *
1991
 * @param string $chamiloVersion
1992
 * @param EntityManager $manager
1993
 * @throws \Doctrine\DBAL\DBALException
1994
 */
1995
function migrate($chamiloVersion, EntityManager $manager)
1996
{
1997
    $debug = true;
1998
    $connection = $manager->getConnection();
1999
2000
    $config = new \Doctrine\DBAL\Migrations\Configuration\Configuration($connection);
2001
2002
    // Table name that will store migrations log (will be created automatically,
2003
    // default name is: doctrine_migration_versions)
2004
    $config->setMigrationsTableName('version');
2005
    // Namespace of your migration classes, do not forget escape slashes, do not add last slash
2006
    $config->setMigrationsNamespace('Application\Migrations\Schema\V'.$chamiloVersion);
2007
    // Directory where your migrations are located
2008
    $config->setMigrationsDirectory(api_get_path(SYS_PATH).'app/Migrations/Schema/V'.$chamiloVersion);
2009
    // Load your migrations
2010
    $config->registerMigrationsFromDirectory($config->getMigrationsDirectory());
2011
2012
    $migration = new \Doctrine\DBAL\Migrations\Migration($config);
2013
    $versions = $config->getMigrations();
2014
2015
    /** @var Doctrine\DBAL\Migrations\Version $migrationItem */
2016
    foreach ($versions as $version) {
2017
        $version->getMigration()->setEntityManager($manager);
2018
    }
2019
2020
    $to = null; // if $to == null then schema will be migrated to latest version
2021
2022
    echo "<pre>";
2023
2024
    try {
2025
        // Execute migration!
2026
        $migratedSQL = $migration->migrate($to);
2027
2028
        if ($debug) {
2029
            foreach ($migratedSQL as $version => $sqlList) {
2030
                echo "VERSION: $version<br>";
2031
                echo "----------------------------------------------<br>";
2032
2033
                foreach ($sqlList as $sql) {
2034
                    echo "<code>$sql</code><br>";
2035
                }
2036
            }
2037
2038
            echo "<br>DONE!<br>";
2039
        }
2040
2041
        return true;
2042
    } catch (Exception $ex) {
2043
        if ($debug) {
2044
            echo "ERROR: {$ex->getMessage()}<br>";
2045
            return false;
2046
        }
2047
    }
2048
2049
    echo "</pre>";
2050
2051
    return false;
2052
}
2053
2054
/**
2055
* @param EntityManager $em
2056
 *
2057
* @throws \Doctrine\DBAL\DBALException
2058
 */
2059
function fixIds(EntityManager $em)
2060
{
2061
    $debug = true;
2062
    $connection = $em->getConnection();
2063
2064
    if ($debug) {
2065
        error_log('fixIds');
2066
    }
2067
2068
    // Create temporary indexes to increase speed of the following operations
2069
    // Adding and removing indexes will usually take much less time than
2070
    // the execution without indexes of the queries in this function, particularly
2071
    // for large tables
2072
    $sql = "ALTER TABLE c_document ADD INDEX tmpidx_doc(c_id, id)";
2073
    $connection->executeQuery($sql);
2074
    $sql = "ALTER TABLE c_student_publication ADD INDEX tmpidx_stud (c_id, id)";
2075
    $connection->executeQuery($sql);
2076
    $sql = "ALTER TABLE c_quiz ADD INDEX tmpidx_quiz (c_id, id)";
2077
    $connection->executeQuery($sql);
2078
    $sql = "ALTER TABLE c_item_property ADD INDEX tmpidx_ip (to_group_id)";
2079
    $connection->executeQuery($sql);
2080
2081
    $sql = "SELECT * FROM c_lp_item";
2082
    $result = $connection->fetchAll($sql);
2083
    foreach ($result as $item) {
2084
        $courseId = $item['c_id'];
2085
        $iid = isset($item['iid']) ? intval($item['iid']) : 0;
2086
        $ref = isset($item['ref']) ? intval($item['ref']) : 0;
2087
        $sql = null;
2088
2089
        $newId = '';
2090
2091
        switch ($item['item_type']) {
2092 View Code Duplication
            case TOOL_LINK:
2093
                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref";
2094
                $data = $connection->fetchAssoc($sql);
2095
                if ($data) {
2096
                    $newId = $data['iid'];
2097
                }
2098
                break;
2099 View Code Duplication
            case TOOL_STUDENTPUBLICATION:
2100
                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2101
                $data = $connection->fetchAssoc($sql);
2102
                if ($data) {
2103
                    $newId = $data['iid'];
2104
                }
2105
                break;
2106 View Code Duplication
            case TOOL_QUIZ:
2107
                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2108
                $data = $connection->fetchAssoc($sql);
2109
                if ($data) {
2110
                    $newId = $data['iid'];
2111
                }
2112
                break;
2113 View Code Duplication
            case TOOL_DOCUMENT:
2114
                $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2115
                $data = $connection->fetchAssoc($sql);
2116
                if ($data) {
2117
                    $newId = $data['iid'];
2118
                }
2119
                break;
2120 View Code Duplication
            case TOOL_FORUM:
2121
                $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND forum_id = $ref";
2122
                $data = $connection->fetchAssoc($sql);
2123
                if ($data) {
2124
                    $newId = $data['iid'];
2125
                }
2126
                break;
2127 View Code Duplication
            case 'thread':
2128
                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
2129
                $data = $connection->fetchAssoc($sql);
2130
                if ($data) {
2131
                    $newId = $data['iid'];
2132
                }
2133
                break;
2134
        }
2135
2136
        if (!empty($sql) && !empty($newId) && !empty($iid)) {
2137
            $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid";
2138
2139
            $connection->executeQuery($sql);
2140
        }
2141
    }
2142
2143
    // Set NULL if session = 0
2144
    $sql = "UPDATE c_item_property SET session_id = NULL WHERE session_id = 0";
2145
    $connection->executeQuery($sql);
2146
2147
    // Set NULL if group = 0
2148
    $sql = "UPDATE c_item_property SET to_group_id = NULL WHERE to_group_id = 0";
2149
    $connection->executeQuery($sql);
2150
2151
    // Set NULL if insert_user_id = 0
2152
    $sql = "UPDATE c_item_property SET insert_user_id = NULL WHERE insert_user_id = 0";
2153
    $connection->executeQuery($sql);
2154
2155
    // Delete session data of sessions that don't exist.
2156
    $sql = "DELETE FROM c_item_property
2157
            WHERE session_id IS NOT NULL AND session_id NOT IN (SELECT id FROM session)";
2158
    $connection->executeQuery($sql);
2159
2160
    // Delete group data of groups that don't exist.
2161
    $sql = "DELETE FROM c_item_property
2162
            WHERE to_group_id IS NOT NULL AND to_group_id NOT IN (SELECT DISTINCT id FROM c_group_info)";
2163
    $connection->executeQuery($sql);
2164
2165
    // This updates the group_id with c_group_info.iid instead of c_group_info.id
2166
2167
    if ($debug) {
2168
        error_log('update iids');
2169
    }
2170
2171
    $groupTableToFix = [
2172
        'c_group_rel_user',
2173
        'c_group_rel_tutor',
2174
        'c_permission_group',
2175
        'c_role_group',
2176
        'c_survey_invitation',
2177
        'c_attendance_calendar_rel_group'
2178
    ];
2179
2180
    foreach ($groupTableToFix as $table) {
2181
        $sql = "SELECT * FROM $table";
2182
        $result = $connection->fetchAll($sql);
2183
        foreach ($result as $item) {
2184
            $iid = $item['iid'];
2185
            $courseId = $item['c_id'];
2186
            $groupId = intval($item['group_id']);
2187
2188
            // Fix group id
2189 View Code Duplication
            if (!empty($groupId)) {
2190
                $sql = "SELECT * FROM c_group_info
2191
                        WHERE c_id = $courseId AND id = $groupId
2192
                        LIMIT 1";
2193
                $data = $connection->fetchAssoc($sql);
2194
                if (!empty($data)) {
2195
                    $newGroupId = $data['iid'];
2196
                    $sql = "UPDATE $table SET group_id = $newGroupId
2197
                            WHERE iid = $iid";
2198
                    $connection->executeQuery($sql);
2199
                } else {
2200
                    // The group does not exists clean this record
2201
                    $sql = "DELETE FROM $table WHERE iid = $iid";
2202
                    $connection->executeQuery($sql);
2203
                }
2204
            }
2205
        }
2206
    }
2207
2208
    // Fix c_item_property
2209
    if ($debug) {
2210
        error_log('update c_item_property');
2211
    }
2212
2213
    $sql = "SELECT * FROM course";
2214
    $courseList = $connection->fetchAll($sql);
2215
    if ($debug) {
2216
        error_log('Getting course list');
2217
    }
2218
2219
    $totalCourse = count($courseList);
2220
    $counter = 0;
2221
2222
    foreach ($courseList as $courseData) {
2223
        $courseId = $courseData['id'];
2224
        if ($debug) {
2225
            error_log('Updating course: '.$courseData['code']);
2226
        }
2227
2228
        $sql = "SELECT * FROM c_item_property WHERE c_id = $courseId";
2229
        $result = $connection->fetchAll($sql);
2230
2231
        foreach ($result as $item) {
2232
            //$courseId = $item['c_id'];
2233
            $sessionId = intval($item['session_id']);
2234
            $groupId = intval($item['to_group_id']);
2235
            $iid = $item['iid'];
2236
            $ref = $item['ref'];
2237
2238
            // Fix group id
2239 View Code Duplication
            if (!empty($groupId)) {
2240
                $sql = "SELECT * FROM c_group_info
2241
                        WHERE c_id = $courseId AND id = $groupId";
2242
                $data = $connection->fetchAssoc($sql);
2243
                if (!empty($data)) {
2244
                    $newGroupId = $data['iid'];
2245
                    $sql = "UPDATE c_item_property SET to_group_id = $newGroupId
2246
                            WHERE iid = $iid";
2247
                    $connection->executeQuery($sql);
2248
                } else {
2249
                    // The group does not exists clean this record
2250
                    $sql = "DELETE FROM c_item_property WHERE iid = $iid";
2251
                    $connection->executeQuery($sql);
2252
                }
2253
            }
2254
2255
            $sql = '';
2256
            $newId = '';
2257
            switch ($item['tool']) {
2258
                case TOOL_LINK:
2259
                    $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
2260
                    break;
2261
                case TOOL_STUDENTPUBLICATION:
2262
                    $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2263
                    break;
2264
                case TOOL_QUIZ:
2265
                    $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2266
                    break;
2267
                case TOOL_DOCUMENT:
2268
                    $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2269
                    break;
2270
                case TOOL_FORUM:
2271
                    $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND id = $ref";
2272
                    break;
2273
                case 'thread':
2274
                    $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND id = $ref";
2275
                    break;
2276
            }
2277
2278 View Code Duplication
            if (!empty($sql) && !empty($newId)) {
2279
                $data = $connection->fetchAssoc($sql);
2280
                if (isset($data['iid'])) {
2281
                    $newId = $data['iid'];
2282
                }
2283
                $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid";
2284
                error_log($sql);
2285
                $connection->executeQuery($sql);
2286
            }
2287
2288
            if ($debug) {
2289
                // Print a status in the log once in a while
2290
                error_log("Process item #$counter/$totalCourse");
2291
            }
2292
            $counter++;
2293
        }
2294
    }
2295
2296
    if ($debug) {
2297
        error_log('update gradebook_link');
2298
    }
2299
2300
    // Fix gradebook_link
2301
    $sql = "SELECT * FROM gradebook_link";
2302
    $result = $connection->fetchAll($sql);
2303
    foreach ($result as $item) {
2304
        $courseCode = $item['course_code'];
2305
        $courseInfo = api_get_course_info($courseCode);
2306
2307
        if (empty($courseInfo)) {
2308
            continue;
2309
        }
2310
        $courseId = $courseInfo['real_id'];
2311
        $ref = $item['ref_id'];
2312
        $iid = $item['id'];
2313
        $sql = '';
2314
2315
        switch ($item['type']) {
2316
            case LINK_LEARNPATH:
2317
                $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
2318
                break;
2319
            case LINK_STUDENTPUBLICATION:
2320
                $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
2321
                break;
2322
            case LINK_EXERCISE:
2323
                $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
2324
                break;
2325
            case LINK_ATTENDANCE:
2326
                //$sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
2327
                break;
2328
            case LINK_FORUM_THREAD:
2329
                $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
2330
                break;
2331
        }
2332
2333 View Code Duplication
        if (!empty($sql)) {
2334
            $data = $connection->fetchAssoc($sql);
2335
            if (isset($data) && isset($data['iid'])) {
2336
                $newId = $data['iid'];
2337
                $sql = "UPDATE gradebook_link SET ref_id = $newId
2338
                        WHERE id = $iid";
2339
                $connection->executeQuery($sql);
2340
            }
2341
        }
2342
    }
2343
2344
    if ($debug) {
2345
        error_log('update groups');
2346
    }
2347
2348
    $sql = "SELECT * FROM groups";
2349
    $result = $connection->executeQuery($sql);
2350
    $groups = $result->fetchAll();
2351
2352
    $oldGroups = array();
2353
2354
    if (!empty($groups)) {
2355
        foreach ($groups as $group) {
2356
            if (empty($group['name'])) {
2357
                continue;
2358
            }
2359
2360
            /*$group['description'] = Database::escape_string($group['description']);
2361
            $group['name'] = Database::escape_string($group['name']);
2362
            $sql = "INSERT INTO usergroup (name, group_type, description, picture, url, visibility, updated_at, created_at)
2363
                    VALUES ('{$group['name']}', '1', '{$group['description']}', '{$group['picture_uri']}', '{$group['url']}', '{$group['visibility']}', '{$group['updated_on']}', '{$group['created_on']}')";
2364
            */
2365
            $params = [
2366
                'name' => $group['name'],
2367
                'description' => $group['description'],
2368
                'group_type' => 1,
2369
                'picture' => $group['picture_uri'],
2370
                'url' => $group['url'],
2371
                'visibility' => $group['visibility'],
2372
                'updated_at' => $group['updated_on'],
2373
                'created_at' => $group['created_on']
2374
            ];
2375
            $connection->insert('usergroup', $params);
2376
            //$connection->executeQuery($sql);
2377
            $id = $connection->lastInsertId('id');
2378
            $oldGroups[$group['id']] = $id;
2379
        }
2380
    }
2381
2382
    if (!empty($oldGroups)) {
2383
        foreach ($oldGroups as $oldId => $newId) {
2384
            $path = \GroupPortalManager::get_group_picture_path_by_id(
2385
                $oldId,
2386
                'system'
2387
            );
2388
2389
            if (!empty($path)) {
2390
                $newPath = str_replace(
2391
                    "groups/$oldId/",
2392
                    "groups/$newId/",
2393
                    $path['dir']
2394
                );
2395
                $command = "mv {$path['dir']} $newPath ";
2396
                system($command);
2397
            }
2398
        }
2399
2400
        $sql = "SELECT * FROM group_rel_user";
2401
        $result = $connection->executeQuery($sql);
2402
        $dataList = $result->fetchAll();
2403
2404
        if (!empty($dataList)) {
2405
            foreach ($dataList as $data) {
2406
                if (isset($oldGroups[$data['group_id']])) {
2407
                    $data['group_id'] = $oldGroups[$data['group_id']];
2408
2409
                    $userId = $data['user_id'];
2410
2411
                    $sql = "SELECT id FROM user WHERE user_id = $userId";
2412
                    $userResult = $connection->executeQuery($sql);
2413
                    $userInfo = $userResult->fetch();
2414
                    if (empty($userInfo)) {
2415
                        continue;
2416
                    }
2417
2418
                    $sql = "INSERT INTO usergroup_rel_user (usergroup_id, user_id, relation_type)
2419
                            VALUES ('{$data['group_id']}', '{$userId}', '{$data['relation_type']}')";
2420
                    $connection->executeQuery($sql);
2421
                }
2422
            }
2423
        }
2424
2425
        $sql = "SELECT * FROM group_rel_group";
2426
        $result = $connection->executeQuery($sql);
2427
        $dataList = $result->fetchAll();
2428
2429
        if (!empty($dataList)) {
2430
            foreach ($dataList as $data) {
2431
                if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
2432
                    $data['group_id'] = $oldGroups[$data['group_id']];
2433
                    $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
2434
                    $sql = "INSERT INTO usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
2435
                            VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
2436
                    $connection->executeQuery($sql);
2437
                }
2438
            }
2439
        }
2440
2441
        $sql = "SELECT * FROM announcement_rel_group";
2442
        $result = $connection->executeQuery($sql);
2443
        $dataList = $result->fetchAll();
2444
2445
        if (!empty($dataList)) {
2446
            foreach ($dataList as $data) {
2447 View Code Duplication
                if (isset($oldGroups[$data['group_id']])) {
2448
                    // Deleting relation
2449
                    $sql = "DELETE FROM announcement_rel_group WHERE group_id = {$data['group_id']}";
2450
                    $connection->executeQuery($sql);
2451
2452
                    // Add new relation
2453
                    $data['group_id'] = $oldGroups[$data['group_id']];
2454
                    $sql = "INSERT INTO announcement_rel_group(group_id, announcement_id)
2455
                            VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
2456
                    $connection->executeQuery($sql);
2457
                }
2458
            }
2459
        }
2460
2461
        $sql = "SELECT * FROM group_rel_tag";
2462
        $result = $connection->executeQuery($sql);
2463
        $dataList = $result->fetchAll();
2464 View Code Duplication
        if (!empty($dataList)) {
2465
            foreach ($dataList as $data) {
2466
                if (isset($oldGroups[$data['group_id']])) {
2467
                    $data['group_id'] = $oldGroups[$data['group_id']];
2468
                    $sql = "INSERT INTO usergroup_rel_tag (tag_id, usergroup_id)
2469
                            VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
2470
                    $connection->executeQuery($sql);
2471
                }
2472
            }
2473
        }
2474
    }
2475
2476
    if ($debug) {
2477
        error_log('update extra fields');
2478
    }
2479
2480
    // Extra fields
2481
    $extraFieldTables = [
2482
        ExtraField::USER_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_USER_FIELD),
2483
        ExtraField::COURSE_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
2484
        //ExtraField::LP_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_LP_FIELD),
2485
        ExtraField::SESSION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
2486
        //ExtraField::CALENDAR_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
2487
        //ExtraField::QUESTION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
2488
        //ExtraField::USER_FIELD_TYPE => //Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD),
2489
    ];
2490
2491
    foreach ($extraFieldTables as $type => $table) {
2492
        //continue;
2493
        $sql = "SELECT * FROM $table ";
2494
        if ($debug) {
2495
            error_log($sql);
2496
        }
2497
        $result = $connection->query($sql);
2498
        $fields = $result->fetchAll();
2499
2500
        foreach ($fields as $field) {
2501
            if ($debug) {
2502
                error_log("Loading field: ".$field['field_variable']);
2503
            }
2504
            $originalId = $field['id'];
2505
            $extraField = new ExtraField();
2506
            $extraField
2507
                ->setExtraFieldType($type)
2508
                ->setVariable($field['field_variable'])
2509
                ->setFieldType($field['field_type'])
2510
                ->setDisplayText($field['field_display_text'])
2511
                ->setDefaultValue($field['field_default_value'])
2512
                ->setFieldOrder($field['field_order'])
2513
                ->setVisible($field['field_visible'])
2514
                ->setChangeable($field['field_changeable'])
2515
                ->setFilter($field['field_filter']);
2516
2517
            $em->persist($extraField);
2518
            $em->flush();
2519
2520
            $values = array();
2521
            $handlerId = null;
2522
            switch ($type) {
2523
                case ExtraField::USER_FIELD_TYPE:
2524
                    $optionTable = Database::get_main_table(
2525
                        TABLE_MAIN_USER_FIELD_OPTIONS
2526
                    );
2527
                    $valueTable = Database::get_main_table(
2528
                        TABLE_MAIN_USER_FIELD_VALUES
2529
                    );
2530
                    $handlerId = 'user_id';
2531
                    break;
2532
                case ExtraField::COURSE_FIELD_TYPE:
2533
                    $optionTable = Database::get_main_table(
2534
                        TABLE_MAIN_COURSE_FIELD_OPTIONS
2535
                    );
2536
                    $valueTable = Database::get_main_table(
2537
                        TABLE_MAIN_COURSE_FIELD_VALUES
2538
                    );
2539
                    $handlerId = 'c_id';
2540
                    break;
2541
                case ExtraField::SESSION_FIELD_TYPE:
2542
                    $optionTable = Database::get_main_table(
2543
                        TABLE_MAIN_SESSION_FIELD_OPTIONS
2544
                    );
2545
                    $valueTable = Database::get_main_table(
2546
                        TABLE_MAIN_SESSION_FIELD_VALUES
2547
                    );
2548
                    $handlerId = 'session_id';
2549
                    break;
2550
            }
2551
2552
            if (!empty($optionTable)) {
2553
                $sql = "SELECT * FROM $optionTable WHERE field_id = $originalId ";
2554
                $result = $connection->query($sql);
2555
                $options = $result->fetchAll();
2556
2557
                foreach ($options as $option) {
2558
                    $extraFieldOption = new ExtraFieldOptions();
2559
                    $extraFieldOption
2560
                        ->setDisplayText($option['option_display_text'])
2561
                        ->setField($extraField)
2562
                        ->setOptionOrder($option['option_order'])
2563
                        ->setValue($option['option_value']);
2564
                    $em->persist($extraFieldOption);
2565
                    $em->flush();
2566
                }
2567
2568
                $sql = "SELECT * FROM $valueTable WHERE field_id = $originalId ";
2569
                $result = $connection->query($sql);
2570
                $values = $result->fetchAll();
2571
                if ($debug) {
2572
                    error_log("Fetch all values for field");
2573
                }
2574
            }
2575
2576
            if (!empty($values)) {
2577
                if ($debug) {
2578
                    error_log("Saving field value in new table");
2579
                }
2580
                $k = 0;
2581
                foreach ($values as $value) {
2582
                    if (isset($value[$handlerId])) {
2583
                        /*
2584
                        $extraFieldValue = new ExtraFieldValues();
2585
                        $extraFieldValue
2586
                            ->setValue($value['field_value'])
2587
                            ->setField($extraField)
2588
                            ->setItemId($value[$handlerId]);
2589
                        $em->persist($extraFieldValue);
2590
                        $em->flush();
2591
                        */
2592
                        // Insert without the use of the entity as it reduces
2593
                        // speed to 2 records per second (much too slow)
2594
                        $params = [
2595
                            'field_id' => $extraField->getId(),
2596
                            'value' => $value['field_value'],
2597
                            'item_id' => $value[$handlerId]
2598
                        ];
2599
                        $connection->insert('extra_field_values', $params);
2600
                        if ($debug && ($k % 10000 == 0)) {
2601
                            error_log("Saving field $k");
2602
                        }
2603
                        $k++;
2604
                    }
2605
                }
2606
            }
2607
        }
2608
    }
2609
2610
    if ($debug) {
2611
        error_log('Remove index');
2612
    }
2613
2614
    // Drop temporary indexes added to increase speed of this function's queries
2615
    $sql = "ALTER TABLE c_document DROP INDEX tmpidx_doc";
2616
    $connection->executeQuery($sql);
2617
    $sql = "ALTER TABLE c_student_publication DROP INDEX tmpidx_stud";
2618
    $connection->executeQuery($sql);
2619
    $sql = "ALTER TABLE c_quiz DROP INDEX tmpidx_quiz";
2620
    $connection->executeQuery($sql);
2621
    $sql = "ALTER TABLE c_item_property DROP INDEX tmpidx_ip";
2622
    $connection->executeQuery($sql);
2623
2624
    if ($debug) {
2625
        error_log('Finish fixId function');
2626
    }
2627
}
2628
2629
/**
2630
 *
2631
 * After the schema was created (table creation), the function adds
2632
 * admin/platform information.
2633
 *
2634
 * @param EntityManager $manager
2635
 * @param string $sysPath
2636
 * @param string $encryptPassForm
2637
 * @param string $passForm
2638
 * @param string $adminLastName
2639
 * @param string $adminFirstName
2640
 * @param string $loginForm
2641
 * @param string $emailForm
2642
 * @param string $adminPhoneForm
2643
 * @param string $languageForm
2644
 * @param string $institutionForm
2645
 * @param string $institutionUrlForm
2646
 * @param string $siteName
2647
 * @param string $allowSelfReg
2648
 * @param string $allowSelfRegProf
2649
 * @param string $installationProfile Installation profile, if any was provided
2650
 */
2651
function finishInstallation(
2652
    $manager,
2653
    $sysPath,
2654
    $encryptPassForm,
2655
    $passForm,
2656
    $adminLastName,
2657
    $adminFirstName,
2658
    $loginForm,
2659
    $emailForm,
2660
    $adminPhoneForm,
2661
    $languageForm,
2662
    $institutionForm,
2663
    $institutionUrlForm,
2664
    $siteName,
2665
    $allowSelfReg,
2666
    $allowSelfRegProf,
2667
    $installationProfile = ''
2668
) {
2669
    $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYS_PATH);
2670
2671
    // Inserting data
2672
    $data = file_get_contents($sysPath.'main/install/data.sql');
2673
    $result = $manager->getConnection()->prepare($data);
2674
    $result->execute();
2675
    $result->closeCursor();
2676
2677
    UserManager::setPasswordEncryption($encryptPassForm);
2678
2679
    // Create admin user.
2680
    UserManager::create_user(
2681
        $adminFirstName,
2682
        $adminLastName,
2683
        1,
2684
        $emailForm,
2685
        $loginForm,
2686
        $passForm,
2687
        'ADMIN', //$official_code = '',
2688
        $languageForm,
2689
        $adminPhoneForm,
2690
        '', //$picture_uri = '',
2691
        PLATFORM_AUTH_SOURCE,
2692
        '',//$expirationDate,
2693
        1,
2694
        0,
2695
        null,
2696
        '',
2697
        false,  //$send_mail = false,
2698
        true //$isAdmin = false
2699
    );
2700
2701
    // Create anonymous user.
2702
    UserManager::create_user(
2703
        'Joe',
2704
        'Anonymous',
2705
        6,
2706
        'anonymous@localhost',
2707
        'anon',
2708
        'anon',
2709
        'anonymous', //$official_code = '',
2710
        $languageForm,
2711
        '',
2712
        '', //$picture_uri = '',
2713
        PLATFORM_AUTH_SOURCE,
2714
        '',
2715
        1,
2716
        0,
2717
        null,
2718
        '',
2719
        false,  //$send_mail = false,
2720
        false //$isAdmin = false
2721
    );
2722
2723
    // Set default language
2724
    $sql = "UPDATE language SET available=1 WHERE dokeos_folder = '$languageForm'";
2725
    Database::query($sql);
2726
2727
    // Install settings
2728
    installSettings(
2729
        $institutionForm,
2730
        $institutionUrlForm,
2731
        $siteName,
2732
        $emailForm,
2733
        $adminLastName,
2734
        $adminFirstName,
2735
        $languageForm,
2736
        $allowSelfReg,
2737
        $allowSelfRegProf,
2738
        $installationProfile
2739
    );
2740
2741
    lockSettings();
2742
    updateDirAndFilesPermissions();
2743
}
2744
2745
/**
2746
 * Update settings based on installation profile defined in a JSON file
2747
 * @param string $installationProfile The name of the JSON file in main/install/profiles/ folder
2748
 *
2749
 * @return bool false on failure (no bad consequences anyway, just ignoring profile)
2750
 */
2751
function installProfileSettings($installationProfile = '')
2752
{
2753
    if (empty($installationProfile)) {
2754
        return false;
2755
    }
2756
    $jsonPath = api_get_path(SYS_PATH).'main/install/profiles/'.$installationProfile.'.json';
2757
    // Make sure the path to the profile is not hacked
2758
    if (!Security::check_abs_path($jsonPath, api_get_path(SYS_PATH).'main/install/profiles/')) {
2759
        return false;
2760
    }
2761
    if (!is_file($jsonPath)) {
2762
        return false;
2763
    }
2764
    if (!is_readable($jsonPath)) {
2765
        return false;
2766
    }
2767
    if (!function_exists('json_decode')) {
2768
        // The php-json extension is not available. Ignore profile.
2769
        return false;
2770
    }
2771
    $json = file_get_contents($jsonPath);
2772
    $params = json_decode($json);
2773
    if ($params === false or $params === null) {
2774
        return false;
2775
    }
2776
    $settings = $params->params;
2777
    if (!empty($params->parent)) {
2778
        installProfileSettings($params->parent);
2779
    }
2780
    foreach ($settings as $id => $param) {
2781
        $sql = "UPDATE settings_current
2782
                SET selected_value = '".$param->selected_value."'
2783
                WHERE variable = '".$param->variable."'";
2784
        if (!empty($param->subkey)) {
2785
            $sql .= " AND subkey='" . $param->subkey . "'";
2786
        }
2787
        Database::query($sql);
2788
    }
2789
2790
    return true;
2791
}
2792