Project

General

Profile

1
<?php
2
/**
3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18

    
19
/**
20
 * initialize.php
21
 *
22
 * @category     Core
23
 * @package      Core_Environment
24
 * @author       Werner v.d.Decken <wkl@isteam.de>
25
 * @copyright    Werner v.d.Decken <wkl@isteam.de>
26
 * @license      http://www.gnu.org/licenses/gpl.html   GPL License
27
 * @version      0.0.1
28
 * @revision     $Revision: 2070 $
29
 * @link         $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/initialize.php $
30
 * @lastmodified $Date: 2014-01-03 02:21:42 +0100 (Fri, 03 Jan 2014) $
31
 * @since        File replaced since 05.02.2013
32
 * @description  set the basic environment to run WebsiteBaker
33
 */
34

    
35
/* *** define some helper functions *** */
36
/**
37
 * sanitize $_SERVER['HTTP_REFERER']
38
 * @param string $sWbUrl qualified startup URL of current application
39
 */
40
	function initSanitizeHttpReferer($sWbUrl) {
41
		$sTmpReferer = '';
42
		if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != '') {
43
			$sTmpReferer = $_SERVER['HTTP_REFERER'];
44
			$aRefUrl = parse_url($_SERVER['HTTP_REFERER']);
45
			if ($aRefUrl !== false) {
46
				$aRefUrl['host'] = isset($aRefUrl['host']) ? $aRefUrl['host'] : '';
47
				$aRefUrl['path'] = isset($aRefUrl['path']) ? $aRefUrl['path'] : '';
48
				$aRefUrl['fragment'] = isset($aRefUrl['fragment']) ? '#'.$aRefUrl['fragment'] : '';
49
				$aWbUrl = parse_url($sWbUrl);
50
				if ($aWbUrl !== false) {
51
					$aWbUrl['host'] = isset($aWbUrl['host']) ? $aWbUrl['host'] : '';
52
					$aWbUrl['path'] = isset($aWbUrl['path']) ? $aWbUrl['path'] : '';
53
					if (strpos($aRefUrl['host'].$aRefUrl['path'],
54
							   $aWbUrl['host'].$aWbUrl['path']) !== false) {
55
						$aRefUrl['path'] = preg_replace('#^'.$aWbUrl['path'].'#i', '', $aRefUrl['path']);
56
						$sTmpReferer = $sWbUrl.$aRefUrl['path'].$aRefUrl['fragment'];
57
					}
58
					unset($aWbUrl);
59
				}
60
				unset($aRefUrl);
61
			}
62
		}
63
		$_SERVER['HTTP_REFERER'] = $sTmpReferer;
64
	}
65
/**
66
 * Set constants for system/install values
67
 * @throws RuntimeException
68
 */
69
	function initSetInstallPathConstants() {
70
		if(!defined('DEBUG')){ define('DEBUG', false); } // normaly set in config file
71
		if(!defined('ADMIN_DIRECTORY')){ define('ADMIN_DIRECTORY', 'admin'); }
72
		if(!preg_match('/xx[a-z0-9_][a-z0-9_\-\.]+/i', 'xx'.ADMIN_DIRECTORY)) {
73
			throw new RuntimeException('Invalid admin-directory: ' . ADMIN_DIRECTORY);
74
		}
75
		if(!defined('WB_PATH')){ define('WB_PATH', dirname(dirname(__FILE__))); }
76
		if(!defined('ADMIN_URL')){ define('ADMIN_URL', rtrim(WB_URL, '/\\').'/'.ADMIN_DIRECTORY); }
77
		if(!defined('ADMIN_PATH')){ define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY); }
78
		if(!defined('WB_REL')){
79
			$x1 = parse_url(WB_URL);
80
			define('WB_REL', (isset($x1['path']) ? $x1['path'] : ''));
81
		}
82
		if(!defined('ADMIN_REL')){ define('ADMIN_REL', WB_REL.'/'.ADMIN_DIRECTORY); }
83
		if(!defined('DOCUMENT_ROOT')) {
84
			define('DOCUMENT_ROOT', preg_replace('/'.preg_quote(str_replace('\\', '/', WB_REL), '/').'$/', '', str_replace('\\', '/', WB_PATH)));
85
			$_SERVER['DOCUMENT_ROOT'] = DOCUMENT_ROOT;
86
		}
87
		if(!defined('TMP_PATH')){ define('TMP_PATH', WB_PATH.'/temp'); }
88
	}
89
/**
90
 * checkValidCaller
91
 * @param array $aCaller list of allowed scripts
92
 * @return true || Exception
93
 * @throws RuntimeException
94
 * @description test if acctual file is called from one of the given list
95
 */
