Project

General

Profile

1
<?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: save.php 2 2017-07-02 15:14:29Z Manuela $
14
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb/2.10.x/trunk/install/save.php $
15
 * @lastmodified    $Date: 2017-07-02 17:14:29 +0200 (Sun, 02 Jul 2017) $
16
 *
17
 */
18

    
19
$debug = false;
20

    
21
if (true === $debug) {
22
    ini_set('display_errors', 1);
23
    error_reporting(E_ALL);
24
}
25
// Start a session
26
if (!defined('SESSION_STARTED')) {
27
    session_name('wb-installer');
28
    session_start();
29
    define('SESSION_STARTED', true);
30
}
31
// get random-part for session_name()
32
list($usec,$sec) = explode(' ',microtime());
33
srand((float)$sec+((float)$usec*100000));
34
$session_rand = rand(1000,9999);
35

    
36
// Function to set error
37
function set_error($message, $field_name = '') {
38
//    global $_POST;
39
    if (isset($message) AND $message != '') {
40
        // Copy values entered into session so user doesn't have to re-enter everything
41
        if (isset($_POST['website_title'])) {
42
            $_SESSION['wb_url'] = $_POST['wb_url'];
43
            $_SESSION['default_timezone'] = $_POST['default_timezone'];
44
            $_SESSION['default_language'] = $_POST['default_language'];
45
            if (!isset($_POST['operating_system'])) {
46
                $_SESSION['operating_system'] = 'linux';
47
            } else {
48
                $_SESSION['operating_system'] = $_POST['operating_system'];
49
            }
50
            if (!isset($_POST['world_writeable'])) {
51
                $_SESSION['world_writeable'] = false;
52
            } else {
53
                $_SESSION['world_writeable'] = true;
54
            }
55
            $_SESSION['database_host'] = $_POST['database_host'];
56
            $_SESSION['database_username'] = $_POST['database_username'];
57
            $_SESSION['database_password'] = $_POST['database_password'];
58
            $_SESSION['database_name'] = $_POST['database_name'];
59
            $_SESSION['table_prefix'] = $_POST['table_prefix'];
60
            if (!isset($_POST['install_tables'])) {
61
                $_SESSION['install_tables'] = false;
62
            } else {
63
                $_SESSION['install_tables'] = true;
64
            }
65
            $_SESSION['website_title'] = $_POST['website_title'];
66
            $_SESSION['admin_username'] = $_POST['admin_username'];
67
            $_SESSION['admin_email'] = $_POST['admin_email'];
68
            $_SESSION['admin_password'] = $_POST['admin_password'];
69
            $_SESSION['admin_repassword'] = $_POST['admin_repassword'];
70
        }
71
        // Set the message
72
        $_SESSION['message'] = $message;
73
        // Set the element(s) to highlight
74
        if ($field_name != '') {
75
            $_SESSION['ERROR_FIELD'] = $field_name;
76
        }
77
        // Specify that session support is enabled
78
        $_SESSION['session_support'] = '<font class="good">Enabled</font>';
79
        // Redirect to first page again and exit
80
        header('Location: index.php?sessions_checked=true');
81
        exit();
82
    }
83
}
84
/* */
85

    
86
// Function to workout what the default permissions are for files created by the webserver
87
function default_file_mode($temp_dir) {
88
    if (version_compare(PHP_VERSION, '5.3.6', '>=') && is_writable($temp_dir)) {
89
        $filename = $temp_dir.'/test_permissions.txt';
90
        $handle = fopen($filename, 'w');
91
        fwrite($handle, 'This file is to get the default file permissions');
92
        fclose($handle);
93
        $default_file_mode = '0'.substr(sprintf('%o', fileperms($filename)), -3);
94
        unlink($filename);
95
    } else {
96
        $default_file_mode = '0777';
97
    }
98
    return $default_file_mode;
99
}
100

    
101
// Function to workout what the default permissions are for directories created by the webserver
102
function default_dir_mode($temp_dir) {
103
    if (version_compare(PHP_VERSION, '5.3.6', '>=') && is_writable($temp_dir)) {
104
        $dirname = $temp_dir.'/test_permissions/';
105
        mkdir($dirname);
106
        $default_dir_mode = '0'.substr(sprintf('%o', fileperms($dirname)), -3);
107
        rmdir($dirname);
108
    } else {
109
        $default_dir_mode = '0777';
110
    }
111
    return $default_dir_mode;
112
}
113

    
114
function add_slashes($input) {
115
    if (get_magic_quotes_gpc() || ( !is_string($input) )) {
116
        return $input;
117
    }
118
    $output = addslashes($input);
119
    return $output;
120
}
121

    
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
        set_error('The language file: \'' .$default_language .'.php\' is missing. Upload file to language folder or choose another language','default_language');
