Project

General

Profile

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