96
	function initCheckValidCaller(array $aCaller)
97
	{
98
        return true;
99
		$x = debug_backtrace();
100
		if(sizeof($x) == 0) {
101
			return true;
102
		}
103
		$sPattern = '/('.str_replace('#', '|', preg_quote(implode('#', $aCaller), '/')).')$/si';
104
		foreach($x as $aStep) {
105
			// define the scripts which can read the configuration
106
			if(preg_match($sPattern, $aStep['file'])) {
107
				return true;
108
			}
109
		}
110
		throw new RuntimeException('illegal file request!');
111
	}
112
/**
113
 * Read DB settings from configuration file
114
 * @return array
115
 * @throws RuntimeException
116
 * 
117
 */
118
	function initReadSetupFile()
119
	{
120
	// check for valid file request. Becomes more stronger in next version
121
		initCheckValidCaller(array('save.php','index.php','config.php','upgrade-script.php'));
122
		$aCfg = array();
123

    
124
		$sSetupFile = dirname(dirname(__FILE__)).'/setup.ini.php';
125
		if(is_readable($sSetupFile)) {
126
			$aCfg = parse_ini_file($sSetupFile, true);
127
			foreach($aCfg['Constants'] as $key=>$value) {
128
				switch($key):
129
					case 'DEBUG':
130
						$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
131
						if(!defined('DEBUG')) { define('DEBUG', $value); }
132
						break;
133
					case 'WB_URL': // << case is set deprecated
134
					case 'AppUrl':
135
						$value = trim(str_replace('\\', '/', $value), '/'); 
136
						if(!defined('WB_URL')) { define('WB_URL', $value); }
137
						break;
138
					case 'ADMIN_DIRECTORY': // << case is set deprecated
139
					case 'AcpDir':
140
						$value = trim(str_replace('\\', '/', $value), '/'); 
141
						if(!defined('ADMIN_DIRECTORY')) { define('ADMIN_DIRECTORY', $value); }
142
						break;
143
					default:
144
						if(!defined($key)) { define($key, $value); }
145
						break;
146
				endswitch;
147
			}
148
		}
149
		return $aCfg;
150
//		throw new RuntimeException('unable to read setup.ini.php');
151
	}
152
 /**
153
 * GetDbConnectData
154
 * @param array $aCfg
155
 * @param string $sDbConnectType  can be 'url' or 'dsn'
156
 * @return array
157
 *
158
 */
159
	function initGetDbConnectData(array $aCfg, $sDbConnectType = 'url')
160
	{
161
		if(defined('DB_TYPE'))
162
		{
163
		// import constants for compatibility reasons
164
			$db = array();
165
			if(defined('DB_TYPE'))      { $db['type']         = DB_TYPE; }
166
			if(defined('DB_USERNAME'))  { $db['user']         = DB_USERNAME; }
167
			if(defined('DB_PASSWORD'))  { $db['pass']         = DB_PASSWORD; }
168
			if(defined('DB_HOST'))      { $db['host']         = DB_HOST; }
169
			if(defined('DB_PORT'))      { $db['port']         = DB_PORT; }
170
			if(defined('DB_NAME'))      { $db['name']         = DB_NAME; }
171
			if(defined('DB_CHARSET'))   { $db['charset']      = DB_CHARSET; }
172
			if(defined('TABLE_PREFIX')) { $db['table_prefix'] = TABLE_PREFIX; }
173
			$aCfg['DataBase'] = $db;
174
		}
175
		// sanitize values
176
		$db = $aCfg['DataBase'];
177
		$db['type'] = isset($db['type']) ? $db['type'] : 'mysql';
178
		$db['user'] = isset($db['user']) ? $db['user'] : 'foo';
179
		$db['pass'] = isset($db['pass']) ? $db['pass'] : 'bar';
180
		$db['host'] = isset($db['host']) ? $db['host'] : 'localhost';
181
		$db['port'] = isset($db['port']) ? $db['port'] : '3306';
182
		$db['port'] = ($db['port'] != '3306') ? $db['port'] : '';
183
		$db['name'] = isset($db['name']) ? $db['name'] : 'dummy';
184
		$db['charset'] = isset($db['charset']) ? trim($db['charset']) : 'utf8';
185
		$db['table_prefix'] = (isset($db['table_prefix']) ? $db['table_prefix'] : '');
186
		if(!defined('TABLE_PREFIX')) { define('TABLE_PREFIX', $db['table_prefix']); }
187
		if($sDbConnectType == 'dsn') {
188
		// build dsn to connect
189
			$aRetval[0] = $db['type'].':dbname='.$db['name'].';host='.$db['host'].';'
190
						. ($db['port'] != '' ? 'port='.(int)$db['port'].';' : '');
191
			$aRetval[1] = array('CHARSET' => $db['charset'], 'TABLE_PREFIX' => $db['table_prefix']);
192
			$aRetval[2] = array( 'user' => $db['user'], 'pass' => $db['pass']);
193
		}else { 
194
		// build url to connect
195
			$aRetval[0] = $db['type'].'://'.$db['user'].':'.$db['pass'].'@'
196
						. $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name']
197
						. '?Charset='.$db['charset'].'&TablePrefix='.$db['table_prefix'];
198
		}
199
		return $aRetval;
200
	}
