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: 1900 $
29
 * @link         $HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/initialize.php $
30
 * @lastmodified $Date: 2013-04-18 22:05:18 +0200 (Thu, 18 Apr 2013) $
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 SanitizeHttpReferer($sWbUrl = WB_URL) {
41
		$sTmpReferer = '';
42
		if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != '') {
43
			$aRefUrl = parse_url($_SERVER['HTTP_REFERER']);
44
			if ($aRefUrl !== false) {
45
				$aRefUrl['host'] = isset($aRefUrl['host']) ? $aRefUrl['host'] : '';
46
				$aRefUrl['path'] = isset($aRefUrl['path']) ? $aRefUrl['path'] : '';
47
				$aRefUrl['fragment'] = isset($aRefUrl['fragment']) ? '#'.$aRefUrl['fragment'] : '';
48
				$aWbUrl = parse_url(WB_URL);
49
				if ($aWbUrl !== false) {
50
					$aWbUrl['host'] = isset($aWbUrl['host']) ? $aWbUrl['host'] : '';
51
					$aWbUrl['path'] = isset($aWbUrl['path']) ? $aWbUrl['path'] : '';
52
					if (strpos($aRefUrl['host'].$aRefUrl['path'],
53
							   $aWbUrl['host'].$aWbUrl['path']) !== false) {
54
						$aRefUrl['path'] = preg_replace('#^'.$aWbUrl['path'].'#i', '', $aRefUrl['path']);
55
						$sTmpReferer = WB_URL.$aRefUrl['path'].$aRefUrl['fragment'];
56
					}
57
					unset($aWbUrl);
58
				}
59
				unset($aRefUrl);
60
			}
61
		}
62
		$_SERVER['HTTP_REFERER'] = $sTmpReferer;
63
	}
64
/**
65
 * Set constants for system/install values
66
 * @throws RuntimeException
67
 */
68
	function SetInstallPathConstants() {
69
		if(!defined('DEBUG')){ define('DEBUG', false); } // normaly set in config file
70
		if(!defined('ADMIN_DIRECTORY')){ define('ADMIN_DIRECTORY', 'admin'); }
71
		if(!preg_match('/xx[a-z0-9_][a-z0-9_\-\.]+/i', 'xx'.ADMIN_DIRECTORY)) {
72
			throw new RuntimeException('Invalid admin-directory: ' . ADMIN_DIRECTORY);
73
		}
74
		if(!defined('WB_PATH')){ define('WB_PATH', dirname(dirname(__FILE__))); }
75
		if(!defined('ADMIN_URL')){ define('ADMIN_URL', WB_URL.'/'.ADMIN_DIRECTORY); }
76
		if(!defined('ADMIN_PATH')){ define('ADMIN_PATH', WB_PATH.'/'.ADMIN_DIRECTORY); }
77
		if(!defined('WB_REL')){
78
			$x1 = parse_url(WB_URL);
79
			define('WB_REL', (isset($x1['path']) ? $x1['path'] : ''));
80
		}
81
		if(!defined('ADMIN_REL')){ define('ADMIN_REL', WB_REL.'/'.ADMIN_DIRECTORY); }
82
		if(!defined('DOCUMENT_ROOT')) {
83
			
84
			define('DOCUMENT_ROOT', preg_replace('/'.preg_quote(WB_REL, '/').'$/', '', WB_PATH));
85
		}
86
		if(!defined('TMP_PATH')){ define('TMP_PATH', WB_PATH.'/temp'); }
87
	}
88
/**
89
 * Read DB settings from configuration file
90
 * @return string
91
 * @throws RuntimeException
92
 * 
93
 */