157
    }
158
}
159
// End default language details code
160

    
161
// Begin operating system specific code
162
// Get operating system
163
if (!isset($_POST['operating_system']) OR $_POST['operating_system'] != 'linux' AND $_POST['operating_system'] != 'windows') {
164
    set_error('Please select a valid operating system');
165
} else {
166
    $operating_system = $_POST['operating_system'];
167
}
168
// Work-out file permissions
169
if ($operating_system == 'windows') {
170
    $file_mode = '0666';
171
    $dir_mode = '0777';
172
} elseif (isset($_POST['world_writeable']) AND $_POST['world_writeable'] == 'true') {
173
    $file_mode = '0666';
174
    $dir_mode = '0777';
175
} else {
176
    $file_mode = default_file_mode('../temp');
177
    $dir_mode = default_dir_mode('../temp');
178
}
179
// End operating system specific code
180

    
181
// Begin database details code
182
// Check if user has entered a database host
183
if (!isset($_POST['database_host']) OR $_POST['database_host'] == '') {
184
    set_error('Please enter a database host name', 'database_host');
185
} else {
186
    $database_host = trim($_POST['database_host']);
187
}
188
// extract port if available
189
if (isset($database_port)) { unset($database_port); }
190
$aMatches = preg_split('/:/s', $database_host, -1, PREG_SPLIT_NO_EMPTY);
191
$database_host = $aMatches[0];
192
$database_port = (isset($aMatches[1]) ? (int)$aMatches[1] : ini_get('mysqli.default_port'));
193

    
194
// Check if user has entered a database username
195
if (!isset($_POST['database_username']) OR $_POST['database_username'] == '') {
196
    set_error('Please enter a database username','database_username');
197
} else {
198
    $database_username = $_POST['database_username'];
199
}
200
// Check if user has entered a database password
201
if (!isset($_POST['database_password'])) {
202
    set_error('Please enter a database password', 'database_password');
203
} else {
204
    $database_password = $_POST['database_password'];
205
}
206
// Check if user has entered a database name
207
if (!isset($_POST['database_name']) OR $_POST['database_name'] == '') {
208
    set_error('Please enter a database name', 'database_name');
209
} else {
210
    // make sure only allowed characters are specified
211
    if(preg_match('/[^a-z0-9_-]+/i', $_POST['database_name'])) {
212
        // contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
213
        set_error('Only characters a-z, A-Z, 0-9, - and _ allowed in database name.', 'database_name');
214
    }
215
    $database_name = $_POST['database_name'];
216
}
217
// Get table prefix
218
if (preg_match('/[^a-z0-9_]+/i', $_POST['table_prefix'])) {
219
    // contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
220
    set_error('Only characters a-z, A-Z, 0-9 and _ allowed in table_prefix.', 'table_prefix');
221
} else {
222
    $table_prefix = $_POST['table_prefix'];
223
}
224

    
225
$install_tables = true;
226
// Begin website title code
227
// Get website title
228
if (!isset($_POST['website_title']) OR $_POST['website_title'] == '') {
229
    set_error('Please enter a website title', 'website_title');
230
} else {
231
    $website_title = add_slashes($_POST['website_title']);
232
}
233
// End website title code
234

    
235
// Begin admin user details code
236
$sClientIp = '';
237
// Get admin username
238
if (!isset($_POST['admin_username']) OR $_POST['admin_username'] == '') {
239
    set_error('Please enter a username for the Administrator account','admin_username');
240
} else {
241
    $admin_username = $_POST['admin_username'];
242
    $sClientIp = (isset($_SERVER['REMOTE_ADDR']))
243
                         ? $_SERVER['REMOTE_ADDR'] : '000.000.000.000';
244
    $iClientIp = ip2long($sClientIp);
245
    $sClientIp = long2ip(($iClientIp & ~65535));
246

    
247
}
248
// Get admin email and validate it
249
if (!isset($_POST['admin_email']) OR $_POST['admin_email'] == '') {
250
    set_error('Please enter an email for the Administrator account','admin_email');
251
} else {
252
    if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i', $_POST['admin_email'])) {
253
        $admin_email = $_POST['admin_email'];
254
    } else {
255
        set_error('Please enter a valid email address for the Administrator account','admin_email');
256
    }
