summaryrefslogtreecommitdiff
path: root/includes/session.php
blob: cc5b216dc513476df157075cbb30f67dbfaa32ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2017 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Fisharebest\Webtrees;

use DateTime;
use Fisharebest\Webtrees\Theme\AdministrationTheme;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use PDOException;
use Symfony\Component\HttpFoundation\Request;

/**
 * We set the following globals
 *
 * @global Tree    $WT_TREE
 */
global $WT_TREE;

// Identify ourself
define('WT_WEBTREES', 'webtrees');
define('WT_VERSION', '2.0.0-dev');

// External URLs
define('WT_WEBTREES_URL', 'https://www.webtrees.net/');
define('WT_BOOTSTRAP_CSS_URL', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');
define('WT_BOOTSTRAP_DATETIMEPICKER_CSS_URL', 'packages/bootstrap-datetimepicker-4.17.37/css/bootstrap-datetimepicker.min.css');
define('WT_BOOTSTRAP_DATETIMEPICKER_JS_URL', 'packages/bootstrap-datetimepicker-4.17.37/js/bootstrap-datetimepicker.min.js');
define('WT_BOOTSTRAP_JS_URL', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js');
define('WT_BOOTSTRAP_RTL_CSS_URL', 'packages/bootstrap-rtl-3.3.4/css/bootstrap-rtl.min.css');
define('WT_DATATABLES_JS_URL', 'packages/datatables-1.10.15/jquery.dataTables.min.js');
define('WT_DATATABLES_BOOTSTRAP_CSS_URL', 'packages/datatables-1.10.15/dataTables.bootstrap4.min.css');
define('WT_DATATABLES_BOOTSTRAP_JS_URL', 'packages/datatables-1.10.15/dataTables.bootstrap4.min.js');
define('WT_FONT_AWESOME_CSS_URL', 'packages/font-awesome-4.7.0/css/font-awesome.min.css');
define('WT_JQUERY_JS_URL', 'packages/jquery-3.1.1/jquery.min.js');
define('WT_MOMENT_JS_URL', 'packages/moment-2.11.2/moment-with-locales.min.js');
define('WT_SELECT2_JS_URL', 'packages/select2-4.0.3/js/select2.min.js');
define('WT_SELECT2_CSS_URL', 'packages/select2-4.0.3/css/select2.min.css');
define('WT_SORTABLE_JS_URL', 'packages/rubaxa-sortable-1.4.0/Sortable.min.js');
define('WT_TETHER_JS_URL', 'packages/tether-1.4.0/tether.min.js');
// Note: these have been patched.
define('WT_JQUERY_COLORBOX_URL', 'assets/js-2.0.0/jquery.colorbox-1.5.14.js');
define('WT_JQUERY_WHEELZOOM_URL', 'assets/js-2.0.0/jquery.wheelzoom-2.0.0.js');
define('WT_CKEDITOR_BASE_URL', 'packages/ckeditor-4.5.2-custom/');

// Location of our own scripts
define('WT_ADMIN_JS_URL', 'assets/js-2.0.0/admin.js');
define('WT_WEBTREES_JS_URL', 'assets/js-2.0.0/webtrees.js');
define('WT_FONT_AWESOME_RTL_CSS_URL', 'assets/js-2.0.0/font-awesome-rtl.css');

// Location of our modules and themes. These are used as URLs and folder paths.
define('WT_MODULES_DIR', 'modules_v3/'); // Update setup.php and build/Makefile when this changes
define('WT_THEMES_DIR', 'themes/');

// Enable debugging output on development builds
define('WT_DEBUG', strpos(WT_VERSION, 'dev') !== false);

// Required version of database tables/columns/indexes/etc.
define('WT_SCHEMA_VERSION', 37);

// Regular expressions for validating user input, etc.
define('WT_MINIMUM_PASSWORD_LENGTH', 6);
define('WT_REGEX_XREF', '[A-Za-z0-9:_-]+');
define('WT_REGEX_TAG', '[_A-Z][_A-Z0-9]*');
define('WT_REGEX_INTEGER', '-?\d+');
define('WT_REGEX_BYTES', '[0-9]+[bBkKmMgG]?');
define('WT_REGEX_PASSWORD', '.{' . WT_MINIMUM_PASSWORD_LENGTH . ',}');

// UTF8 representation of various characters
define('WT_UTF8_BOM', "\xEF\xBB\xBF"); // U+FEFF (Byte order mark)
define('WT_UTF8_LRM', "\xE2\x80\x8E"); // U+200E (Left to Right mark:  zero-width character with LTR directionality)
define('WT_UTF8_RLM', "\xE2\x80\x8F"); // U+200F (Right to Left mark:  zero-width character with RTL directionality)
define('WT_UTF8_LRO', "\xE2\x80\xAD"); // U+202D (Left to Right override: force everything following to LTR mode)
define('WT_UTF8_RLO', "\xE2\x80\xAE"); // U+202E (Right to Left override: force everything following to RTL mode)
define('WT_UTF8_LRE', "\xE2\x80\xAA"); // U+202A (Left to Right embedding: treat everything following as LTR text)
define('WT_UTF8_RLE', "\xE2\x80\xAB"); // U+202B (Right to Left embedding: treat everything following as RTL text)
define('WT_UTF8_PDF', "\xE2\x80\xAC"); // U+202C (Pop directional formatting: restore state prior to last LRO, RLO, LRE, RLE)

// Alternatives to BMD events for lists, charts, etc.
define('WT_EVENTS_BIRT', 'BIRT|CHR|BAPM|_BRTM|ADOP');
define('WT_EVENTS_DEAT', 'DEAT|BURI|CREM');
define('WT_EVENTS_MARR', 'MARR|_NMR');
define('WT_EVENTS_DIV', 'DIV|ANUL|_SEPR');

// Use these line endings when writing files on the server
define('WT_EOL', "\r\n");

// Gedcom specification/definitions
define('WT_GEDCOM_LINE_LENGTH', 255 - strlen(WT_EOL)); // Characters, not bytes

// Used in Google charts
define('WT_GOOGLE_CHART_ENCODING', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.');

// For performance, it is quicker to refer to files using absolute paths
define('WT_ROOT', realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR);

// Keep track of time statistics, for the summary in the footer
define('WT_START_TIME', microtime(true));

// We want to know about all PHP errors during development, and fewer in production.
if (WT_DEBUG) {
	error_reporting(E_ALL | E_STRICT | E_NOTICE | E_DEPRECATED);
} else {
	error_reporting(E_ALL);
}

require WT_ROOT . 'vendor/autoload.php';

// PHP requires a time zone to be set. We'll set a better one later on.
date_default_timezone_set('UTC');

// Calculate the base URL, so we can generate absolute URLs.
$request = Request::createFromGlobals();
$request_uri = $request->getSchemeAndHttpHost() . $request->getRequestUri();

// Remove any PHP script name and parameters.
$base_uri = preg_replace('/[^\/]+\.php(\?.*)?$/', '', $request_uri);
define('WT_BASE_URL', $base_uri);

// What is the name of the requested script.
define('WT_SCRIPT_NAME', basename(Filter::server('SCRIPT_NAME')));

// Convert PHP errors into exceptions
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
	throw new \ErrorException($errfile . ':' . $errline . ' ' . $errstr, $errno);
});

set_exception_handler(function ($ex) {
	$message = $ex->getFile() . ':' . $ex->getLine() . ' ' . $ex->getMessage() . PHP_EOL;

	foreach ($ex->getTrace() as $level => $frame) {
		$frame += ['args' => [], 'file' => 'unknown', 'line' => 'unknown'];
		array_walk($frame['args'], function (&$arg) {
			switch (gettype($arg)) {
			case 'boolean':
			case 'integer':
			case 'double':
			case 'null':
				$arg = var_export($arg, true);
				break;
			case 'string':
				if (mb_strlen($arg) > 30) {
					$arg = mb_substr($arg, 0, 30) . '…';
				}
				$arg = var_export($arg, true);
				break;
			case 'object':
				$reflection = new \ReflectionClass($arg);
				if (is_object($arg) && method_exists($arg, '__toString')) {
					$arg = '[' . $reflection->getShortName() . ' ' . (string) $arg . ']';
				} else {
					$arg = '[' . $reflection->getShortName() . ']';
				}
				break;
			default:
				$arg = '[' . gettype($arg) . ']';
				break;
			}
		});
		$frame['file'] = str_replace(dirname(__DIR__), '', $frame['file']);
		$message .= '#' . $level . ' ' . $frame['file'] . ':' . $frame['line'] . ' ';
		if ($level > 0) {
			$message .= $frame['function'] . '(' . implode(', ', $frame['args']) . ')' . PHP_EOL;
		} else {
			$message .= get_class($ex) . '("' . $ex->getMessage() . '")' . PHP_EOL;
		}
	}

	echo $message;

	Log::addErrorLog($message);
});

// Load our configuration file, so we can connect to the database
if (file_exists(WT_ROOT . 'data/config.ini.php')) {
	$dbconfig = parse_ini_file(WT_ROOT . 'data/config.ini.php');
	// Invalid/unreadable config file?
	if (!is_array($dbconfig)) {
		header('Location: site-unavailable.php');
		exit;
	}
	// Down for maintenance?
	if (file_exists(WT_ROOT . 'data/offline.txt')) {
		header('Location: site-offline.php');
		exit;
	}
} else {
	// No config file. Set one up.
	header('Location: setup.php');
	exit;
}

// What is the remote client's IP address
define('WT_CLIENT_IP', $request->getClientIp());

// Connect to the database
try {
	Database::createInstance($dbconfig['dbhost'], $dbconfig['dbport'], $dbconfig['dbname'], $dbconfig['dbuser'], $dbconfig['dbpass']);
	define('WT_TBLPREFIX', $dbconfig['tblpfx']);
	unset($dbconfig);
	// Some of the FAMILY JOIN HUSBAND JOIN WIFE queries can excede the MAX_JOIN_SIZE setting
	Database::exec("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci', SQL_BIG_SELECTS=1");
	// Update the database schema
	$updated = Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', WT_SCHEMA_VERSION);
	if ($updated) {
		// updateSchema() might load custom modules - which we cannot load again.
		header('Location: ' . $request->getRequestUri());
		exit;
	}
} catch (PDOException $ex) {
	header('Location: ' . Html::url('site-unavailable.php', ['message' => $ex->getMessage()]));
	exit;
}

// The config.ini.php file must always be in a fixed location.
// Other user files can be stored elsewhere...
define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR);