201

    
202
/* ***************************************************************************************
203
 * Start initialization                                                                  *
204
 ****************************************************************************************/
205
// initialize debug evaluation values ---	
206
	$starttime = array_sum(explode(" ",microtime()));
207
	$iPhpDeclaredClasses = sizeof(get_declared_classes());
208
	$sDbConnectType = 'url'; // depending from class WbDatabase it can be 'url' or 'dsn'
209
// PHP less then 5.3.2 is prohibited ---
210
	if (version_compare(PHP_VERSION, '5.3.2', '<')) {
211
		$sMsg = '<p style="color: #ff0000;">WebsiteBaker is not able to run with PHP-Version less then 5.3.2!!<br />'
212
		      . 'Please change your PHP-Version to any kind from 5.3.2 and up!<br />'
213
		      . 'If you have problems to solve that, ask your hosting provider for it.<br  />'
214
		      . 'The very best solution is the use of PHP-5.4 and up</p>';
215
		die($sMsg);
216
	}
217
// disable all kind of magic_quotes in PHP versions before 5.4 ---
218
	if (function_exists('get_magic_quotes_gpc') && filter_var(get_magic_quotes_gpc(), FILTER_VALIDATE_BOOLEAN)) {
219
		$sMsg = '<p style="color: #ff0000;">WebsiteBaker is not able to run with magic_quotes=on!!<br />'
220
		      . 'Please change your PHP-ini or add a _htaccess file to switch this setting to off!<br />'
221
		      . 'If you have problems to solve that, ask your hosting provider for it.<br  />'
222
		      . 'The very best solution is the use of PHP-5.4 and up</p>';
223
		die($sMsg);
224
	}
225
// load configuration ---
226
	$aCfg = initReadSetupFile();
227
// sanitize $_SERVER['HTTP_REFERER'] ---
228
	initSetInstallPathConstants();
229
	initSanitizeHttpReferer(WB_URL);
230
// register WB basic autoloader ---
231
	$sTmp = dirname(__FILE__).'/WbAutoloader.php';
232
	if(!class_exists('WbAutoloader')){ 
233
		include($sTmp);
234
	}
235
	WbAutoloader::doRegister(array(ADMIN_DIRECTORY=>'a', 'modules'=>'m', 'templates'=>'t', 'include'=>'i'));
236
// instantiate and initialize adaptor for temporary registry replacement ---
237
    $oReg = WbAdaptor::getInstance();
238
	$oReg->getWbConstants();
239
// register TWIG autoloader ---
240
	$sTmp = dirname(dirname(__FILE__)).'/include/Sensio/Twig/lib/Twig/Autoloader.php';
241
	if(!class_exists('Twig_Autoloader')) { 
242
		include($sTmp); 
243
	}
244
	Twig_Autoloader::register();
245
// register PHPMailer autoloader ---
246
    if (!function_exists('PHPMailerAutoload')) {
247
        require($oReg->AppPath.'include/phpmailer/PHPMailerAutoload.php');
248
    }
249
// aktivate exceptionhandler ---
250
	if(!function_exists('globalExceptionHandler')) {
251
		include(dirname(__FILE__).'/globalExceptionHandler.php');
252
	}
253
// ---------------------------
254
// get Database connection data from configuration
255
	$aSqlData = initGetDbConnectData($aCfg, $sDbConnectType);
256
// Create global database instance ---
257
	$oDb = $database = WbDatabase::getInstance();
258
	if($sDbConnectType == 'dsn') {
259
		$bTmp = $oDb->doConnect($aSqlData[0], $aSqlData[1]['user'], $aSqlData[1]['pass'], $aSqlData[2]);
260
	}else {
261
		$bTmp = $oDb->doConnect($aSqlData[0]);
262
	}
263
// remove critical data from memory
264
	unset($aSqlData, $aCfg);
265

    
266
	if(!defined('TABLE_PREFIX')) { define('TABLE_PREFIX', $oDb->TablePrefix); }