257
}
258
// Get the two admin passwords entered, and check that they match
259
if (!isset($_POST['admin_password']) OR $_POST['admin_password'] == '') {
260
    set_error('Please enter a password for the Administrator account','admin_password');
261
} else {
262
    $admin_password = $_POST['admin_password'];
263
}
264
if (!isset($_POST['admin_repassword']) OR $_POST['admin_repassword'] == '') {
265
    set_error('Please make sure you re-enter the password for the Administrator account','admin_repassword');
266
} else {
267
    $admin_repassword = $_POST['admin_repassword'];
268
}
269
if ($admin_password != $admin_repassword) {
270
    set_error('Sorry, the two Administrator account passwords you entered do not match','admin_repassword');
271
}
272

    
273
$database_charset = 'utf8';
274
// End admin user details code
275

    
276
$getNewVersion = function () {
277
    $sVersionFile = file_get_contents(dirname(__DIR__).'/admin/interface/version.php');
278
    $sPattern = '=define\s*\(\'VERSION\'\,\s*\'([^\']*)\'=is';
279
    $sVersion = ((preg_match($sPattern, $sVersionFile, $aMatches)) ? $aMatches[1] : '???');
280
    return $sVersion;
281
};
282
// build name and content of the config file
283
$sFileMarker = '*** auto generated config file for '.$getNewVersion();
284
$config_filename = dirname(dirname(__FILE__)).'/config.php';
285
$config_content
286
    = '<?php'."\n"
287
    . '/*'."\n"
288
    . ' '.$sFileMarker."\n"
289
    . ' *** WebsiteBaker '.$getNewVersion()."\n"
290
    . ' *** created at '.date('Y-m-d h:i:s e')."\n"
291
    . ' */'."\n"
292
    . '// define(\'DEBUG\', false);'."\n"
293
    . 'define(\'DB_TYPE\', \'mysqli\');'."\n"
294
    . 'define(\'DB_HOST\', \''.$database_host.'\');'."\n"
295
    . 'define(\'DB_PORT\', \''.sprintf('%04d', $database_port).'\');'."\n"
296
    . 'define(\'DB_NAME\', \''.$database_name.'\');'."\n"
297
    . 'define(\'DB_USERNAME\', \''.$database_username.'\');'."\n"
298
    . 'define(\'DB_PASSWORD\', \''.$database_password.'\');'."\n"
299
    . 'define(\'DB_CHARSET\', \''.$database_charset.'\');'."\n"
300
    . 'define(\'TABLE_PREFIX\', \''.$table_prefix.'\');'."\n"
301
   . "\n"
302
    . 'define(\'WB_URL\', \''.$wb_url.'\'); '
303
    . '// no trailing slash or backslash!!'."\n"
304
    . 'define(\'ADMIN_DIRECTORY\', \'admin\'); '
305
    . '// no leading/trailing slash or backslash!! A simple directory name only!!'."\n";
306
unset($getNewVersion);
307
// Check if the file exists and is writable first.
308
$sMsg = '';
309
if (is_writable($config_filename)) {
310
    // try to write file
311
    if (file_put_contents($config_filename, $config_content) === false) {
312
        $sMsg = 'Cannot write to the configuration file <'.$config_filename.'>';
313
    }
314
} else {
315
    $sMsg = 'The configuration file <'.$config_filename.'> is missing or not writable.<br />'
316
          . 'Change its permissions so it is, then re-run step 4.';
317
}
318
if ($sMsg) { set_error($sMsg); } // if something gone wrong, break with message
319
// include config file to set constants
320
include_once($config_filename);
321
// now we can complete the config file
322
$config_content
323
    = "\n".'require_once __DIR__.\'/framework/initialize.php\';'."\n"
