Project

General

Profile

1 2 Manuela
<?php
2
/**
3
 *
4
 * @category        backend
5
 * @package         install
6
 * @author          WebsiteBaker Project
7
 * @copyright       Ryan Djurovich
8
 * @copyright       WebsiteBaker Org. e.V.
9
 * @link            http://websitebaker.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.8.3
12
 * @requirements    PHP 5.3.6 and higher
13
 * @version         $Id$
14
 * @filesource      $HeadURL$
15
 * @lastmodified    $Date$
16
 *
17
 */
18
19
// Function to set error
20 4 Manuela
    function set_error($message, $field_name = '') {
21
    //    global $_POST;
22
        if (isset($message) AND $message != '') {
23
            // first clean session before fill up with values to remember
24
            $_SESSION = [];
25
            // Copy values entered into session so user doesn't have to re-enter everything
26
            if (isset($_POST['website_title'])) {
27
                $_SESSION['wb_url'] = $_POST['wb_url'];
28
                $_SESSION['default_timezone'] = $_POST['default_timezone'];
29
                $_SESSION['default_language'] = $_POST['default_language'];
30
                if (!isset($_POST['operating_system'])) {
31
                    $_SESSION['operating_system'] = 'linux';
32
                } else {
33
                    $_SESSION['operating_system'] = $_POST['operating_system'];
34
                }
35
                $_SESSION['world_writeable'] = (bool) isset($_POST['world_writeable']) ? $_POST['world_writeable'] : false;
36
                $_SESSION['database_host'] = $_POST['database_host'];
37
                $_SESSION['database_username'] = $_POST['database_username'];
38
                $_SESSION['database_password'] = $_POST['database_password'];
39
                $_SESSION['database_name'] = $_POST['database_name'];
40
                $_SESSION['table_prefix'] = $_POST['table_prefix'];
41
                $_SESSION['install_tables'] = (bool) isset($_POST['install_tables']) ? $_POST['install_tables'] : false;
42
                $_SESSION['website_title'] = $_POST['website_title'];
43
                $_SESSION['admin_username'] = $_POST['admin_username'];
44
                $_SESSION['admin_email'] = $_POST['admin_email'];
45
                $_SESSION['admin_password'] = $_POST['admin_password'];
46
                $_SESSION['admin_repassword'] = $_POST['admin_repassword'];
47 2 Manuela
            }
48 4 Manuela
            // Set the message
49
            $_SESSION['message'] = $message;
50
            // Set the element(s) to highlight
51
            if ($field_name != '') {
52
                $_SESSION['ERROR_FIELD'] = $field_name;
53 2 Manuela
            }
54 4 Manuela
            // Specify that session support is enabled
55
            $_SESSION['session_support'] = '<font class="good">Enabled</font>';
56
            // Redirect to first page again and exit
57
            header('Location: index.php?sessions_checked=true');
58
            exit();
59 2 Manuela
        }
60
    }
61
/* */
62
63
// Function to workout what the default permissions are for files created by the webserver
64 4 Manuela
    function default_file_mode($temp_dir) {
65
        if (version_compare(PHP_VERSION, '5.3.6', '>=') && is_writable($temp_dir)) {
66
            $filename = $temp_dir.'/test_permissions.txt';
67
            $handle = fopen($filename, 'w');
68
            fwrite($handle, 'This file is to get the default file permissions');
69
            fclose($handle);
70
            $default_file_mode = '0'.substr(sprintf('%o', fileperms($filename)), -3);
71
            unlink($filename);
72
        } else {
73
            $default_file_mode = '0777';
74
        }
75
        return $default_file_mode;
76 2 Manuela
    }