94
	function readConfiguration($sRetvalType = 'url') {
95
		// check for valid file request. Becomes more stronger in next version
96
		$x = debug_backtrace();
97
		$bValidRequest = false;
98
		if(sizeof($x) != 0) {
99
			foreach($x as $aStep) {
100
				// define the scripts which can read the configuration
101
				if(preg_match('/(save.php|index.php|config.php|upgrade-script.php)$/si', $aStep['file'])) {
102
					$bValidRequest = true;
103
					break;
104
				}
105
			}
106
		} else {
107
			$bValidRequest = true;
108
		}
109
		if(!$bValidRequest) {
110
			throw new RuntimeException('illegal function request!'); 
111
		}
112
		$aRetval = array();
113
		$sSetupFile = dirname(dirname(__FILE__)).'/setup.ini.php';
114
		if(is_readable($sSetupFile)) {
115
			$aCfg = parse_ini_file($sSetupFile, true);
116
			foreach($aCfg['Constants'] as $key=>$value) {
117
				switch($key):
118
					case 'DEBUG':
119
						$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
120
						if(!defined('DEBUG')) { define('DEBUG', $value); }
121
						break;
122
					case 'WB_URL':
123
					case 'AppUrl':
124
						$value = trim(str_replace('\\', '/', $value), '/'); 
125
						if(!defined('WB_URL')) { define('WB_URL', $value); }
126
						break;
127
					case 'ADMIN_DIRECTORY':
128
					case 'AcpDir':
129
						$value = trim(str_replace('\\', '/', $value), '/'); 
130
						if(!defined('ADMIN_DIRECTORY')) { define('ADMIN_DIRECTORY', $value); }
131
						break;
132
					default:
133
						if(!defined($key)) { define($key, $value); }
134
						break;
135
				endswitch;
136
			}
137
			$db = $aCfg['DataBase'];
138
			$db['type'] = isset($db['type']) ? $db['type'] : 'mysql';
139
			$db['user'] = isset($db['user']) ? $db['user'] : 'foo';
140
			$db['pass'] = isset($db['pass']) ? $db['pass'] : 'bar';
141
			$db['host'] = isset($db['host']) ? $db['host'] : 'localhost';
142
			$db['port'] = isset($db['port']) ? $db['port'] : '3306';
143
			$db['port'] = ($db['port'] != '3306') ? $db['port'] : '';
144
			$db['name'] = isset($db['name']) ? $db['name'] : 'dummy';
145
			$db['charset'] = isset($db['charset']) ? trim($db['charset']) : '';
146
			$db['table_prefix'] = (isset($db['table_prefix']) ? $db['table_prefix'] : '');
147
			if(!defined('TABLE_PREFIX')) { define('TABLE_PREFIX', $db['table_prefix']); }
148
			if($sRetvalType == 'dsn') {
149
				$aRetval[0] = $db['type'].':dbname='.$db['name'].';host='.$db['host'].';'
150
				            . ($db['port'] != '' ? 'port='.(int)$db['port'].';' : '');
151
				$aRetval[1] = array('CHARSET' => $db['charset'], 'TABLE_PREFIX' => $db['table_prefix']);
152
				$aRetval[2] = array( 'user' => $db['user'], 'pass' => $db['pass']);
153
			}else { // $sRetvalType == 'url'
154
				$aRetval[0] = $db['type'].'://'.$db['user'].':'.$db['pass'].'@'
155
				            . $db['host'].($db['port'] != '' ? ':'.$db['port'] : '').'/'.$db['name']
156
				            . '?Charset='.$db['charset'].'&TablePrefix='.$db['table_prefix'];
157
			}
158
			unset($db, $aCfg);
159
			return $aRetval;
160
		}
161
		throw new RuntimeException('unable to read setup.ini.php');
162
	}
163
/* ***************************************************************************************
164
 * Start initialization                                                                  *
165
 ****************************************************************************************/
166
// initialize debug evaluation values ---	
167
	$sDbConnectType = 'url'; // depending from class WbDatabase it can be 'url' or 'dsn'
168
	$starttime = array_sum(explode(" ",microtime()));
169
	$iPhpDeclaredClasses = sizeof(get_declared_classes());
170
// disable all kind of magic_quotes in PHP versions before 5.4 ---
171
	if(version_compare(PHP_VERSION, '5.4.0', '<')) {
172
		if(get_magic_quotes_gpc() || get_magic_quotes_runtime()) {
173
			@ini_set('magic_quotes_sybase', 0);
174
			@ini_set('magic_quotes_gpc', 0);
175
			@ini_set('magic_quotes_runtime', 0);
176
		}
177
	}
178
// load db configuration ---
179
	if(defined('DB_TYPE')) {
180
		$sTmp = ($sTmp=((defined('DB_PORT') && DB_PORT !='') ? DB_PORT : '')) ? ':'.$sTmp : '';
181
		$sTmp = DB_TYPE.'://'.DB_USERNAME.':'.DB_PASSWORD.'@'.DB_HOST.$sTmp.'/'.DB_NAME.'?Charset=';
182
		$sTmp .= (defined('DB_CHARSET') ? DB_CHARSET : '').'&TablePrefix='.TABLE_PREFIX;
183
		$aSqlData = array( 0 => $sTmp);
184
	}else {
185
		$aSqlData = readConfiguration($sDbConnectType);
186
	}
187
// sanitize $_SERVER['HTTP_REFERER'] ---
188
	SanitizeHttpReferer(WB_URL); 
189
	SetInstallPathConstants();
190
// define constant systemenvironment settings ---
191
	date_default_timezone_set('UTC');
192
	if(!defined('MAX_TIME')) { define('MAX_TIME', (pow(2, 31)-1)); } // 32-Bit Timestamp of 19 Jan 2038 03:14:07 GMT
193
	$sTmp = (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] != '') ? $_SERVER['HTTP_DNT'] : '0';