267

    
268
// load global settings from database and define global consts from ---
269
	$sql = 'SELECT `name`, `value` FROM `'.TABLE_PREFIX.'settings`';
270
	if(($oSettings = $database->query($sql))) {
271
		if(!$oSettings->numRows()) { throw new AppException('no settings found'); }
272
		while($aSetting = $oSettings->fetchRow(MYSQL_ASSOC)) {
273
			//sanitize true/false values
274
			$aSetting['value'] = ($aSetting['value'] == 'true' 
275
								  ? true 
276
								  : ($aSetting['value'] == 'false' 
277
									 ? false 
278
									 : $aSetting['value'])
279
								 );
280
			$sSettingName = strtoupper($aSetting['name']);
281
			switch($sSettingName):
282
				case 'STRING_FILE_MODE':
283
					$iTmp = ((intval(octdec($aSetting['value'])) & ~0111)|0600);
284
					if(!defined('OCTAL_FILE_MODE')) { define('OCTAL_FILE_MODE', $iTmp); }
285
					if(!defined('STRING_FILE_MODE')) { define('STRING_FILE_MODE', sprintf('0%03o', $iTmp)); }
286
					break;
287
				case 'STRING_DIR_MODE':
288
					$iTmp = (intval(octdec($aSetting['value'])) |0711);
289
					if(!defined('OCTAL_DIR_MODE')) { define('OCTAL_DIR_MODE', $iTmp); }
290
					if(!defined('STRING_DIR_MODE')) { define('STRING_DIR_MODE', sprintf('0%03o', $iTmp)); }
291
					break;
292
				case 'PAGES_DIRECTORY':
293
					// sanitize pages_directory
294
					$sTmp = trim($aSetting['value'], '/');
295
					$sTmp = ($sTmp == '' ? '' : '/'.$sTmp);
296
					if(!defined('PAGES_DIRECTORY')) { define('PAGES_DIRECTORY', $sTmp); }
297
					break;
298
				default: // make global const from setting
299
					if(!defined($sSettingName)) { define($sSettingName, $aSetting['value']); }
300
					break;
301
			endswitch;
302
		}
303
	}else { throw new AppException($database->get_error()); }
304
// set error-reporting from loaded settings ---
305
	if(intval(ER_LEVEL) > 0 ) {
306
		error_reporting(ER_LEVEL);
307
		if( intval(ini_get ( 'display_errors' )) == 0 ) {
308
			ini_set('display_errors', 1);
309
		}
310
	}
311
// Start a session ---
312
	if(!defined('SESSION_STARTED')) {
313
		session_name(APP_NAME.'_session_id');
314
		@session_start();
315
		define('SESSION_STARTED', true);
316
	}
317
// get/set server timezone ---
318
	if(!defined('SERVER_TIMEZONE')) { define('SERVER_TIMEZONE', "UTC"); }
319
	date_default_timezone_set( SERVER_TIMEZONE );
320
	if(!defined('MAX_TIME')) { define('MAX_TIME', (pow(2, 31)-1)); } // 32-Bit Timestamp of 19 Jan 2038 03:14:07 GMT
321
	$sTmp = (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] != '') ? $_SERVER['HTTP_DNT'] : '0';
322
	if(!defined('DO_NOT_TRACK')) { define('DO_NOT_TRACK', ($sTmp[0] == '1')); }
323
// get/set users timezone ---
324
	if(!defined('TIMEZONE')) { define('TIMEZONE', (isset($_SESSION['TIMEZONE']) ? $_SESSION['TIMEZONE'] : DEFAULT_TIMEZONE)); }
325
	if(!defined('DATE_FORMAT')) { define('DATE_FORMAT', (isset($_SESSION['DATE_FORMAT']) ? $_SESSION['DATE_FORMAT'] : DEFAULT_DATE_FORMAT)); }
326
	if(!defined('TIME_FORMAT')) { define('TIME_FORMAT', (isset($_SESSION['TIME_FORMAT']) ? $_SESSION['TIME_FORMAT'] : DEFAULT_TIME_FORMAT)); }
327
// set Theme directory --- 
328
	if(!defined('THEME_URL')) { define('THEME_URL',  WB_URL.'/templates/'.DEFAULT_THEME); }
329
	if(!defined('THEME_PATH')) { define('THEME_PATH', WB_PATH.'/templates/'.DEFAULT_THEME); }
330
	if(!defined('THEME_REL')) { define('THEME_REL',  WB_REL.'/templates/'.DEFAULT_THEME); }
331
// extended wb editor settings
332
	if(!defined('EDIT_ONE_SECTION')) { define('EDIT_ONE_SECTION', false); }