77
78
// Function to workout what the default permissions are for directories created by the webserver
79 4 Manuela
    function default_dir_mode($temp_dir) {
80
        if (version_compare(PHP_VERSION, '5.3.6', '>=') && is_writable($temp_dir)) {
81
            $dirname = $temp_dir.'/test_permissions/';
82
            mkdir($dirname);
83
            $default_dir_mode = '0'.substr(sprintf('%o', fileperms($dirname)), -3);
84
            rmdir($dirname);
85
        } else {
86
            $default_dir_mode = '0777';
87
        }
88
        return $default_dir_mode;
89 2 Manuela
    }
90
91 4 Manuela
    function add_slashes($sInput) {
92
    //    if (get_magic_quotes_gpc() || ( !is_string($input) )) {
93
    //        return $input;
94
    //    }
95
    //    $output = addslashes($input);
96
    //    return $output;
97
        return $sInput;
98 2 Manuela
    }
99 4 Manuela
//
100
// ************************************************************************************ //
101
//
102
103
$debug = false;
104
105
if (true === $debug) {
106
    ini_set('display_errors', 1);
107
    error_reporting(E_ALL);
108 2 Manuela
}
109 4 Manuela
// Start a session
110
if (!defined('SESSION_STARTED')) {
111
    session_name('wb-installer');
112
    session_start();
113
    define('SESSION_STARTED', true);
114
}
115
$bTokenOk = false;
116
if (isset($_SESSION['token']) && isset($_POST[$_SESSION['token']['name']])) {
117
    $bTokenOk = (bool) ($_POST[$_SESSION['token']['name']] == $_SESSION['token']['value']);
118
}
119
if (!$bTokenOk) { throw new RuntimeException('Illegal file access detected!!'); }
120
unset($_SESSION['token']);
121 2 Manuela
122
// Begin check to see if form was even submitted
123
// Set error if no post vars found
124
if (!isset($_POST['website_title'])) {
125
    set_error('Please fill-in the form below');
126
}
127
// End check to see if form was even submitted
128
129
// Begin path and timezone details code
130
131
// Check if user has entered the installation url
132
if (!isset($_POST['wb_url']) OR $_POST['wb_url'] == '') {
133
    set_error('Please enter an absolute URL', 'wb_url');
134
} else {
135
    $wb_url = $_POST['wb_url'];
136
}
137
// Remove any slashes at the end of the URL
138
$wb_url = rtrim($wb_url, '\\/');
139
// Get the default time zone
140
if (!isset($_POST['default_timezone']) OR !is_numeric($_POST['default_timezone'])) {
141
    set_error('Please select a valid default timezone', 'default_timezone');
142
} else {
143
    $default_timezone = $_POST['default_timezone']*60*60;
144
}
145
// End path and timezone details code
146
147
// Get the default language
148
$sLangDir = str_replace('\\', '/', dirname(dirname(__FILE__)).'/languages/');
149
$allowed_languages = preg_replace('/^.*\/([A-Z]{2})\.php$/iU', '\1', glob($sLangDir.'??.php'));
150
if (!isset($_POST['default_language']) OR !in_array($_POST['default_language'], $allowed_languages)) {
151
    set_error('Please select a valid default backend language','default_language');
152
} else {
153
    $default_language = $_POST['default_language'];
154
    // make sure the selected language file exists in the language folder
155
    if (!file_exists('../languages/' .$default_language .'.php')) {
156 4 Manuela
        set_error(
157
            'The language file: \'' .$default_language .'.php\' is missing. '.
158
            'Upload file to language folder or choose another language',
159
            'default_language'
160
        );
161 2 Manuela
    }
162
}
163
// End default language details code
164
165
// Begin operating system specific code
166
// Get operating system
167
if (!isset($_POST['operating_system']) OR $_POST['operating_system'] != 'linux' AND $_POST['operating_system'] != 'windows') {
168
    set_error('Please select a valid operating system');
169
} else {
170
    $operating_system = $_POST['operating_system'];
171
}
172
// Work-out file permissions
173
if ($operating_system == 'windows') {
174
    $file_mode = '0666';
175
    $dir_mode = '0777';
176
} elseif (isset($_POST['world_writeable']) AND $_POST['world_writeable'] == 'true') {
177
    $file_mode = '0666';
178
    $dir_mode = '0777';
179
} else {
180
    $file_mode = default_file_mode('../temp');
181
    $dir_mode = default_dir_mode('../temp');
182
}
183
// End operating system specific code
184
185
// Begin database details code
186
// Check if user has entered a database host
187
if (!isset($_POST['database_host']) OR $_POST['database_host'] == '') {
188
    set_error('Please enter a database host name', 'database_host');
189
} else {
190
    $database_host = trim($_POST['database_host']);
191
}
192
// extract port if available
193
if (isset($database_port)) { unset($database_port); }
194
$aMatches = preg_split('/:/s', $database_host, -1, PREG_SPLIT_NO_EMPTY);
195
$database_host = $aMatches[0];
196
$database_port = (isset($aMatches[1]) ? (int)$aMatches[1] : ini_get('mysqli.default_port'));
197
198
// Check if user has entered a database username
199
if (!isset($_POST['database_username']) OR $_POST['database_username'] == '') {
200
    set_error('Please enter a database username','database_username');
201
} else {
202
    $database_username = $_POST['database_username'];
203
}
204
// Check if user has entered a database password
205
if (!isset($_POST['database_password'])) {
206
    set_error('Please enter a database password', 'database_password');
207
} else {
208
    $database_password = $_POST['database_password'];
209
}
210
// Check if user has entered a database name
211
if (!isset($_POST['database_name']) OR $_POST['database_name'] == '') {
212
    set_error('Please enter a database name', 'database_name');
213
} else {
214
    // make sure only allowed characters are specified
215
    if(preg_match('/[^a-z0-9_-]+/i', $_POST['database_name'])) {
216
        // contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
217
        set_error('Only characters a-z, A-Z, 0-9, - and _ allowed in database name.', 'database_name');
218
    }
219
    $database_name = $_POST['database_name'];
220
}
221
// Get table prefix
222
if (preg_match('/[^a-z0-9_]+/i', $_POST['table_prefix'])) {
223
    // contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
224
    set_error('Only characters a-z, A-Z, 0-9 and _ allowed in table_prefix.', 'table_prefix');
225
} else {
226
    $table_prefix = $_POST['table_prefix'];
227
}
228
229
$install_tables = true;
230
// Begin website title code
231
// Get website title
232
if (!isset($_POST['website_title']) OR $_POST['website_title'] == '') {
233
    set_error('Please enter a website title', 'website_title');
234
} else {
235
    $website_title = add_slashes($_POST['website_title']);
236
}
237
// End website title code
238
239
// Begin admin user details code
240
$sClientIp = '';
241
// Get admin username
242
if (!isset($_POST['admin_username']) OR $_POST['admin_username'] == '') {
243
    set_error('Please enter a username for the Administrator account','admin_username');
244
} else {
245
    $admin_username = $_POST['admin_username'];
246
    $sClientIp = (isset($_SERVER['REMOTE_ADDR']))
247
                         ? $_SERVER['REMOTE_ADDR'] : '000.000.000.000';
248
    $iClientIp = ip2long($sClientIp);
249
    $sClientIp = long2ip(($iClientIp & ~65535));
250
251
}
252
// Get admin email and validate it
253
if (!isset($_POST['admin_email']) OR $_POST['admin_email'] == '') {
254
    set_error('Please enter an email for the Administrator account','admin_email');
255
} else {
256
    if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i', $_POST['admin_email'])) {
257
        $admin_email = $_POST['admin_email'];
258
    } else {
259
        set_error('Please enter a valid email address for the Administrator account','admin_email');
260
    }