194
	if(!defined('DO_NOT_TRACK')) { define('DO_NOT_TRACK', ($sTmp[0] == '1')); }
195
// register WB basic autoloader ---
196
	$sTmp = dirname(__FILE__).'/WbAutoloader.php';
197
	if(!class_exists('WbAutoloader')){ 
198
		include($sTmp);
199
	}
200
	WbAutoloader::doRegister(array(ADMIN_DIRECTORY=>'a', 'modules'=>'m'));
201
// register TWIG autoloader ---
202
	$sTmp = dirname(dirname(__FILE__)).'/include/Sensio/Twig/lib/Twig/Autoloader.php';
203
	if(!class_exists('Twig_Autoloader')) { 
204
		include($sTmp); 
205
	}
206
	Twig_Autoloader::register();
207
// aktivate exceptionhandler ---
208
	if(!function_exists('globalExceptionHandler')) {
209
		include(dirname(__FILE__).'/globalExceptionHandler.php');
210
	}
211
// activate secure PasswordHashes
212
	if(!class_exists('PasswordHash')) {
213
		include(dirname(dirname(__FILE__)).'/include/phpass/PasswordHash.php'); 
214
	}
215
// ---------------------------
216
// Create global database instance ---
217
	$database = WbDatabase::getInstance();
218
	if($sDbConnectType == 'dsn') {
219
		$bTmp = $database->doConnect($aSqlData[0], $aSqlData[1]['user'], $aSqlData[1]['pass'], $aSqlData[2]);
220
	}else {
221
		$bTmp = $database->doConnect($aSqlData[0]);
222
	}
223
	unset($aSqlData);
224
// load global settings from database and define global consts from ---
225
	$sql = 'SELECT `name`, `value` FROM `'.TABLE_PREFIX.'settings`';
226
	if(($oSettings = $database->query($sql))) {
227
		if(!$oSettings->numRows()) { throw new AppException('no settings found'); }
228
		while($aSetting = $oSettings->fetchRow(MYSQL_ASSOC)) {
229
			//sanitize true/false values
230
			$aSetting['value'] = ($aSetting['value'] == 'true' 
231
								  ? true 
232
								  : ($aSetting['value'] == 'false' 
233
									 ? false 
234
									 : $aSetting['value'])
235
								 );
236
			$sSettingName = strtoupper($aSetting['name']);
237
			switch($sSettingName):
238
				case 'STRING_FILE_MODE':
239
					$iTmp = ((intval(octdec($aSetting['value'])) & ~0111)|0600);
240
					if(!defined('OCTAL_FILE_MODE')) { define('OCTAL_FILE_MODE', $iTmp); }
241
					if(!defined('STRING_FILE_MODE')) { define('STRING_FILE_MODE', sprintf('0%03o', $iTmp)); }
242
					break;
243
				case 'STRING_DIR_MODE':
244
					$iTmp = (intval(octdec($aSetting['value'])) |0711);
245
					if(!defined('OCTAL_DIR_MODE')) { define('OCTAL_DIR_MODE', $iTmp); }
246
					if(!defined('STRING_DIR_MODE')) { define('STRING_DIR_MODE', sprintf('0%03o', $iTmp)); }
247
					break;
248
				case 'PAGES_DIRECTORY':
249
					// sanitize pages_directory
250
					$sTmp = trim($aSetting['value'], '/');
251
					$sTmp = ($sTmp == '' ? '' : '/'.$sTmp);
252
					if(!defined('PAGES_DIRECTORY')) { define('PAGES_DIRECTORY', $sTmp); }
253
					break;
254
				default: // make global const from setting
255
					if(!defined($sSettingName)) { define($sSettingName, $aSetting['value']); }
256
					break;
257
			endswitch;
258
		}
259
	}else { throw new AppException($database->get_error()); }
260
// set error-reporting from loaded settings ---
261
	if(intval(ER_LEVEL) > 0 ) {
262
		error_reporting(ER_LEVEL);
263
		if( intval(ini_get ( 'display_errors' )) == 0 ) {
264
			ini_set('display_errors', 1);
265
		}
266
	}
267
// Start a session ---
268
	if(!defined('SESSION_STARTED')) {
269
		session_name(APP_NAME.'_session_id');
270
		@session_start();
271
		define('SESSION_STARTED', true);
272
	}
273
// get/set users timezone ---
274
	if(!defined('TIMEZONE')) { define('TIMEZONE', (isset($_SESSION['TIMEZONE']) ? $_SESSION['TIMEZONE'] : DEFAULT_TIMEZONE)); }
275
	if(!defined('DATE_FORMAT')) { define('DATE_FORMAT', (isset($_SESSION['DATE_FORMAT']) ? $_SESSION['DATE_FORMAT'] : DEFAULT_DATE_FORMAT)); }