// Some broken servers block access to their own temp folder using open_basedir...
$data_dir = new Filesystem(new Local(WT_DATA_DIR));
$data_dir->createDir('tmp');
putenv('TMPDIR=' . WT_DATA_DIR . 'tmp');

// Request more resources - if we can/want to
if (!ini_get('safe_mode')) {
	$memory_limit = Site::getPreference('MEMORY_LIMIT');
	if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) {
		ini_set('memory_limit', $memory_limit);
	}
	$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME');
	if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
		set_time_limit($max_execution_time);
	}
}

// Store our session data in the database.
session_set_save_handler(
	// open
	function () {
		return true;
	},
	// close
	function () {
		return true;
	},
	// read
	function ($id) {
		return (string) Database::prepare("SELECT session_data FROM `##session` WHERE session_id=?")->execute([$id])->fetchOne();
	},
	// write
	function ($id, $data) {
		// Only update the session table once per minute, unless the session data has actually changed.
		Database::prepare(
			"INSERT INTO `##session` (session_id, user_id, ip_address, session_data, session_time)" .
			" VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP - SECOND(CURRENT_TIMESTAMP))" .
			" ON DUPLICATE KEY UPDATE" .
			" user_id      = VALUES(user_id)," .
			" ip_address   = VALUES(ip_address)," .
			" session_data = VALUES(session_data)," .
			" session_time = CURRENT_TIMESTAMP - SECOND(CURRENT_TIMESTAMP)"
		)->execute([$id, (int) Auth::id(), WT_CLIENT_IP, $data]);

		return true;
	},
	// destroy
	function ($id) {
		Database::prepare("DELETE FROM `##session` WHERE session_id=?")->execute([$id]);

		return true;
	},
	// gc
	function ($maxlifetime) {
		Database::prepare("DELETE FROM `##session` WHERE session_time < DATE_SUB(NOW(), INTERVAL ? SECOND)")->execute([$maxlifetime]);

		return true;
	}
);