261
}
262
// Get the two admin passwords entered, and check that they match
263
if (!isset($_POST['admin_password']) OR $_POST['admin_password'] == '') {
264
    set_error('Please enter a password for the Administrator account','admin_password');
265
} else {
266
    $admin_password = $_POST['admin_password'];
267
}
268
if (!isset($_POST['admin_repassword']) OR $_POST['admin_repassword'] == '') {
269
    set_error('Please make sure you re-enter the password for the Administrator account','admin_repassword');
270
} else {
271
    $admin_repassword = $_POST['admin_repassword'];
272
}
273
if ($admin_password != $admin_repassword) {
274
    set_error('Sorry, the two Administrator account passwords you entered do not match','admin_repassword');
275
}
276
277
$database_charset = 'utf8';
278
// End admin user details code
279
280
$getNewVersion = function () {
281
    $sVersionFile = file_get_contents(dirname(__DIR__).'/admin/interface/version.php');
282
    $sPattern = '=define\s*\(\'VERSION\'\,\s*\'([^\']*)\'=is';
283
    $sVersion = ((preg_match($sPattern, $sVersionFile, $aMatches)) ? $aMatches[1] : '???');
284
    return $sVersion;
285
};
286
// build name and content of the config file
287
$sFileMarker = '*** auto generated config file for '.$getNewVersion();
288
$config_filename = dirname(dirname(__FILE__)).'/config.php';
289
$config_content
290
    = '<?php'."\n"