333
	if(!defined('EDITOR_WIDTH')) { define('EDITOR_WIDTH', 0); }
334
// define form security class and preload it ---
335
	$sSecMod = (defined('SECURE_FORM_MODULE') && SECURE_FORM_MODULE != '') ? '.'.SECURE_FORM_MODULE : '';
336
	$sSecMod = WB_PATH.'/framework/SecureForm'.$sSecMod.'.php';
337
	require_once($sSecMod);
338
// *** begin deprecated part *************************************************************
339
// load settings for use in Captch and ASP module
340
	if (!defined('WB_INSTALL_PROCESS') && !defined('ENABLED_CAPTCHA')) {
341
		$sql = 'SELECT * FROM `'.TABLE_PREFIX.'mod_captcha_control`';
342
		// request settings from database
343
		if(($oSettings = $database->query($sql))) {
344
			if(($aSetting = $oSettings->fetchRow(MYSQL_ASSOC))) {
345
				define('ENABLED_CAPTCHA', ($aSetting['enabled_captcha'] == '1'));
346
				define('ENABLED_ASP', ($aSetting['enabled_asp'] == '1'));
347
				define('CAPTCHA_TYPE', $aSetting['captcha_type']);
348
				define('ASP_SESSION_MIN_AGE', (int)$aSetting['asp_session_min_age']);
349
				define('ASP_VIEW_MIN_AGE', (int)$aSetting['asp_view_min_age']);
350
				define('ASP_INPUT_MIN_AGE', (int)$aSetting['asp_input_min_age']);
351
			}
352
		}
353
	}
354
	if(defined('ENABLED_ASP') && ENABLED_ASP && !isset($_SESSION['session_started'])) {
355
		$_SESSION['session_started'] = time();
356
	}
357
// *** end of deprecated part ************************************************************
358
// get user language ---
359
    $sRequestMethod = '_'.strtoupper($_SERVER['REQUEST_METHOD']);
360
    // check if get/post value is available
361
    $sTempLanguage = (isset(${$sRequestMethod}['lang']) ? ${$sRequestMethod}['lang'] : '');
362
    // validate language code
363
    if (preg_match('/^[a-z]{2}$/si', $sTempLanguage)) {
364
    // if there's valid get/post
365
        define('LANGUAGE', strtoupper($sTempLanguage));
366
    } else {
367
        if (!defined('LANGUAGE')) {
368
            if(isset($_SESSION['LANGUAGE']) && $_SESSION['LANGUAGE']) {
369
            // if there's valid session value
370
                define('LANGUAGE', $_SESSION['LANGUAGE']);
371
            } else {
372
            // otherwise set to default
373
                define('LANGUAGE', DEFAULT_LANGUAGE);
374
            }
375
        }
376
    }
377
    $_SESSION['LANGUAGE'] = LANGUAGE;
378
// activate translations / load language definitions
379
/** begin of deprecated part || will be replaced by class Translate **/	
380
// Load Language file
381
	if(!file_exists(WB_PATH.'/languages/'.LANGUAGE.'.php')) {
382
		$sMsg = 'Error loading language file '.LANGUAGE.', please check configuration';
383
		throw new AppException($sMsg);
384
	} else {
385
	// include language file
386
		require_once(WB_PATH.'/languages/'.LANGUAGE.'.php');
387
	}
388
/** end of deprecated part **/
389
// instantiate and initialize adaptor for temporary registry replacement ---
390
	$oReg->getWbConstants();
391
// load and activate new global translation table
392
	Translate::getInstance()->initialize('en',
393
										 (defined('DEFAULT_LANGUAGE') ? DEFAULT_LANGUAGE : ''), 
394
										 (defined('LANGUAGE') ? LANGUAGE : ''),
395
										 'WbOldStyle',
396
										 (Translate::CACHE_DISABLED|Translate::KEEP_MISSING)
397
//										 (DEBUG ? Translate::CACHE_DISABLED|Translate::KEEP_MISSING : 0)
398
										);
399
	if(!class_exists('PasswordHash', false)) { include(WB_PATH.'/include/phpass/PasswordHash.php'); }
400
	$oPass = Password::getInstance(new PasswordHash(Password::CRYPT_LOOPS_DEFAULT, Password::HASH_TYPE_AUTO));
401
	if(defined('PASSWORD_CRYPT_LOOPS')) { $oPass->setIteration(PASSWORD_CRYPT_LOOPS); }
402
	if(defined('PASSWORD_HASH_TYPES'))  { $oPass->setHashType(PASSWORD_HASH_TYPES); }
403
// *** END OF FILE ***********************************************************************
404
 
(34-34/36)