324
    . '// --- end of file ----------------------------------'."\n";
325
// no errorhandling needed. 15 lines before we already wrote to this file successful!
326
file_put_contents($config_filename, $config_content, FILE_APPEND);
327

    
328
// Define additional configuration constants
329
define('WB_PATH', dirname(dirname(__FILE__)));
330
define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY);
331
define('ADMIN_URL', WB_URL.'/'.ADMIN_DIRECTORY);
332
require(ADMIN_PATH.'/interface/version.php');
333
// *** initialize Exception handling
334
if(!function_exists('globalExceptionHandler')) {
335
    include(WB_PATH.'/framework/globalExceptionHandler.php');
336
}
337

    
338
// Try connecting to database
339
if (!file_exists(WB_PATH.'/framework/class.database.php')) {
340
    set_error('It appears the Absolute path that you entered is incorrect or file \'class.database.php\' is missing!');
341
}
342
include(WB_PATH.'/framework/class.database.php');
343
try {
344
    $database = new database();
345
} catch (DatabaseException $e) {
346
    $sMsg = 'Database host name, username and/or password incorrect.<br />MySQL Error:<br />'
347
          . $e->getMessage();
348
    set_error($sMsg);
349
}
350
if (!defined('WB_INSTALL_PROCESS')) {
351
    define ('WB_INSTALL_PROCESS', true);
352
}
353

    
354
/*****************************
355
Begin Create Database Tables
356
*****************************/
357
$sInstallDir = dirname(__FILE__);
358
if (is_readable($sInstallDir.'/install-struct.sql')) {
359
    if (! $database->SqlImport($sInstallDir.'/install-struct.sql', TABLE_PREFIX, false)) {
360
        set_error('unable to import \'install/install-struct.sql\'');
361
    }
362
} else {
363
    set_error('unable to read file \'install/install-struct.sql\'');
364
}
365
if (is_readable($sInstallDir.'/install-data.sql')) {
366
    if (! $database->SqlImport($sInstallDir.'/install-data.sql', TABLE_PREFIX, false )) {
367
        set_error('unable to import \'install/install-data.sql\'');
368
    }
369
} else {
370
    set_error('unable to read file \'install/install-data.sql\'');
371
}
372
$sql = // add settings from install input
373
'INSERT INTO `'.TABLE_PREFIX.'settings` (`name`, `value`) VALUES '
374
    .'(\'wb_version\', \''.VERSION.'\'),'
375
    .'(\'wb_revision\', \''.REVISION.'\'),'
376
    .'(\'wb_sp\', \''.SP.'\'),'
377
    .'(\'website_title\', \''.$website_title.'\'),'
378
    .'(\'default_language\', \''.$default_language.'\'),'
379
    .'(\'app_name\', \'wb-'.$session_rand.'\'),'
380
    .'(\'default_timezone\', \''.$default_timezone.'\'),'
381
    .'(\'operating_system\', \''.$operating_system.'\'),'
382
    .'(\'string_dir_mode\', \''.$dir_mode.'\'),'
383
    .'(\'string_file_mode\', \''.$file_mode.'\'),'
384
    .'(\'server_email\', \''.$admin_email.'\')';
385
if (! ($database->query($sql))) {
386
    $msg = $database->get_error();
387
    set_error('unable to write \'install presets\' into table \'settings\'<br />'.$msg);
388
}
389

    
390
$sql = // add the Admin user
391
     'INSERT INTO `'.TABLE_PREFIX.'users` SET '
392
    .    '`group_id`=1, '
393
    .    '`groups_id`=\'1\', '
394
    .    '`active`=\'1\', '
395
    .    '`username`=\''.$admin_username.'\', '
396
    .    '`password`=\''.md5($admin_password).'\', '
397
    .    '`remember_key`=\'\', '
398
    .    '`last_reset`=0, '
399
    .    '`display_name`=\'Administrator\', '
400
    .    '`email`=\''.$admin_email.'\', '
401
    .    '`timezone`=\''.$default_timezone.'\', '
402
    .    '`date_format`=\'M d Y\', '
403
    .    '`time_format`=\'g:i A\', '
404
    .    '`language`=\''.$default_language.'\', '
405
    .    '`home_folder`=\'\', '