291
    . '/*'."\n"
292
    . ' '.$sFileMarker."\n"
293
    . ' *** WebsiteBaker '.$getNewVersion()."\n"
294
    . ' *** created at '.date('Y-m-d h:i:s e')."\n"
295
    . ' */'."\n"
296
    . '// define(\'DEBUG\', false);'."\n"
297
    . 'define(\'DB_TYPE\', \'mysqli\');'."\n"
298
    . 'define(\'DB_HOST\', \''.$database_host.'\');'."\n"
299
    . 'define(\'DB_PORT\', \''.sprintf('%04d', $database_port).'\');'."\n"
300
    . 'define(\'DB_NAME\', \''.$database_name.'\');'."\n"
301
    . 'define(\'DB_USERNAME\', \''.$database_username.'\');'."\n"
302
    . 'define(\'DB_PASSWORD\', \''.$database_password.'\');'."\n"
303
    . 'define(\'DB_CHARSET\', \''.$database_charset.'\');'."\n"
304
    . 'define(\'TABLE_PREFIX\', \''.$table_prefix.'\');'."\n"
305
   . "\n"
306
    . 'define(\'WB_URL\', \''.$wb_url.'\'); '
307
    . '// no trailing slash or backslash!!'."\n"
308
    . 'define(\'ADMIN_DIRECTORY\', \'admin\'); '
309
    . '// no leading/trailing slash or backslash!! A simple directory name only!!'."\n";
310
unset($getNewVersion);
311
// Check if the file exists and is writable first.
312
$sMsg = '';
313
if (is_writable($config_filename)) {
314
    // try to write file
315
    if (file_put_contents($config_filename, $config_content) === false) {
316
        $sMsg = 'Cannot write to the configuration file <'.$config_filename.'>';
317
    }
318
} else {
319
    $sMsg = 'The configuration file <'.$config_filename.'> is missing or not writable.<br />'
320
          . 'Change its permissions so it is, then re-run step 4.';
321
}
322
if ($sMsg) { set_error($sMsg); } // if something gone wrong, break with message
323
// include config file to set constants
324
include_once($config_filename);
325
// now we can complete the config file
326
$config_content
327
    = "\n".'require_once __DIR__.\'/framework/initialize.php\';'."\n"
328
    . '// --- end of file ----------------------------------'."\n";