276
	if(!defined('TIME_FORMAT')) { define('TIME_FORMAT', (isset($_SESSION['TIME_FORMAT']) ? $_SESSION['TIME_FORMAT'] : DEFAULT_TIME_FORMAT)); }
277
// set Theme directory --- 
278
	if(!defined('THEMA_URL')) { define('THEME_URL',  WB_URL.'/templates/'.DEFAULT_THEME); }
279
	if(!defined('THEME_PATH')) { define('THEME_PATH', WB_PATH.'/templates/'.DEFAULT_THEME); }
280
	if(!defined('THEME_REL')) { define('THEME_REL',  WB_REL.'/templates/'.DEFAULT_THEME); }
281
// extended wb editor settings
282
	if(!defined('EDIT_ONE_SECTION')) { define('EDIT_ONE_SECTION', false); }
283
	if(!defined('EDITOR_WIDTH')) { define('EDITOR_WIDTH', 0); }
284
// define form security class and preload it ---
285
	$sSecMod = (defined('SECURE_FORM_MODULE') && SECURE_FORM_MODULE != '') ? '.'.SECURE_FORM_MODULE : '';
286
	$sSecMod = WB_PATH.'/framework/SecureForm'.$sSecMod.'.php';
287
	require_once($sSecMod);
288
// *** begin deprecated part *************************************************************
289
// load settings for use in Captch and ASP module
290
	if (!defined('WB_INSTALL_PROCESS') && !defined('ENABLED_CAPTCHA')) {
291
		$sql = 'SELECT * FROM `'.TABLE_PREFIX.'mod_captcha_control`';
292
		// request settings from database
293
		if(($oSettings = $database->query($sql))) {
294
			if(($aSetting = $oSettings->fetchRow(MYSQL_ASSOC))) {
295
				define('ENABLED_CAPTCHA', ($aSetting['enabled_captcha'] == '1'));
296
				define('ENABLED_ASP', ($aSetting['enabled_asp'] == '1'));
297
				define('CAPTCHA_TYPE', $aSetting['captcha_type']);
298
				define('ASP_SESSION_MIN_AGE', (int)$aSetting['asp_session_min_age']);
299
				define('ASP_VIEW_MIN_AGE', (int)$aSetting['asp_view_min_age']);
300
				define('ASP_INPUT_MIN_AGE', (int)$aSetting['asp_input_min_age']);
301
			}
302
		}
303
	}
304
	if(defined('ENABLED_ASP') && ENABLED_ASP && !isset($_SESSION['session_started'])) {
305
		$_SESSION['session_started'] = time();
306
	}
307
// *** end of deprecated part ************************************************************
308
// get user language ---
309
	$sRequestMethod = '_'.strtoupper($_SERVER['REQUEST_METHOD']);
310
	// check if get/post value is available
311
	$sTempLanguage = (isset(${$sRequestMethod}['lang']) ? ${$sRequestMethod}['lang'] : '');
312
	// validate language code
313
	if(preg_match('/^[a-z]{2}$/si', $sTempLanguage)) {
314
	// if there's valid get/post
315
		define('LANGUAGE', strtoupper($sTempLanguage));
316
		$_SESSION['LANGUAGE']=LANGUAGE;
317
	}else {
318
		if(isset($_SESSION['LANGUAGE']) && $_SESSION['LANGUAGE']) {
319
		// if there's valid session value
320
			define('LANGUAGE', $_SESSION['LANGUAGE']);
321
		}else {
322
		// otherwise set to default
323
			define('LANGUAGE', DEFAULT_LANGUAGE);
324
		}
325
	}
326
// activate translations / load language definitions
327
/** begin of deprecated part || will be replaced by class Translate **/	
328
// Load Language file
329
	if(!file_exists(WB_PATH.'/languages/'.LANGUAGE.'.php')) {
330
		$sMsg = 'Error loading language file '.LANGUAGE.', please check configuration';
331
		throw new AppException($sMsg);
332
	} else {
333
	// include language file
334
		require_once(WB_PATH.'/languages/'.LANGUAGE.'.php');
335
	}
336
/** end of deprecated part **/
337
// instantiate and initialize adaptor for temporary registry replacement ---
338
	if(class_exists('WbAdaptor')) {
339
		WbAdaptor::getInstance()->getWbConstants();
340
	}
341
// load and activate new global translation table
342
	Translate::getInstance()->initialize('en',
343
										 (defined('DEFAULT_LANGUAGE') ? DEFAULT_LANGUAGE : ''), 
344
										 (defined('LANGUAGE') ? LANGUAGE : ''),
345
										 'WbOldStyle',
346
										 (DEBUG ? Translate::CACHE_DISABLED|Translate::KEEP_MISSING : 0)
347
										);
348
// *** END OF FILE ***********************************************************************
349
 
(30-30/32)