406
    .    '`login_when`=\''.time().'\', '
407
    .    '`login_ip`=\''.$sClientIp.'\' '
408
    .    '';
409
if (! ($database->query($sql))) {
410
    set_error('unable to write Administrator account into table \'users\'');
411
}
412
/**********************
413
END OF TABLES IMPORT
414
**********************/
415

    
416
// initialize the system
417
include(WB_PATH.'/framework/initialize.php');
418

    
419
//$sSecMod = (defined('SECURE_FORM_MODULE') && SECURE_FORM_MODULE != '') ? '.'.SECURE_FORM_MODULE : '';
420
//$sSecMod = WB_PATH.'/framework/SecureForm'.$sSecMod.'.php';
421
//require_once($sSecMod);
422

    
423
require_once(WB_PATH.'/framework/class.admin.php');
424
/***********************
425
// Dummy class to allow modules' install scripts to call $admin->print_error
426
***********************/
427
class admin_dummy extends admin
428
{
429
    public $error='';
430
    public function print_error($message, $link = 'index.php', $auto_footer = true)
431
    {
432
        $this->error=$message;
433
    }
434
}
435

    
436
// Include WB functions file
437
require_once(WB_PATH.'/framework/functions.php');
438

    
439
require_once(WB_PATH.'/framework/Login.php');
440
// Include the PclZip class file (thanks to
441
require_once(WB_PATH.'/include/pclzip/pclzip.lib.php');
442

    
443
$admin = new admin_dummy('Start','',false,false);
444

    
445
// Load addons into DB
446
$dirs['modules']   = WB_PATH.'/modules/';
447
$dirs['templates'] = WB_PATH.'/templates/';
448
$dirs['languages'] = WB_PATH.'/languages/';
449

    
450
foreach ($dirs as $type => $dir) {
451
    if ($handle = opendir($dir)) {
452
        while (false !== ($file = readdir($handle))) {
453
            if ($file != '' AND substr($file, 0, 1) != '.' AND $file != 'admin.php' AND $file != 'index.php') {
454
                // Get addon type
455
                if ($type == 'modules') {
456
                    load_module($dir.'/'.$file, true);
457
                    // Pretty ugly hack to let modules run $admin->set_error
458
                    // See dummy class definition admin_dummy above
459
                    if ($admin->error!='') {
460
                        set_error($admin->error);
461
                    }
462
                } elseif ($type == 'templates') {
463
                    load_template($dir.'/'.$file);
464
                } elseif ($type == 'languages') {
465
                    load_language($dir.'/'.$file);
466
                }
467
            }
468
        }
469
    closedir($handle);
470
    }
471
}
472
// Check if there was a database error
473
if ($database->is_error()) {
474
    set_error($database->get_error());
475
}
476

    
477
$ThemeUrl = WB_URL.$admin->correct_theme_source('warning.html');
478
// Setup template object, parse vars to it, then parse it
479
$ThemePath = realpath(WB_PATH.$admin->correct_theme_source('login.htt'));
480

    
481
// Log the user in and go to Website Baker Administration
482
$thisApp = new Login(
483
        array(
484
                "MAX_ATTEMPS" => "50",
485
                "WARNING_URL" => $ThemeUrl."/warning.html",
486
                "USERNAME_FIELDNAME" => 'admin_username',
487
                "PASSWORD_FIELDNAME" => 'admin_password',
488
                "REMEMBER_ME_OPTION" => false,
489
                "MIN_USERNAME_LEN" => "2",
490
                "MIN_PASSWORD_LEN" => "3",
491
                "MAX_USERNAME_LEN" => "30",
492
                "MAX_PASSWORD_LEN" => "30",
493
                'LOGIN_URL' => ADMIN_URL."/login/index.php",
494
                'DEFAULT_URL' => ADMIN_URL."/start/index.php",
495
                'TEMPLATE_DIR' => $ThemePath,
496
                'TEMPLATE_FILE' => 'login.htt',
497
                'FRONTEND' => false,
498
                'FORGOTTEN_DETAILS_APP' => ADMIN_URL."/login/forgot/index.php",
499
                'USERS_TABLE' => TABLE_PREFIX."users",
500
                'GROUPS_TABLE' => TABLE_PREFIX."groups",
501
        )
502
);
(8-8/9)