329
// no errorhandling needed. 15 lines before we already wrote to this file successful!
330
file_put_contents($config_filename, $config_content, FILE_APPEND);
331
332
// Define additional configuration constants
333
define('WB_PATH', dirname(dirname(__FILE__)));
334
define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY);
335
define('ADMIN_URL', WB_URL.'/'.ADMIN_DIRECTORY);
336
require(ADMIN_PATH.'/interface/version.php');
337
// *** initialize Exception handling
338
if(!function_exists('globalExceptionHandler')) {
339
    include(WB_PATH.'/framework/globalExceptionHandler.php');
340
}
341
342
// Try connecting to database
343
if (!file_exists(WB_PATH.'/framework/class.database.php')) {
344
    set_error('It appears the Absolute path that you entered is incorrect or file \'class.database.php\' is missing!');
345
}
346
include(WB_PATH.'/framework/class.database.php');
347
try {
348
    $database = new database();
349
} catch (DatabaseException $e) {
350
    $sMsg = 'Database host name, username and/or password incorrect.<br />MySQL Error:<br />'
351
          . $e->getMessage();
352
    set_error($sMsg);
353
}
354
if (!defined('WB_INSTALL_PROCESS')) {
355
    define ('WB_INSTALL_PROCESS', true);
356
}
357
358
/*****************************
359
Begin Create Database Tables
360
*****************************/
361
$sInstallDir = dirname(__FILE__);
362
if (is_readable($sInstallDir.'/install-struct.sql')) {
363
    if (! $database->SqlImport($sInstallDir.'/install-struct.sql', TABLE_PREFIX, false)) {
364
        set_error('unable to import \'install/install-struct.sql\'');
365
    }
366
} else {
367
    set_error('unable to read file \'install/install-struct.sql\'');
368
}
369
if (is_readable($sInstallDir.'/install-data.sql')) {
370
    if (! $database->SqlImport($sInstallDir.'/install-data.sql', TABLE_PREFIX, false )) {
371
        set_error('unable to import \'install/install-data.sql\'');
372
    }
373
} else {
374
    set_error('unable to read file \'install/install-data.sql\'');
375
}
376
$sql = // add settings from install input
377
'INSERT INTO `'.TABLE_PREFIX.'settings` (`name`, `value`) VALUES '
378
    .'(\'wb_version\', \''.VERSION.'\'),'
379
    .'(\'wb_revision\', \''.REVISION.'\'),'
380
    .'(\'wb_sp\', \''.SP.'\'),'
381
    .'(\'website_title\', \''.$website_title.'\'),'
382
    .'(\'default_language\', \''.$default_language.'\'),'
383 4 Manuela
    .'(\'app_name\', \'wb-'.(string) rand(1000, 9999).'\'),'
384 2 Manuela
    .'(\'default_timezone\', \''.$default_timezone.'\'),'
385
    .'(\'operating_system\', \''.$operating_system.'\'),'
386
    .'(\'string_dir_mode\', \''.$dir_mode.'\'),'
387
    .'(\'string_file_mode\', \''.$file_mode.'\'),'
388
    .'(\'server_email\', \''.$admin_email.'\')';
389
if (! ($database->query($sql))) {
390
    $msg = $database->get_error();
391
    set_error('unable to write \'install presets\' into table \'settings\'<br />'.$msg);
392
}
393
394
$sql = // add the Admin user
395
     'INSERT INTO `'.TABLE_PREFIX.'users` SET '
396
    .    '`group_id`=1, '
397
    .    '`groups_id`=\'1\', '
398
    .    '`active`=\'1\', '
399
    .    '`username`=\''.$admin_username.'\', '
400
    .    '`password`=\''.md5($admin_password).'\', '
401
    .    '`remember_key`=\'\', '
402
    .    '`last_reset`=0, '
403
    .    '`display_name`=\'Administrator\', '
404
    .    '`email`=\''.$admin_email.'\', '
405
    .    '`timezone`=\''.$default_timezone.'\', '
406
    .    '`date_format`=\'M d Y\', '
407
    .    '`time_format`=\'g:i A\', '
408
    .    '`language`=\''.$default_language.'\', '
409
    .    '`home_folder`=\'\', '