Session::start([
	'gc_maxlifetime' => Site::getPreference('SESSION_TIME'),
	'cookie_path'    => implode('/', array_map('rawurlencode', explode('/', parse_url(WT_BASE_URL, PHP_URL_PATH)))),
]);

if (!Session::get('initiated')) {
	// A new session, so prevent session fixation attacks by choosing a new PHPSESSID.
	Session::regenerate(true);
	Session::put('initiated', true);
}

// Set the tree for the page; (1) the request, (2) the session, (3) the site default, (4) any tree
foreach ([Filter::post('ged'), Filter::get('ged'), Session::get('GEDCOM'), Site::getPreference('DEFAULT_GEDCOM')] as $tree_name) {
	$WT_TREE = Tree::findByName($tree_name);
	if ($WT_TREE) {
		Session::put('GEDCOM', $tree_name);
		break;
	}
}
// No chosen tree? Use any one.
if (!$WT_TREE) {
	foreach (Tree::getAll() as $WT_TREE) {
		break;
	}
}

// With no parameters, init() looks to the environment to choose a language
define('WT_LOCALE', I18N::init());
Session::put('locale', WT_LOCALE);

// Note that the database/webservers may not be synchronised, so use DB time throughout.
define('WT_TIMESTAMP', (int) Database::prepare("SELECT UNIX_TIMESTAMP()")->fetchOne());