410
    .    '`login_when`=\''.time().'\', '
411
    .    '`login_ip`=\''.$sClientIp.'\' '
412
    .    '';
413
if (! ($database->query($sql))) {
414
    set_error('unable to write Administrator account into table \'users\'');
415
}
416
/**********************
417
END OF TABLES IMPORT
418
**********************/
419
420
// initialize the system
421
include(WB_PATH.'/framework/initialize.php');
422
423
//$sSecMod = (defined('SECURE_FORM_MODULE') && SECURE_FORM_MODULE != '') ? '.'.SECURE_FORM_MODULE : '';
424
//$sSecMod = WB_PATH.'/framework/SecureForm'.$sSecMod.'.php';
425
//require_once($sSecMod);
426
427
require_once(WB_PATH.'/framework/class.admin.php');
428
/***********************
429
// Dummy class to allow modules' install scripts to call $admin->print_error
430
***********************/
431
class admin_dummy extends admin
432
{
433
    public $error='';
434 4 Manuela
    // overwrite method from parent
435 2 Manuela
    public function print_error($message, $link = 'index.php', $auto_footer = true)
436
    {
437
        $this->error=$message;
438
    }
439
}
440
441
// Include WB functions file
442
require_once(WB_PATH.'/framework/functions.php');
443
444
require_once(WB_PATH.'/framework/Login.php');
445
// Include the PclZip class file (thanks to
446
require_once(WB_PATH.'/include/pclzip/pclzip.lib.php');
447
448
$admin = new admin_dummy('Start','',false,false);
449
450
// Load addons into DB
451
452 4 Manuela
    $sOldWorkingDir = getcwd();
453
    foreach (glob(WB_PATH.'/modules/*', GLOB_ONLYDIR) as $sModule) {
454
        load_module($sModule, true);
455
        if ($admin->error!='') {
456
            set_error($admin->error);
457 2 Manuela
        }
458
    }
459 4 Manuela
    foreach (glob(WB_PATH.'/templates/*', GLOB_ONLYDIR) as $sTemplate) {
460
        load_template($sTemplate);
461
    }
462
    foreach (glob(WB_PATH.'/languages/??.php') as $sLanguage) {
463
        load_language($sLanguage);
464
    }
465
466 2 Manuela
// Check if there was a database error
467
if ($database->is_error()) {
468
    set_error($database->get_error());
469
}
470
471
$ThemeUrl = WB_URL.$admin->correct_theme_source('warning.html');
472
// Setup template object, parse vars to it, then parse it
473
$ThemePath = realpath(WB_PATH.$admin->correct_theme_source('login.htt'));
474
475
// Log the user in and go to Website Baker Administration
476
$thisApp = new Login(
477
        array(
478
                "MAX_ATTEMPS" => "50",
479
                "WARNING_URL" => $ThemeUrl."/warning.html",
480
                "USERNAME_FIELDNAME" => 'admin_username',
481
                "PASSWORD_FIELDNAME" => 'admin_password',
482
                "REMEMBER_ME_OPTION" => false,
483
                "MIN_USERNAME_LEN" => "2",
484
                "MIN_PASSWORD_LEN" => "3",
485
                "MAX_USERNAME_LEN" => "30",
486
                "MAX_PASSWORD_LEN" => "30",
487
                'LOGIN_URL' => ADMIN_URL."/login/index.php",
488
                'DEFAULT_URL' => ADMIN_URL."/start/index.php",
489
                'TEMPLATE_DIR' => $ThemePath,
490
                'TEMPLATE_FILE' => 'login.htt',
491
                'FRONTEND' => false,
492
                'FORGOTTEN_DETAILS_APP' => ADMIN_URL."/login/forgot/index.php",
493
                'USERS_TABLE' => TABLE_PREFIX."users",
494
                'GROUPS_TABLE' => TABLE_PREFIX."groups",
495
        )
496
);