// Users get their own time-zone. Visitors get the site time-zone.
if (Auth::check()) {
	date_default_timezone_set(Auth::user()->getPreference('TIMEZONE', 'UTC'));
} else {
	date_default_timezone_set(Site::getPreference('TIMEZONE', 'UTC'));
}
define('WT_TIMESTAMP_OFFSET', date_offset_get(new DateTime('now')));

define('WT_CLIENT_JD', 2440588 + (int) ((WT_TIMESTAMP + WT_TIMESTAMP_OFFSET) / 86400));

// The login URL must be an absolute URL, and can be user-defined
if (Site::getPreference('LOGIN_URL') !== '') {
	define('WT_LOGIN_URL', Site::getPreference('LOGIN_URL'));
} else {
	define('WT_LOGIN_URL', WT_BASE_URL . 'login.php');
}

// If there is no current tree and we need one, then redirect somewhere
if (WT_SCRIPT_NAME != 'admin_trees_manage.php' && WT_SCRIPT_NAME != 'admin_pgv_to_wt.php' && WT_SCRIPT_NAME != 'login.php' && WT_SCRIPT_NAME != 'logout.php' && WT_SCRIPT_NAME != 'import.php' && WT_SCRIPT_NAME != 'help_text.php' && WT_SCRIPT_NAME != 'action.php') {
	if (!$WT_TREE || !$WT_TREE->getPreference('imported')) {
		if (Auth::isAdmin()) {
			header('Location: admin_trees_manage.php');
		} else {
			// We're not an administrator, so we can only log in if there is a tree.
			if (Auth::id()) {
				Auth::logout();
				FlashMessages::addMessage(
					I18N::translate('This user account does not have access to any tree.')
				);
			}
			header('Location: ' . Html::url(WT_LOGIN_URL, ['url' => $request->getRequestUri()]));

		}
		exit;
	}
}

// Update the last-login time no more than once a minute
if (WT_TIMESTAMP - Session::get('activity_time') >= 60) {
	if (Session::get('masquerade') === null) {
		Auth::user()->setPreference('sessiontime', WT_TIMESTAMP);
	}
	Session::put('activity_time', WT_TIMESTAMP);
}

// Set the theme
if (substr(WT_SCRIPT_NAME, 0, 5) === 'admin' || WT_SCRIPT_NAME === 'module.php' && substr(Filter::get('mod_action'), 0, 5) === 'admin') {
	// Administration scripts begin with “admin” and use a special administration theme
	Theme::theme(new AdministrationTheme)->init($WT_TREE);
} else {
	// Last theme used?
	$theme_id = Session::get('theme_id');
	// Default for tree
	if (!array_key_exists($theme_id, Theme::themeNames()) && $WT_TREE) {
		$theme_id = $WT_TREE->getPreference('THEME_DIR');
	}
	// Default for site
	if (!array_key_exists($theme_id, Theme::themeNames())) {
		$theme_id = Site::getPreference('THEME_DIR');
	}
	// Default
	if (!array_key_exists($theme_id, Theme::themeNames())) {
		$theme_id = 'webtrees';
	}
	foreach (Theme::installedThemes() as $theme) {
		if ($theme->themeId() === $theme_id) {
			Theme::theme($theme)->init($WT_TREE);
			// Remember this setting
			if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
				Session::put('theme_id', $theme_id);
			}
			break;
		}
	}
}