phpBB
Statistics
| Revision:

root / trunk / phpBB / includes / session.php

History | View | Annotate | Download (72.2 kB)

1
<?php
2
/**
3
*
4
* @package phpBB3
5
* @copyright (c) 2005 phpBB Group
6
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
7
*
8
*/
9
10
/**
11
* @ignore
12
*/
13
if (!defined('IN_PHPBB'))
14
{
15
        exit;
16
}
17
18
/**
19
* Session class
20
* @package phpBB3
21
*/
22
class session
23
{
24
        var $cookie_data = array();
25
        var $page = array();
26
        var $data = array();
27
        var $browser = '';
28
        var $forwarded_for = '';
29
        var $host = '';
30
        var $session_id = '';
31
        var $ip = '';
32
        var $load = 0;
33
        var $time_now = 0;
34
        var $update_session_page = true;
35
36
        /**
37
        * Extract current session page
38
        *
39
        * @param string $root_path current root path (phpbb_root_path)
40
        */
41
        static function extract_current_page($root_path)
42
        {
43
                global $request;
44
45
                $page_array = array();
46
47
                // First of all, get the request uri...
48
                $script_name = htmlspecialchars_decode($request->server('PHP_SELF'));
49
                $args = explode('&', htmlspecialchars_decode($request->server('QUERY_STRING')));
50
51
                // If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
52
                if (!$script_name)
53
                {
54
                        $script_name = htmlspecialchars_decode($request->server('REQUEST_URI'));
55
                        $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
56
                        $page_array['failover'] = 1;
57
                }
58
59
                // Replace backslashes and doubled slashes (could happen on some proxy setups)
60
                $script_name = str_replace(array('\\', '//'), '/', $script_name);
61
62
                // Now, remove the sid and let us get a clean query string...
63
                $use_args = array();
64
65
                // Since some browser do not encode correctly we need to do this with some "special" characters...
66
                // " -> %22, ' => %27, < -> %3C, > -> %3E
67
                $find = array('"', "'", '<', '>');
68
                $replace = array('%22', '%27', '%3C', '%3E');
69
70
                foreach ($args as $key => $argument)
71
                {
72
                        if (strpos($argument, 'sid=') === 0)
73
                        {
74
                                continue;
75
                        }
76
77
                        $use_args[] = str_replace($find, $replace, $argument);
78
                }
79
                unset($args);
80
81
                // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
82
83
                // The current query string
84
                $query_string = trim(implode('&', $use_args));
85
86
                // basenamed page name (for example: index.php)
87
                $page_name = (substr($script_name, -1, 1) == '/') ? '' : basename($script_name);
88
                $page_name = urlencode(htmlspecialchars($page_name));
89
90
                // current directory within the phpBB root (for example: adm)
91
                $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
92
                $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
93
                $intersection = array_intersect_assoc($root_dirs, $page_dirs);
94
95
                $root_dirs = array_diff_assoc($root_dirs, $intersection);
96
                $page_dirs = array_diff_assoc($page_dirs, $intersection);
97
98
                $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
99
100
                if ($page_dir && substr($page_dir, -1, 1) == '/')
101
                {
102
                        $page_dir = substr($page_dir, 0, -1);
103
                }
104
105
                // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
106
                $page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');
107
108
                // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
109
                $script_path = trim(str_replace('\\', '/', dirname($script_name)));
110
111
                // The script path from the webroot to the phpBB root (for example: /phpBB3/)
112
                $script_dirs = explode('/', $script_path);
113
                array_splice($script_dirs, -sizeof($page_dirs));
114
                $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
115
116
                // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
117
                if (!$root_script_path)
118
                {
119
                        $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
120
                }
121
122
                $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
123
                $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
124
125
                $page_array += array(
126
                        'page_name'                        => $page_name,
127
                        'page_dir'                        => $page_dir,
128
129
                        'query_string'                => $query_string,
130
                        'script_path'                => str_replace(' ', '%20', htmlspecialchars($script_path)),
131
                        'root_script_path'        => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
132
133
                        'page'                                => $page,
134
                        'forum'                                => request_var('f', 0),
135
                );
136
137
                return $page_array;
138
        }
139
140
        /**
141
        * Get valid hostname/port. HTTP_HOST is used, SERVER_NAME if HTTP_HOST not present.
142
        */
143
        function extract_current_hostname()
144
        {
145
                global $config, $request;
146
147
                // Get hostname
148
                $host = htmlspecialchars_decode($request->header('Host', $request->server('SERVER_NAME')));
149
150
                // Should be a string and lowered
151
                $host = (string) strtolower($host);
152
153
                // If host is equal the cookie domain or the server name (if config is set), then we assume it is valid
154
                if ((isset($config['cookie_domain']) && $host === $config['cookie_domain']) || (isset($config['server_name']) && $host === $config['server_name']))
155
                {
156
                        return $host;
157
                }
158
159
                // Is the host actually a IP? If so, we use the IP... (IPv4)
160
                if (long2ip(ip2long($host)) === $host)
161
                {
162
                        return $host;
163
                }
164
165
                // Now return the hostname (this also removes any port definition). The http:// is prepended to construct a valid URL, hosts never have a scheme assigned
166
                $host = @parse_url('http://' . $host);
167
                $host = (!empty($host['host'])) ? $host['host'] : '';
168
169
                // Remove any portions not removed by parse_url (#)
170
                $host = str_replace('#', '', $host);
171
172
                // If, by any means, the host is now empty, we will use a "best approach" way to guess one
173
                if (empty($host))
174
                {
175
                        if (!empty($config['server_name']))
176
                        {
177
                                $host = $config['server_name'];
178
                        }
179
                        else if (!empty($config['cookie_domain']))
180
                        {
181
                                $host = (strpos($config['cookie_domain'], '.') === 0) ? substr($config['cookie_domain'], 1) : $config['cookie_domain'];
182
                        }
183
                        else
184
                        {
185
                                // Set to OS hostname or localhost
186
                                $host = (function_exists('php_uname')) ? php_uname('n') : 'localhost';
187
                        }
188
                }
189
190
                // It may be still no valid host, but for sure only a hostname (we may further expand on the cookie domain... if set)
191
                return $host;
192
        }
193
194
        /**
195
        * Start session management
196
        *
197
        * This is where all session activity begins. We gather various pieces of
198
        * information from the client and server. We test to see if a session already
199
        * exists. If it does, fine and dandy. If it doesn't we'll go on to create a
200
        * new one ... pretty logical heh? We also examine the system load (if we're
201
        * running on a system which makes such information readily available) and
202
        * halt if it's above an admin definable limit.
203
        *
204
        * @param bool $update_session_page if true the session page gets updated.
205
        *                        This can be set to circumvent certain scripts to update the users last visited page.
206
        */
207
        function session_begin($update_session_page = true)
208
        {
209
                global $phpEx, $SID, $_SID, $_EXTRA_URL, $db, $config, $phpbb_root_path;
210
                global $request;
211
212
                // Give us some basic information
213
                $this->time_now                                = time();
214
                $this->cookie_data                        = array('u' => 0, 'k' => '');
215
                $this->update_session_page        = $update_session_page;
216
                $this->browser                                = $request->header('User-Agent');
217
                $this->referer                                = $request->header('Referer');
218
                $this->forwarded_for                = $request->header('X-Forwarded-For');
219
220
                $this->host                                        = $this->extract_current_hostname();
221
                $this->page                                        = $this->extract_current_page($phpbb_root_path);
222
223
                // if the forwarded for header shall be checked we have to validate its contents
224
                if ($config['forwarded_for_check'])
225
                {
226
                        $this->forwarded_for = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->forwarded_for));
227
228
                        // split the list of IPs
229
                        $ips = explode(' ', $this->forwarded_for);
230
                        foreach ($ips as $ip)
231
                        {
232
                                // check IPv4 first, the IPv6 is hopefully only going to be used very seldomly
233
                                if (!empty($ip) && !preg_match(get_preg_expression('ipv4'), $ip) && !preg_match(get_preg_expression('ipv6'), $ip))
234
                                {
235
                                        // contains invalid data, don't use the forwarded for header
236
                                        $this->forwarded_for = '';
237
                                        break;
238
                                }
239
                        }
240
                }
241
                else
242
                {
243
                        $this->forwarded_for = '';
244
                }
245
246
                if ($request->is_set($config['cookie_name'] . '_sid', phpbb_request_interface::COOKIE) || $request->is_set($config['cookie_name'] . '_u', phpbb_request_interface::COOKIE))
247
                {
248
                        $this->cookie_data['u'] = request_var($config['cookie_name'] . '_u', 0, false, true);
249
                        $this->cookie_data['k'] = request_var($config['cookie_name'] . '_k', '', false, true);
250
                        $this->session_id                 = request_var($config['cookie_name'] . '_sid', '', false, true);
251
252
                        $SID = (defined('NEED_SID')) ? '?sid=' . $this->session_id : '?sid=';
253
                        $_SID = (defined('NEED_SID')) ? $this->session_id : '';
254
255
                        if (empty($this->session_id))
256
                        {
257
                                $this->session_id = $_SID = request_var('sid', '');
258
                                $SID = '?sid=' . $this->session_id;
259
                                $this->cookie_data = array('u' => 0, 'k' => '');
260
                        }
261
                }
262
                else
263
                {
264
                        $this->session_id = $_SID = request_var('sid', '');
265
                        $SID = '?sid=' . $this->session_id;
266
                }
267
268
                $_EXTRA_URL = array();
269
270
                // Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
271
                // it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
272
                $this->ip = htmlspecialchars_decode($request->server('REMOTE_ADDR'));
273
                $this->ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->ip));
274
275
                // split the list of IPs
276
                $ips = explode(' ', trim($this->ip));
277
278
                // Default IP if REMOTE_ADDR is invalid
279
                $this->ip = '127.0.0.1';
280
281
                foreach ($ips as $ip)
282
                {
283
                        if (function_exists('phpbb_ip_normalise'))
284
                        {
285
                                // Normalise IP address
286
                                $ip = phpbb_ip_normalise($ip);
287
288
                                if (empty($ip))
289
                                {
290
                                        // IP address is invalid.
291
                                        break;
292
                                }
293
294
                                // IP address is valid.
295
                                $this->ip = $ip;
296
297
                                // Skip legacy code.
298
                                continue;
299
                        }
300
301
                        if (preg_match(get_preg_expression('ipv4'), $ip))
302
                        {
303
                                $this->ip = $ip;
304
                        }
305
                        else if (preg_match(get_preg_expression('ipv6'), $ip))
306
                        {
307
                                // Quick check for IPv4-mapped address in IPv6
308
                                if (stripos($ip, '::ffff:') === 0)
309
                                {
310
                                        $ipv4 = substr($ip, 7);
311
312
                                        if (preg_match(get_preg_expression('ipv4'), $ipv4))
313
                                        {
314
                                                $ip = $ipv4;
315
                                        }
316
                                }
317
318
                                $this->ip = $ip;
319
                        }
320
                        else
321
                        {
322
                                // We want to use the last valid address in the chain
323
                                // Leave foreach loop when address is invalid
324
                                break;
325
                        }
326
                }
327
328
                $this->load = false;
329
330
                // Load limit check (if applicable)
331
                if ($config['limit_load'] || $config['limit_search_load'])
332
                {
333
                        if ((function_exists('sys_getloadavg') && $load = sys_getloadavg()) || ($load = explode(' ', @file_get_contents('/proc/loadavg'))))
334
                        {
335
                                $this->load = array_slice($load, 0, 1);
336
                                $this->load = floatval($this->load[0]);
337
                        }
338
                        else
339
                        {
340
                                set_config('limit_load', '0');
341
                                set_config('limit_search_load', '0');
342
                        }
343
                }
344
345
                // Is session_id is set or session_id is set and matches the url param if required
346
                if (!empty($this->session_id) && (!defined('NEED_SID') || (isset($_GET['sid']) && $this->session_id === request_var('sid', ''))))
347
                {
348
                        $sql = 'SELECT u.*, s.*
349
                                FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . " u
350
                                WHERE s.session_id = '" . $db->sql_escape($this->session_id) . "'
351
                                        AND u.user_id = s.session_user_id";
352
                        $result = $db->sql_query($sql);
353
                        $this->data = $db->sql_fetchrow($result);
354
                        $db->sql_freeresult($result);
355
356
                        // Did the session exist in the DB?
357
                        if (isset($this->data['user_id']))
358
                        {
359
                                // Validate IP length according to admin ... enforces an IP
360
                                // check on bots if admin requires this
361
//                                $quadcheck = ($config['ip_check_bot'] && $this->data['user_type'] & USER_BOT) ? 4 : $config['ip_check'];
362
363
                                if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
364
                                {
365
                                        $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
366
                                        $u_ip = short_ipv6($this->ip, $config['ip_check']);
367
                                }
368
                                else
369
                                {
370
                                        $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
371
                                        $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
372
                                }
373
374
                                $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
375
                                $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
376
377
                                $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
378
                                $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
379
380
                                // referer checks
381
                                // The @ before $config['referer_validation'] suppresses notices present while running the updater
382
                                $check_referer_path = (@$config['referer_validation'] == REFERER_VALIDATE_PATH);
383
                                $referer_valid = true;
384
385
                                // we assume HEAD and TRACE to be foul play and thus only whitelist GET
386
                                if (@$config['referer_validation'] && strtolower($request->server('REQUEST_METHOD')) !== 'get')
387
                                {
388
                                        $referer_valid = $this->validate_referer($check_referer_path);
389
                                }
390
391
                                if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for && $referer_valid)
392
                                {
393
                                        $session_expired = false;
394
395
                                        // Check whether the session is still valid if we have one
396
                                        $method = basename(trim($config['auth_method']));
397
                                        include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
398
399
                                        $method = 'validate_session_' . $method;
400
                                        if (function_exists($method))
401
                                        {
402
                                                if (!$method($this->data))
403
                                                {
404
                                                        $session_expired = true;
405
                                                }
406
                                        }
407
408
                                        if (!$session_expired)
409
                                        {
410
                                                // Check the session length timeframe if autologin is not enabled.
411
                                                // Else check the autologin length... and also removing those having autologin enabled but no longer allowed board-wide.
412
                                                if (!$this->data['session_autologin'])
413
                                                {
414
                                                        if ($this->data['session_time'] < $this->time_now - ($config['session_length'] + 60))
415
                                                        {
416
                                                                $session_expired = true;
417
                                                        }
418
                                                }
419
                                                else if (!$config['allow_autologin'] || ($config['max_autologin_time'] && $this->data['session_time'] < $this->time_now - (86400 * (int) $config['max_autologin_time']) + 60))
420
                                                {
421
                                                        $session_expired = true;
422
                                                }
423
                                        }
424
425
                                        if (!$session_expired)
426
                                        {
427
                                                // Only update session DB a minute or so after last update or if page changes
428
                                                if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
429
                                                {
430
                                                        $sql_ary = array('session_time' => $this->time_now);
431
432
                                                        if ($this->update_session_page)
433
                                                        {
434
                                                                $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
435
                                                                $sql_ary['session_forum_id'] = $this->page['forum'];
436
                                                        }
437
438
                                                        $db->sql_return_on_error(true);
439
440
                                                        $this->update_session($sql_ary);
441
442
                                                        $db->sql_return_on_error(false);
443
444
                                                        // If the database is not yet updated, there will be an error due to the session_forum_id
445
                                                        // @todo REMOVE for 3.0.2
446
                                                        if ($result === false)
447
                                                        {
448
                                                                unset($sql_ary['session_forum_id']);
449
450
                                                                $this->update_session($sql_ary);
451
                                                        }
452
453
                                                        if ($this->data['user_id'] != ANONYMOUS && !empty($config['new_member_post_limit']) && $this->data['user_new'] && $config['new_member_post_limit'] <= $this->data['user_posts'])
454
                                                        {
455
                                                                $this->leave_newly_registered();
456
                                                        }
457
                                                }
458
459
                                                $this->data['is_registered'] = ($this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
460
                                                $this->data['is_bot'] = (!$this->data['is_registered'] && $this->data['user_id'] != ANONYMOUS) ? true : false;
461
                                                $this->data['user_lang'] = basename($this->data['user_lang']);
462
463
                                                return true;
464
                                        }
465
                                }
466
                                else
467
                                {
468
                                        // Added logging temporarly to help debug bugs...
469
                                        if (defined('DEBUG_EXTRA') && $this->data['user_id'] != ANONYMOUS)
470
                                        {
471
                                                if ($referer_valid)
472
                                                {
473
                                                        add_log('critical', 'LOG_IP_BROWSER_FORWARDED_CHECK', $u_ip, $s_ip, $u_browser, $s_browser, htmlspecialchars($u_forwarded_for), htmlspecialchars($s_forwarded_for));
474
                                                }
475
                                                else
476
                                                {
477
                                                        add_log('critical', 'LOG_REFERER_INVALID', $this->referer);
478
                                                }
479
                                        }
480
                                }
481
                        }
482
                }
483
484
                // If we reach here then no (valid) session exists. So we'll create a new one
485
                return $this->session_create();
486
        }
487
488
        /**
489
        * Create a new session
490
        *
491
        * If upon trying to start a session we discover there is nothing existing we
492
        * jump here. Additionally this method is called directly during login to regenerate
493
        * the session for the specific user. In this method we carry out a number of tasks;
494
        * garbage collection, (search)bot checking, banned user comparison. Basically
495
        * though this method will result in a new session for a specific user.
496
        */
497
        function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
498
        {
499
                global $SID, $_SID, $db, $config, $cache, $phpbb_root_path, $phpEx;
500
501
                $this->data = array();
502
503
                /* Garbage collection ... remove old sessions updating user information
504
                // if necessary. It means (potentially) 11 queries but only infrequently
505
                if ($this->time_now > $config['session_last_gc'] + $config['session_gc'])
506
                {
507
                        $this->session_gc();
508
                }*/
509
510
                // Do we allow autologin on this board? No? Then override anything
511
                // that may be requested here
512
                if (!$config['allow_autologin'])
513
                {
514
                        $this->cookie_data['k'] = $persist_login = false;
515
                }
516
517
                /**
518
                * Here we do a bot check, oh er saucy! No, not that kind of bot
519
                * check. We loop through the list of bots defined by the admin and
520
                * see if we have any useragent and/or IP matches. If we do, this is a
521
                * bot, act accordingly
522
                */
523
                $bot = false;
524
                $active_bots = $cache->obtain_bots();
525
526
                foreach ($active_bots as $row)
527
                {
528
                        if ($row['bot_agent'] && preg_match('#' . str_replace('\*', '.*?', preg_quote($row['bot_agent'], '#')) . '#i', $this->browser))
529
                        {
530
                                $bot = $row['user_id'];
531
                        }
532
533
                        // If ip is supplied, we will make sure the ip is matching too...
534
                        if ($row['bot_ip'] && ($bot || !$row['bot_agent']))
535
                        {
536
                                // Set bot to false, then we only have to set it to true if it is matching
537
                                $bot = false;
538
539
                                foreach (explode(',', $row['bot_ip']) as $bot_ip)
540
                                {
541
                                        $bot_ip = trim($bot_ip);
542
543
                                        if (!$bot_ip)
544
                                        {
545
                                                continue;
546
                                        }
547
548
                                        if (strpos($this->ip, $bot_ip) === 0)
549
                                        {
550
                                                $bot = (int) $row['user_id'];
551
                                                break;
552
                                        }
553
                                }
554
                        }
555
556
                        if ($bot)
557
                        {
558
                                break;
559
                        }
560
                }
561
562
                $method = basename(trim($config['auth_method']));
563
                include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
564
565
                $method = 'autologin_' . $method;
566
                if (function_exists($method))
567
                {
568
                        $this->data = $method();
569
570
                        if (sizeof($this->data))
571
                        {
572
                                $this->cookie_data['k'] = '';
573
                                $this->cookie_data['u'] = $this->data['user_id'];
574
                        }
575
                }
576
577
                // If we're presented with an autologin key we'll join against it.
578
                // Else if we've been passed a user_id we'll grab data based on that
579
                if (isset($this->cookie_data['k']) && $this->cookie_data['k'] && $this->cookie_data['u'] && !sizeof($this->data))
580
                {
581
                        $sql = 'SELECT u.*
582
                                FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
583
                                WHERE u.user_id = ' . (int) $this->cookie_data['u'] . '
584
                                        AND u.user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ")
585
                                        AND k.user_id = u.user_id
586
                                        AND k.key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
587
                        $result = $db->sql_query($sql);
588
                        $this->data = $db->sql_fetchrow($result);
589
                        $db->sql_freeresult($result);
590
                        $bot = false;
591
                }
592
                else if ($user_id !== false && !sizeof($this->data))
593
                {
594
                        $this->cookie_data['k'] = '';
595
                        $this->cookie_data['u'] = $user_id;
596
597
                        $sql = 'SELECT *
598
                                FROM ' . USERS_TABLE . '
599
                                WHERE user_id = ' . (int) $this->cookie_data['u'] . '
600
                                        AND user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')';
601
                        $result = $db->sql_query($sql);
602
                        $this->data = $db->sql_fetchrow($result);
603
                        $db->sql_freeresult($result);
604
                        $bot = false;
605
                }
606
607
                // Bot user, if they have a SID in the Request URI we need to get rid of it
608
                // otherwise they'll index this page with the SID, duplicate content oh my!
609
                if ($bot && isset($_GET['sid']))
610
                {
611
                        send_status_line(301, 'Moved Permanently');
612
                        redirect(build_url(array('sid')));
613
                }
614
615
                // If no data was returned one or more of the following occurred:
616
                // Key didn't match one in the DB
617
                // User does not exist
618
                // User is inactive
619
                // User is bot
620
                if (!sizeof($this->data) || !is_array($this->data))
621
                {
622
                        $this->cookie_data['k'] = '';
623
                        $this->cookie_data['u'] = ($bot) ? $bot : ANONYMOUS;
624
625
                        if (!$bot)
626
                        {
627
                                $sql = 'SELECT *
628
                                        FROM ' . USERS_TABLE . '
629
                                        WHERE user_id = ' . (int) $this->cookie_data['u'];
630
                        }
631
                        else
632
                        {
633
                                // We give bots always the same session if it is not yet expired.
634
                                $sql = 'SELECT u.*, s.*
635
                                        FROM ' . USERS_TABLE . ' u
636
                                        LEFT JOIN ' . SESSIONS_TABLE . ' s ON (s.session_user_id = u.user_id)
637
                                        WHERE u.user_id = ' . (int) $bot;
638
                        }
639
640
                        $result = $db->sql_query($sql);
641
                        $this->data = $db->sql_fetchrow($result);
642
                        $db->sql_freeresult($result);
643
                }
644
645
                if ($this->data['user_id'] != ANONYMOUS && !$bot)
646
                {
647
                        $this->data['session_last_visit'] = (isset($this->data['session_time']) && $this->data['session_time']) ? $this->data['session_time'] : (($this->data['user_lastvisit']) ? $this->data['user_lastvisit'] : time());
648
                }
649
                else
650
                {
651
                        $this->data['session_last_visit'] = $this->time_now;
652
                }
653
654
                // Force user id to be integer...
655
                $this->data['user_id'] = (int) $this->data['user_id'];
656
657
                // At this stage we should have a filled data array, defined cookie u and k data.
658
                // data array should contain recent session info if we're a real user and a recent
659
                // session exists in which case session_id will also be set
660
661
                // Is user banned? Are they excluded? Won't return on ban, exists within method
662
                if ($this->data['user_type'] != USER_FOUNDER)
663
                {
664
                        if (!$config['forwarded_for_check'])
665
                        {
666
                                $this->check_ban($this->data['user_id'], $this->ip);
667
                        }
668
                        else
669
                        {
670
                                $ips = explode(' ', $this->forwarded_for);
671
                                $ips[] = $this->ip;
672
                                $this->check_ban($this->data['user_id'], $ips);
673
                        }
674
                }
675
676
                $this->data['is_registered'] = (!$bot && $this->data['user_id'] != ANONYMOUS && ($this->data['user_type'] == USER_NORMAL || $this->data['user_type'] == USER_FOUNDER)) ? true : false;
677
                $this->data['is_bot'] = ($bot) ? true : false;
678
679
                // If our friend is a bot, we re-assign a previously assigned session
680
                if ($this->data['is_bot'] && $bot == $this->data['user_id'] && $this->data['session_id'])
681
                {
682
                        // Only assign the current session if the ip, browser and forwarded_for match...
683
                        if (strpos($this->ip, ':') !== false && strpos($this->data['session_ip'], ':') !== false)
684
                        {
685
                                $s_ip = short_ipv6($this->data['session_ip'], $config['ip_check']);
686
                                $u_ip = short_ipv6($this->ip, $config['ip_check']);
687
                        }
688
                        else
689
                        {
690
                                $s_ip = implode('.', array_slice(explode('.', $this->data['session_ip']), 0, $config['ip_check']));
691
                                $u_ip = implode('.', array_slice(explode('.', $this->ip), 0, $config['ip_check']));
692
                        }
693
694
                        $s_browser = ($config['browser_check']) ? trim(strtolower(substr($this->data['session_browser'], 0, 149))) : '';
695
                        $u_browser = ($config['browser_check']) ? trim(strtolower(substr($this->browser, 0, 149))) : '';
696
697
                        $s_forwarded_for = ($config['forwarded_for_check']) ? substr($this->data['session_forwarded_for'], 0, 254) : '';
698
                        $u_forwarded_for = ($config['forwarded_for_check']) ? substr($this->forwarded_for, 0, 254) : '';
699
700
                        if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for)
701
                        {
702
                                $this->session_id = $this->data['session_id'];
703
704
                                // Only update session DB a minute or so after last update or if page changes
705
                                if ($this->time_now - $this->data['session_time'] > 60 || ($this->update_session_page && $this->data['session_page'] != $this->page['page']))
706
                                {
707
                                        $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
708
709
                                        $sql_ary = array('session_time' => $this->time_now, 'session_last_visit' => $this->time_now, 'session_admin' => 0);
710
711
                                        if ($this->update_session_page)
712
                                        {
713
                                                $sql_ary['session_page'] = substr($this->page['page'], 0, 199);
714
                                                $sql_ary['session_forum_id'] = $this->page['forum'];
715
                                        }
716
717
                                        $this->update_session($sql_ary);
718
719
                                        // Update the last visit time
720
                                        $sql = 'UPDATE ' . USERS_TABLE . '
721
                                                SET user_lastvisit = ' . (int) $this->data['session_time'] . '
722
                                                WHERE user_id = ' . (int) $this->data['user_id'];
723
                                        $db->sql_query($sql);
724
                                }
725
726
                                $SID = '?sid=';
727
                                $_SID = '';
728
                                return true;
729
                        }
730
                        else
731
                        {
732
                                // If the ip and browser does not match make sure we only have one bot assigned to one session
733
                                $db->sql_query('DELETE FROM ' . SESSIONS_TABLE . ' WHERE session_user_id = ' . $this->data['user_id']);
734
                        }
735
                }
736
737
                $session_autologin = (($this->cookie_data['k'] || $persist_login) && $this->data['is_registered']) ? true : false;
738
                $set_admin = ($set_admin && $this->data['is_registered']) ? true : false;
739
740
                // Create or update the session
741
                $sql_ary = array(
742
                        'session_user_id'                => (int) $this->data['user_id'],
743
                        'session_start'                        => (int) $this->time_now,
744
                        'session_last_visit'        => (int) $this->data['session_last_visit'],
745
                        'session_time'                        => (int) $this->time_now,
746
                        'session_browser'                => (string) trim(substr($this->browser, 0, 149)),
747
                        'session_forwarded_for'        => (string) $this->forwarded_for,
748
                        'session_ip'                        => (string) $this->ip,
749
                        'session_autologin'                => ($session_autologin) ? 1 : 0,
750
                        'session_admin'                        => ($set_admin) ? 1 : 0,
751
                        'session_viewonline'        => ($viewonline) ? 1 : 0,
752
                );
753
754
                if ($this->update_session_page)
755
                {
756
                        $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
757
                        $sql_ary['session_forum_id'] = $this->page['forum'];
758
                }
759
760
                $db->sql_return_on_error(true);
761
762
                $sql = 'DELETE
763
                        FROM ' . SESSIONS_TABLE . '
764
                        WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'
765
                                AND session_user_id = ' . ANONYMOUS;
766
767
                if (!defined('IN_ERROR_HANDLER') && (!$this->session_id || !$db->sql_query($sql) || !$db->sql_affectedrows()))
768
                {
769
                        // Limit new sessions in 1 minute period (if required)
770
                        if (empty($this->data['session_time']) && $config['active_sessions'])
771
                        {
772
//                                $db->sql_return_on_error(false);
773
774
                                $sql = 'SELECT COUNT(session_id) AS sessions
775
                                        FROM ' . SESSIONS_TABLE . '
776
                                        WHERE session_time >= ' . ($this->time_now - 60);
777
                                $result = $db->sql_query($sql);
778
                                $row = $db->sql_fetchrow($result);
779
                                $db->sql_freeresult($result);
780
781
                                if ((int) $row['sessions'] > (int) $config['active_sessions'])
782
                                {
783
                                        send_status_line(503, 'Service Unavailable');
784
                                        trigger_error('BOARD_UNAVAILABLE');
785
                                }
786
                        }
787
                }
788
789
                // Since we re-create the session id here, the inserted row must be unique. Therefore, we display potential errors.
790
                // Commented out because it will not allow forums to update correctly
791
//                $db->sql_return_on_error(false);
792
793
                // Something quite important: session_page always holds the *last* page visited, except for the *first* visit.
794
                // We are not able to simply have an empty session_page btw, therefore we need to tell phpBB how to detect this special case.
795
                // If the session id is empty, we have a completely new one and will set an "identifier" here. This identifier is able to be checked later.
796
                if (empty($this->data['session_id']))
797
                {
798
                        // This is a temporary variable, only set for the very first visit
799
                        $this->data['session_created'] = true;
800
                }
801
802
                $this->session_id = $this->data['session_id'] = md5(unique_id());
803
804
                $sql_ary['session_id'] = (string) $this->session_id;
805
                $sql_ary['session_page'] = (string) substr($this->page['page'], 0, 199);
806
                $sql_ary['session_forum_id'] = $this->page['forum'];
807
808
                $sql = 'INSERT INTO ' . SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
809
                $db->sql_query($sql);
810
811
                $db->sql_return_on_error(false);
812
813
                // Regenerate autologin/persistent login key
814
                if ($session_autologin)
815
                {
816
                        $this->set_login_key();
817
                }
818
819
                // refresh data
820
                $SID = '?sid=' . $this->session_id;
821
                $_SID = $this->session_id;
822
                $this->data = array_merge($this->data, $sql_ary);
823
824
                if (!$bot)
825
                {
826
                        $cookie_expire = $this->time_now + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
827
828
                        $this->set_cookie('u', $this->cookie_data['u'], $cookie_expire);
829
                        $this->set_cookie('k', $this->cookie_data['k'], $cookie_expire);
830
                        $this->set_cookie('sid', $this->session_id, $cookie_expire);
831
832
                        unset($cookie_expire);
833
834
                        $sql = 'SELECT COUNT(session_id) AS sessions
835
                                        FROM ' . SESSIONS_TABLE . '
836
                                        WHERE session_user_id = ' . (int) $this->data['user_id'] . '
837
                                        AND session_time >= ' . (int) ($this->time_now - (max($config['session_length'], $config['form_token_lifetime'])));
838
                        $result = $db->sql_query($sql);
839
                        $row = $db->sql_fetchrow($result);
840
                        $db->sql_freeresult($result);
841
842
                        if ((int) $row['sessions'] <= 1 || empty($this->data['user_form_salt']))
843
                        {
844
                                $this->data['user_form_salt'] = unique_id();
845
                                // Update the form key
846
                                $sql = 'UPDATE ' . USERS_TABLE . '
847
                                        SET user_form_salt = \'' . $db->sql_escape($this->data['user_form_salt']) . '\'
848
                                        WHERE user_id = ' . (int) $this->data['user_id'];
849
                                $db->sql_query($sql);
850
                        }
851
                }
852
                else
853
                {
854
                        $this->data['session_time'] = $this->data['session_last_visit'] = $this->time_now;
855
856
                        // Update the last visit time
857
                        $sql = 'UPDATE ' . USERS_TABLE . '
858
                                SET user_lastvisit = ' . (int) $this->data['session_time'] . '
859
                                WHERE user_id = ' . (int) $this->data['user_id'];
860
                        $db->sql_query($sql);
861
862
                        $SID = '?sid=';
863
                        $_SID = '';
864
                }
865
866
                return true;
867
        }
868
869
        /**
870
        * Kills a session
871
        *
872
        * This method does what it says on the tin. It will delete a pre-existing session.
873
        * It resets cookie information (destroying any autologin key within that cookie data)
874
        * and update the users information from the relevant session data. It will then
875
        * grab guest user information.
876
        */
877
        function session_kill($new_session = true)
878
        {
879
                global $SID, $_SID, $db, $config, $phpbb_root_path, $phpEx;
880
881
                $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
882
                        WHERE session_id = '" . $db->sql_escape($this->session_id) . "'
883
                                AND session_user_id = " . (int) $this->data['user_id'];
884
                $db->sql_query($sql);
885
886
                // Allow connecting logout with external auth method logout
887
                $method = basename(trim($config['auth_method']));
888
                include_once($phpbb_root_path . 'includes/auth/auth_' . $method . '.' . $phpEx);
889
890
                $method = 'logout_' . $method;
891
                if (function_exists($method))
892
                {
893
                        $method($this->data, $new_session);
894
                }
895
896
                if ($this->data['user_id'] != ANONYMOUS)
897
                {
898
                        // Delete existing session, update last visit info first!
899
                        if (!isset($this->data['session_time']))
900
                        {
901
                                $this->data['session_time'] = time();
902
                        }
903
904
                        $sql = 'UPDATE ' . USERS_TABLE . '
905
                                SET user_lastvisit = ' . (int) $this->data['session_time'] . '
906
                                WHERE user_id = ' . (int) $this->data['user_id'];
907
                        $db->sql_query($sql);
908
909
                        if ($this->cookie_data['k'])
910
                        {
911
                                $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
912
                                        WHERE user_id = ' . (int) $this->data['user_id'] . "
913
                                                AND key_id = '" . $db->sql_escape(md5($this->cookie_data['k'])) . "'";
914
                                $db->sql_query($sql);
915
                        }
916
917
                        // Reset the data array
918
                        $this->data = array();
919
920
                        $sql = 'SELECT *
921
                                FROM ' . USERS_TABLE . '
922
                                WHERE user_id = ' . ANONYMOUS;
923
                        $result = $db->sql_query($sql);
924
                        $this->data = $db->sql_fetchrow($result);
925
                        $db->sql_freeresult($result);
926
                }
927
928
                $cookie_expire = $this->time_now - 31536000;
929
                $this->set_cookie('u', '', $cookie_expire);
930
                $this->set_cookie('k', '', $cookie_expire);
931
                $this->set_cookie('sid', '', $cookie_expire);
932
                unset($cookie_expire);
933
934
                $SID = '?sid=';
935
                $this->session_id = $_SID = '';
936
937
                // To make sure a valid session is created we create one for the anonymous user
938
                if ($new_session)
939
                {
940
                        $this->session_create(ANONYMOUS);
941
                }
942
943
                return true;
944
        }
945
946
        /**
947
        * Session garbage collection
948
        *
949
        * This looks a lot more complex than it really is. Effectively we are
950
        * deleting any sessions older than an admin definable limit. Due to the
951
        * way in which we maintain session data we have to ensure we update user
952
        * data before those sessions are destroyed. In addition this method
953
        * removes autologin key information that is older than an admin defined
954
        * limit.
955
        */
956
        function session_gc()
957
        {
958
                global $db, $config, $phpbb_root_path, $phpEx;
959
960
                $batch_size = 10;
961
962
                if (!$this->time_now)
963
                {
964
                        $this->time_now = time();
965
                }
966
967
                // Firstly, delete guest sessions
968
                $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
969
                        WHERE session_user_id = ' . ANONYMOUS . '
970
                                AND session_time < ' . (int) ($this->time_now - $config['session_length']);
971
                $db->sql_query($sql);
972
973
                // Get expired sessions, only most recent for each user
974
                $sql = 'SELECT session_user_id, session_page, MAX(session_time) AS recent_time
975
                        FROM ' . SESSIONS_TABLE . '
976
                        WHERE session_time < ' . ($this->time_now - $config['session_length']) . '
977
                        GROUP BY session_user_id, session_page';
978
                $result = $db->sql_query_limit($sql, $batch_size);
979
980
                $del_user_id = array();
981
                $del_sessions = 0;
982
983
                while ($row = $db->sql_fetchrow($result))
984
                {
985
                        $sql = 'UPDATE ' . USERS_TABLE . '
986
                                SET user_lastvisit = ' . (int) $row['recent_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
987
                                WHERE user_id = " . (int) $row['session_user_id'];
988
                        $db->sql_query($sql);
989
990
                        $del_user_id[] = (int) $row['session_user_id'];
991
                        $del_sessions++;
992
                }
993
                $db->sql_freeresult($result);
994
995
                if (sizeof($del_user_id))
996
                {
997
                        // Delete expired sessions
998
                        $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
999
                                WHERE ' . $db->sql_in_set('session_user_id', $del_user_id) . '
1000
                                        AND session_time < ' . ($this->time_now - $config['session_length']);
1001
                        $db->sql_query($sql);
1002
                }
1003
1004
                if ($del_sessions < $batch_size)
1005
                {
1006
                        // Less than 10 users, update gc timer ... else we want gc
1007
                        // called again to delete other sessions
1008
                        set_config('session_last_gc', $this->time_now, true);
1009
1010
                        if ($config['max_autologin_time'])
1011
                        {
1012
                                $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
1013
                                        WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time']));
1014
                                $db->sql_query($sql);
1015
                        }
1016
1017
                        // only called from CRON; should be a safe workaround until the infrastructure gets going
1018
                        if (!class_exists('phpbb_captcha_factory', false))
1019
                        {
1020
                                include($phpbb_root_path . "includes/captcha/captcha_factory." . $phpEx);
1021
                        }
1022
                        phpbb_captcha_factory::garbage_collect($config['captcha_plugin']);
1023
1024
                        $sql = 'DELETE FROM ' . LOGIN_ATTEMPT_TABLE . '
1025
                                WHERE attempt_time < ' . (time() - (int) $config['ip_login_limit_time']);
1026
                        $db->sql_query($sql);
1027
                }
1028
1029
                return;
1030
        }
1031
1032
        /**
1033
        * Sets a cookie
1034
        *
1035
        * Sets a cookie of the given name with the specified data for the given length of time. If no time is specified, a session cookie will be set.
1036
        *
1037
        * @param string $name                Name of the cookie, will be automatically prefixed with the phpBB cookie name. track becomes [cookie_name]_track then.
1038
        * @param string $cookiedata        The data to hold within the cookie
1039
        * @param int $cookietime        The expiration time as UNIX timestamp. If 0 is provided, a session cookie is set.
1040
        */
1041
        function set_cookie($name, $cookiedata, $cookietime)
1042
        {
1043
                global $config;
1044
1045
                $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
1046
                $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
1047
                $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];
1048
1049
                header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
1050
        }
1051
1052
        /**
1053
        * Check for banned user
1054
        *
1055
        * Checks whether the supplied user is banned by id, ip or email. If no parameters
1056
        * are passed to the method pre-existing session data is used. If $return is false
1057
        * this routine does not return on finding a banned user, it outputs a relevant
1058
        * message and stops execution.
1059
        *
1060
        * @param string|array        $user_ips        Can contain a string with one IP or an array of multiple IPs
1061
        */
1062
        function check_ban($user_id = false, $user_ips = false, $user_email = false, $return = false)
1063
        {
1064
                global $config, $db;
1065
1066
                if (defined('IN_CHECK_BAN'))
1067
                {
1068
                        return;
1069
                }
1070
1071
                $banned = false;
1072
                $cache_ttl = 3600;
1073
                $where_sql = array();
1074
1075
                $sql = 'SELECT ban_ip, ban_userid, ban_email, ban_exclude, ban_give_reason, ban_end
1076
                        FROM ' . BANLIST_TABLE . '
1077
                        WHERE ';
1078
1079
                // Determine which entries to check, only return those
1080
                if ($user_email === false)
1081
                {
1082
                        $where_sql[] = "ban_email = ''";
1083
                }
1084
1085
                if ($user_ips === false)
1086
                {
1087
                        $where_sql[] = "(ban_ip = '' OR ban_exclude = 1)";
1088
                }
1089
1090
                if ($user_id === false)
1091
                {
1092
                        $where_sql[] = '(ban_userid = 0 OR ban_exclude = 1)';
1093
                }
1094
                else
1095
                {
1096
                        $cache_ttl = ($user_id == ANONYMOUS) ? 3600 : 0;
1097
                        $_sql = '(ban_userid = ' . $user_id;
1098
1099
                        if ($user_email !== false)
1100
                        {
1101
                                $_sql .= " OR ban_email <> ''";
1102
                        }
1103
1104
                        if ($user_ips !== false)
1105
                        {
1106
                                $_sql .= " OR ban_ip <> ''";
1107
                        }
1108
1109
                        $_sql .= ')';
1110
1111
                        $where_sql[] = $_sql;
1112
                }
1113
1114
                $sql .= (sizeof($where_sql)) ? implode(' AND ', $where_sql) : '';
1115
                $result = $db->sql_query($sql, $cache_ttl);
1116
1117
                $ban_triggered_by = 'user';
1118
                while ($row = $db->sql_fetchrow($result))
1119
                {
1120
                        if ($row['ban_end'] && $row['ban_end'] < time())
1121
                        {
1122
                                continue;
1123
                        }
1124
1125
                        $ip_banned = false;
1126
                        if (!empty($row['ban_ip']))
1127
                        {
1128
                                if (!is_array($user_ips))
1129
                                {
1130
                                        $ip_banned = preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ips);
1131
                                }
1132
                                else
1133
                                {
1134
                                        foreach ($user_ips as $user_ip)
1135
                                        {
1136
                                                if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_ip'], '#')) . '$#i', $user_ip))
1137
                                                {
1138
                                                        $ip_banned = true;
1139
                                                        break;
1140
                                                }
1141
                                        }
1142
                                }
1143
                        }
1144
1145
                        if ((!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id) ||
1146
                                $ip_banned ||
1147
                                (!empty($row['ban_email']) && preg_match('#^' . str_replace('\*', '.*?', preg_quote($row['ban_email'], '#')) . '$#i', $user_email)))
1148
                        {
1149
                                if (!empty($row['ban_exclude']))
1150
                                {
1151
                                        $banned = false;
1152
                                        break;
1153
                                }
1154
                                else
1155
                                {
1156
                                        $banned = true;
1157
                                        $ban_row = $row;
1158
1159
                                        if (!empty($row['ban_userid']) && intval($row['ban_userid']) == $user_id)
1160
                                        {
1161
                                                $ban_triggered_by = 'user';
1162
                                        }
1163
                                        else if ($ip_banned)
1164
                                        {
1165
                                                $ban_triggered_by = 'ip';
1166
                                        }
1167
                                        else
1168
                                        {
1169
                                                $ban_triggered_by = 'email';
1170
                                        }
1171
1172
                                        // Don't break. Check if there is an exclude rule for this user
1173
                                }
1174
                        }
1175
                }
1176
                $db->sql_freeresult($result);
1177
1178
                if ($banned && !$return)
1179
                {
1180
                        global $template;
1181
1182
                        // If the session is empty we need to create a valid one...
1183
                        if (empty($this->session_id))
1184
                        {
1185
                                // This seems to be no longer needed? - #14971
1186
//                                $this->session_create(ANONYMOUS);
1187
                        }
1188
1189
                        // Initiate environment ... since it won't be set at this stage
1190
                        $this->setup();
1191
1192
                        // Logout the user, banned users are unable to use the normal 'logout' link
1193
                        if ($this->data['user_id'] != ANONYMOUS)
1194
                        {
1195
                                $this->session_kill();
1196
                        }
1197
1198
                        // We show a login box here to allow founders accessing the board if banned by IP
1199
                        if (defined('IN_LOGIN') && $this->data['user_id'] == ANONYMOUS)
1200
                        {
1201
                                global $phpEx;
1202
1203
                                $this->setup('ucp');
1204
                                $this->data['is_registered'] = $this->data['is_bot'] = false;
1205
1206
                                // Set as a precaution to allow login_box() handling this case correctly as well as this function not being executed again.
1207
                                define('IN_CHECK_BAN', 1);
1208
1209
                                login_box("index.$phpEx");
1210
1211
                                // The false here is needed, else the user is able to circumvent the ban.
1212
                                $this->session_kill(false);
1213
                        }
1214
1215
                        // Ok, we catch the case of an empty session id for the anonymous user...
1216
                        // This can happen if the user is logging in, banned by username and the login_box() being called "again".
1217
                        if (empty($this->session_id) && defined('IN_CHECK_BAN'))
1218
                        {
1219
                                $this->session_create(ANONYMOUS);
1220
                        }
1221
1222
1223
                        // Determine which message to output
1224
                        $till_date = ($ban_row['ban_end']) ? $this->format_date($ban_row['ban_end']) : '';
1225
                        $message = ($ban_row['ban_end']) ? 'BOARD_BAN_TIME' : 'BOARD_BAN_PERM';
1226
1227
                        $message = sprintf($this->lang[$message], $till_date, '<a href="mailto:' . $config['board_contact'] . '">', '</a>');
1228
                        $message .= ($ban_row['ban_give_reason']) ? '<br /><br />' . sprintf($this->lang['BOARD_BAN_REASON'], $ban_row['ban_give_reason']) : '';
1229
                        $message .= '<br /><br /><em>' . $this->lang['BAN_TRIGGERED_BY_' . strtoupper($ban_triggered_by)] . '</em>';
1230
1231
                        // To circumvent session_begin returning a valid value and the check_ban() not called on second page view, we kill the session again
1232
                        $this->session_kill(false);
1233
1234
                        // A very special case... we are within the cron script which is not supposed to print out the ban message... show blank page
1235
                        if (defined('IN_CRON'))
1236
                        {
1237
                                garbage_collection();
1238
                                exit_handler();
1239
                                exit;
1240
                        }
1241
1242
                        trigger_error($message);
1243
                }
1244
1245
                return ($banned && $ban_row['ban_give_reason']) ? $ban_row['ban_give_reason'] : $banned;
1246
        }
1247
1248
        /**
1249
        * Check if ip is blacklisted
1250
        * This should be called only where absolutly necessary
1251
        *
1252
        * Only IPv4 (rbldns does not support AAAA records/IPv6 lookups)
1253
        *
1254
        * @author satmd (from the php manual)
1255
        * @param string $mode register/post - spamcop for example is ommitted for posting
1256
        * @return false if ip is not blacklisted, else an array([checked server], [lookup])
1257
        */
1258
        function check_dnsbl($mode, $ip = false)
1259
        {
1260
                if ($ip === false)
1261
                {
1262
                        $ip = $this->ip;
1263
                }
1264
1265
                // Neither Spamhaus nor Spamcop supports IPv6 addresses.
1266
                if (strpos($ip, ':') !== false)
1267
                {
1268
                        return false;
1269
                }
1270
1271
                $dnsbl_check = array(
1272
                        'sbl.spamhaus.org'        => 'http://www.spamhaus.org/query/bl?ip=',
1273
                );
1274
1275
                if ($mode == 'register')
1276
                {
1277
                        $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
1278
                }
1279
1280
                if ($ip)
1281
                {
1282
                        $quads = explode('.', $ip);
1283
                        $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
1284
1285
                        // Need to be listed on all servers...
1286
                        $listed = true;
1287
                        $info = array();
1288
1289
                        foreach ($dnsbl_check as $dnsbl => $lookup)
1290
                        {
1291
                                if (phpbb_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
1292
                                {
1293
                                        $info = array($dnsbl, $lookup . $ip);
1294
                                }
1295
                                else
1296
                                {
1297
                                        $listed = false;
1298
                                }
1299
                        }
1300
1301
                        if ($listed)
1302
                        {
1303
                                return $info;
1304
                        }
1305
                }
1306
1307
                return false;
1308
        }
1309
1310
        /**
1311
        * Check if URI is blacklisted
1312
        * This should be called only where absolutly necessary, for example on the submitted website field
1313
        * This function is not in use at the moment and is only included for testing purposes, it may not work at all!
1314
        * This means it is untested at the moment and therefore commented out
1315
        *
1316
        * @param string $uri URI to check
1317
        * @return true if uri is on blacklist, else false. Only blacklist is checked (~zero FP), no grey lists
1318
        function check_uribl($uri)
1319
        {
1320
                // Normally parse_url() is not intended to parse uris
1321
                // We need to get the top-level domain name anyway... change.
1322
                $uri = parse_url($uri);
1323
1324
                if ($uri === false || empty($uri['host']))
1325
                {
1326
                        return false;
1327
                }
1328
1329
                $uri = trim($uri['host']);
1330
1331
                if ($uri)
1332
                {
1333
                        // One problem here... the return parameter for the "windows" method is different from what
1334
                        // we expect... this may render this check useless...
1335
                        if (phpbb_checkdnsrr($uri . '.multi.uribl.com.', 'A') === true)
1336
                        {
1337
                                return true;
1338
                        }
1339
                }
1340
1341
                return false;
1342
        }
1343
        */
1344
1345
        /**
1346
        * Set/Update a persistent login key
1347
        *
1348
        * This method creates or updates a persistent session key. When a user makes
1349
        * use of persistent (formerly auto-) logins a key is generated and stored in the
1350
        * DB. When they revisit with the same key it's automatically updated in both the
1351
        * DB and cookie. Multiple keys may exist for each user representing different
1352
        * browsers or locations. As with _any_ non-secure-socket no passphrase login this
1353
        * remains vulnerable to exploit.
1354
        */
1355
        function set_login_key($user_id = false, $key = false, $user_ip = false)
1356
        {
1357
                global $config, $db;
1358
1359
                $user_id = ($user_id === false) ? $this->data['user_id'] : $user_id;
1360
                $user_ip = ($user_ip === false) ? $this->ip : $user_ip;
1361
                $key = ($key === false) ? (($this->cookie_data['k']) ? $this->cookie_data['k'] : false) : $key;
1362
1363
                $key_id = unique_id(hexdec(substr($this->session_id, 0, 8)));
1364
1365
                $sql_ary = array(
1366
                        'key_id'                => (string) md5($key_id),
1367
                        'last_ip'                => (string) $this->ip,
1368
                        'last_login'        => (int) time()
1369
                );
1370
1371
                if (!$key)
1372
                {
1373
                        $sql_ary += array(
1374
                                'user_id'        => (int) $user_id
1375
                        );
1376
                }
1377
1378
                if ($key)
1379
                {
1380
                        $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . '
1381
                                SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
1382
                                WHERE user_id = ' . (int) $user_id . "
1383
                                        AND key_id = '" . $db->sql_escape(md5($key)) . "'";
1384
                }
1385
                else
1386
                {
1387
                        $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
1388
                }
1389
                $db->sql_query($sql);
1390
1391
                $this->cookie_data['k'] = $key_id;
1392
1393
                return false;
1394
        }
1395
1396
        /**
1397
        * Reset all login keys for the specified user
1398
        *
1399
        * This method removes all current login keys for a specified (or the current)
1400
        * user. It will be called on password change to render old keys unusable
1401
        */
1402
        function reset_login_keys($user_id = false)
1403
        {
1404
                global $config, $db;
1405
1406
                $user_id = ($user_id === false) ? (int) $this->data['user_id'] : (int) $user_id;
1407
1408
                $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
1409
                        WHERE user_id = ' . (int) $user_id;
1410
                $db->sql_query($sql);
1411
1412
                // If the user is logged in, update last visit info first before deleting sessions
1413
                $sql = 'SELECT session_time, session_page
1414
                        FROM ' . SESSIONS_TABLE . '
1415
                        WHERE session_user_id = ' . (int) $user_id . '
1416
                        ORDER BY session_time DESC';
1417
                $result = $db->sql_query_limit($sql, 1);
1418
                $row = $db->sql_fetchrow($result);
1419
                $db->sql_freeresult($result);
1420
1421
                if ($row)
1422
                {
1423
                        $sql = 'UPDATE ' . USERS_TABLE . '
1424
                                SET user_lastvisit = ' . (int) $row['session_time'] . ", user_lastpage = '" . $db->sql_escape($row['session_page']) . "'
1425
                                WHERE user_id = " . (int) $user_id;
1426
                        $db->sql_query($sql);
1427
                }
1428
1429
                // Let's also clear any current sessions for the specified user_id
1430
                // If it's the current user then we'll leave this session intact
1431
                $sql_where = 'session_user_id = ' . (int) $user_id;
1432
                $sql_where .= ($user_id === (int) $this->data['user_id']) ? " AND session_id <> '" . $db->sql_escape($this->session_id) . "'" : '';
1433
1434
                $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
1435
                        WHERE $sql_where";
1436
                $db->sql_query($sql);
1437
1438
                // We're changing the password of the current user and they have a key
1439
                // Lets regenerate it to be safe
1440
                if ($user_id === (int) $this->data['user_id'] && $this->cookie_data['k'])
1441
                {
1442
                        $this->set_login_key($user_id);
1443
                }
1444
        }
1445
1446
1447
        /**
1448
        * Check if the request originated from the same page.
1449
        * @param bool $check_script_path If true, the path will be checked as well
1450
        */
1451
        function validate_referer($check_script_path = false)
1452
        {
1453
                global $config, $request;
1454
1455
                // no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
1456
                if (empty($this->referer) || empty($this->host))
1457
                {
1458
                        return true;
1459
                }
1460
1461
                $host = htmlspecialchars($this->host);
1462
                $ref = substr($this->referer, strpos($this->referer, '://') + 3);
1463
1464
                if (!(stripos($ref, $host) === 0) && (!$config['force_server_vars'] || !(stripos($ref, $config['server_name']) === 0)))
1465
                {
1466
                        return false;
1467
                }
1468
                else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '')
1469
                {
1470
                        $ref = substr($ref, strlen($host));
1471
                        $server_port = $request->server('SERVER_PORT', 0);
1472
1473
                        if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
1474
                        {
1475
                                $ref = substr($ref, strlen(":$server_port"));
1476
                        }
1477
1478
                        if (!(stripos(rtrim($ref, '/'), rtrim($this->page['root_script_path'], '/')) === 0))
1479
                        {
1480
                                return false;
1481
                        }
1482
                }
1483
1484
                return true;
1485
        }
1486
1487
1488
        function unset_admin()
1489
        {
1490
                global $db;
1491
                $sql = 'UPDATE ' . SESSIONS_TABLE . '
1492
                        SET session_admin = 0
1493
                        WHERE session_id = \'' . $db->sql_escape($this->session_id) . '\'';
1494
                $db->sql_query($sql);
1495
        }
1496
1497
        /**
1498
        * Update the session data
1499
        *
1500
        * @param array $session_data associative array of session keys to be updated
1501
        * @param string $session_id optional session_id, defaults to current user's session_id
1502
        */
1503
        public function update_session($session_data, $session_id = null)
1504
        {
1505
                global $db;
1506
1507
                $session_id = ($session_id) ? $session_id : $this->session_id;
1508
1509
                $sql = 'UPDATE ' . SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $session_data) . "
1510
                        WHERE session_id = '" . $db->sql_escape($session_id) . "'";
1511
                $db->sql_query($sql);
1512
        }
1513
}
1514
1515
1516
/**
1517
* Base user class
1518
*
1519
* This is the overarching class which contains (through session extend)
1520
* all methods utilised for user functionality during a session.
1521
*
1522
* @package phpBB3
1523
*/
1524
class user extends session
1525
{
1526
        var $lang = array();
1527
        var $help = array();
1528
        var $theme = array();
1529
        var $date_format;
1530
        var $timezone;
1531
        var $dst;
1532
1533
        var $lang_name = false;
1534
        var $lang_id = false;
1535
        var $lang_path;
1536
        var $img_lang;
1537
        var $img_array = array();
1538
1539
        // Able to add new options (up to id 31)
1540
        var $keyoptions = array('viewimg' => 0, 'viewflash' => 1, 'viewsmilies' => 2, 'viewsigs' => 3, 'viewavatars' => 4, 'viewcensors' => 5, 'attachsig' => 6, 'bbcode' => 8, 'smilies' => 9, 'popuppm' => 10, 'sig_bbcode' => 15, 'sig_smilies' => 16, 'sig_links' => 17);
1541
1542
        /**
1543
        * Constructor to set the lang path
1544
        */
1545
        function user()
1546
        {
1547
                global $phpbb_root_path;
1548
1549
                $this->lang_path = $phpbb_root_path . 'language/';
1550
        }
1551
1552
        /**
1553
        * Function to set custom language path (able to use directory outside of phpBB)
1554
        *
1555
        * @param string $lang_path New language path used.
1556
        * @access public
1557
        */
1558
        function set_custom_lang_path($lang_path)
1559
        {
1560
                $this->lang_path = $lang_path;
1561
1562
                if (substr($this->lang_path, -1) != '/')
1563
                {
1564
                        $this->lang_path .= '/';
1565
                }
1566
        }
1567
1568
        /**
1569
        * Setup basic user-specific items (style, language, ...)
1570
        */
1571
        function setup($lang_set = false, $style = false)
1572
        {
1573
                global $db, $template, $config, $auth, $phpEx, $phpbb_root_path, $cache;
1574
1575
                if ($this->data['user_id'] != ANONYMOUS)
1576
                {
1577
                        $this->lang_name = (file_exists($this->lang_path . $this->data['user_lang'] . "/common.$phpEx")) ? $this->data['user_lang'] : basename($config['default_lang']);
1578
1579
                        $this->date_format = $this->data['user_dateformat'];
1580
                        $this->timezone = $this->data['user_timezone'] * 3600;
1581
                        $this->dst = $this->data['user_dst'] * 3600;
1582
                }
1583
                else
1584
                {
1585
                        $this->lang_name = basename($config['default_lang']);
1586
                        $this->date_format = $config['default_dateformat'];
1587
                        $this->timezone = $config['board_timezone'] * 3600;
1588
                        $this->dst = $config['board_dst'] * 3600;
1589
1590
                        /**
1591
                        * If a guest user is surfing, we try to guess his/her language first by obtaining the browser language
1592
                        * If re-enabled we need to make sure only those languages installed are checked
1593
                        * Commented out so we do not loose the code.
1594
1595
                        if ($request->header('Accept-Language'))
1596
                        {
1597
                                $accept_lang_ary = explode(',', $request->header('Accept-Language'));
1598
1599
                                foreach ($accept_lang_ary as $accept_lang)
1600
                                {
1601
                                        // Set correct format ... guess full xx_YY form
1602
                                        $accept_lang = substr($accept_lang, 0, 2) . '_' . strtoupper(substr($accept_lang, 3, 2));
1603
                                        $accept_lang = basename($accept_lang);
1604
1605
                                        if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx"))
1606
                                        {
1607
                                                $this->lang_name = $config['default_lang'] = $accept_lang;
1608
                                                break;
1609
                                        }
1610
                                        else
1611
                                        {
1612
                                                // No match on xx_YY so try xx
1613
                                                $accept_lang = substr($accept_lang, 0, 2);
1614
                                                $accept_lang = basename($accept_lang);
1615
1616
                                                if (file_exists($this->lang_path . $accept_lang . "/common.$phpEx"))
1617
                                                {
1618
                                                        $this->lang_name = $config['default_lang'] = $accept_lang;
1619
                                                        break;
1620
                                                }
1621
                                        }
1622
                                }
1623
                        }
1624
                        */
1625
                }
1626
1627
                // We include common language file here to not load it every time a custom language file is included
1628
                $lang = &$this->lang;
1629
1630
                // Do not suppress error if in DEBUG_EXTRA mode
1631
                $include_result = (defined('DEBUG_EXTRA')) ? (include $this->lang_path . $this->lang_name . "/common.$phpEx") : (@include $this->lang_path . $this->lang_name . "/common.$phpEx");
1632
1633
                if ($include_result === false)
1634
                {
1635
                        die('Language file ' . $this->lang_path . $this->lang_name . "/common.$phpEx" . " couldn't be opened.");
1636
                }
1637
1638
                $this->add_lang($lang_set);
1639
                unset($lang_set);
1640
1641
                $style_request = request_var('style', 0);
1642
                if ($style_request && $auth->acl_get('a_styles') && !defined('ADMIN_START'))
1643
                {
1644
                        global $SID, $_EXTRA_URL;
1645
1646
                        $style = $style_request;
1647
                        $SID .= '&amp;style=' . $style;
1648
                        $_EXTRA_URL = array('style=' . $style);
1649
                }
1650
                else
1651
                {
1652
                        // Set up style
1653
                        $style = ($style) ? $style : ((!$config['override_user_style']) ? $this->data['user_style'] : $config['default_style']);
1654
                }
1655
1656
                $sql = 'SELECT s.style_id, t.template_path, t.template_id, t.bbcode_bitfield, t.template_inherits_id, t.template_inherit_path, c.theme_path, c.theme_name, c.theme_id
1657
                        FROM ' . STYLES_TABLE . ' s, ' . STYLES_TEMPLATE_TABLE . ' t, ' . STYLES_THEME_TABLE . " c
1658
                        WHERE s.style_id = $style
1659
                                AND t.template_id = s.template_id
1660
                                AND c.theme_id = s.theme_id";
1661
                $result = $db->sql_query($sql, 3600);
1662
                $this->theme = $db->sql_fetchrow($result);
1663
                $db->sql_freeresult($result);
1664
1665
                // User has wrong style
1666
                if (!$this->theme && $style == $this->data['user_style'])
1667
                {
1668
                        $style = $this->data['user_style'] = $config['default_style'];
1669
1670
                        $sql = 'UPDATE ' . USERS_TABLE . "
1671
                                SET user_style = $style
1672
                                WHERE user_id = {$this->data['user_id']}";
1673
                        $db->sql_query($sql);
1674
1675
                        $sql = 'SELECT s.style_id, t.template_path, t.template_id, t.bbcode_bitfield, c.theme_path, c.theme_name, c.theme_id
1676
                                FROM ' . STYLES_TABLE . ' s, ' . STYLES_TEMPLATE_TABLE . ' t, ' . STYLES_THEME_TABLE . " c
1677
                                WHERE s.style_id = $style
1678
                                        AND t.template_id = s.template_id
1679
                                        AND c.theme_id = s.theme_id";
1680
                        $result = $db->sql_query($sql, 3600);
1681
                        $this->theme = $db->sql_fetchrow($result);
1682
                        $db->sql_freeresult($result);
1683
                }
1684
1685
                if (!$this->theme)
1686
                {
1687
                        trigger_error('Could not get style data', E_USER_ERROR);
1688
                }
1689
1690
                // Now parse the cfg file and cache it
1691
                $parsed_items = $cache->obtain_cfg_items($this->theme);
1692
1693
                // We are only interested in the theme configuration for now
1694
                $parsed_items = $parsed_items['theme'];
1695
1696
                $check_for = array(
1697
                        'pagination_sep'        => (string) ', '
1698
                );
1699
1700
                foreach ($check_for as $key => $default_value)
1701
                {
1702
                        $this->theme[$key] = (isset($parsed_items[$key])) ? $parsed_items[$key] : $default_value;
1703
                        settype($this->theme[$key], gettype($default_value));
1704
1705
                        if (is_string($default_value))
1706
                        {
1707
                                $this->theme[$key] = htmlspecialchars($this->theme[$key]);
1708
                        }
1709
                }
1710
1711
                $template->set_template();
1712
1713
                $this->img_lang = $this->lang_name;
1714
1715
                // Call phpbb_user_session_handler() in case external application want to "bend" some variables or replace classes...
1716
                // After calling it we continue script execution...
1717
                phpbb_user_session_handler();
1718
1719
                // If this function got called from the error handler we are finished here.
1720
                if (defined('IN_ERROR_HANDLER'))
1721
                {
1722
                        return;
1723
                }
1724
1725
                // Disable board if the install/ directory is still present
1726
                // For the brave development army we do not care about this, else we need to comment out this everytime we develop locally
1727
                if (!defined('DEBUG_EXTRA') && !defined('ADMIN_START') && !defined('IN_INSTALL') && !defined('IN_LOGIN') && file_exists($phpbb_root_path . 'install') && !is_file($phpbb_root_path . 'install'))
1728
                {
1729
                        // Adjust the message slightly according to the permissions
1730
                        if ($auth->acl_gets('a_', 'm_') || $auth->acl_getf_global('m_'))
1731
                        {
1732
                                $message = 'REMOVE_INSTALL';
1733
                        }
1734
                        else
1735
                        {
1736
                                $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE';
1737
                        }
1738
                        trigger_error($message);
1739
                }
1740
1741
                // Is board disabled and user not an admin or moderator?
1742
                if ($config['board_disable'] && !defined('IN_LOGIN') && !$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_'))
1743
                {
1744
                        if ($this->data['is_bot'])
1745
                        {
1746
                                send_status_line(503, 'Service Unavailable');
1747
                        }
1748
1749
                        $message = (!empty($config['board_disable_msg'])) ? $config['board_disable_msg'] : 'BOARD_DISABLE';
1750
                        trigger_error($message);
1751
                }
1752
1753
                // Is load exceeded?
1754
                if ($config['limit_load'] && $this->load !== false)
1755
                {
1756
                        if ($this->load > floatval($config['limit_load']) && !defined('IN_LOGIN') && !defined('IN_ADMIN'))
1757
                        {
1758
                                // Set board disabled to true to let the admins/mods get the proper notification
1759
                                $config['board_disable'] = '1';
1760
1761
                                if (!$auth->acl_gets('a_', 'm_') && !$auth->acl_getf_global('m_'))
1762
                                {
1763
                                        if ($this->data['is_bot'])
1764
                                        {
1765
                                                send_status_line(503, 'Service Unavailable');
1766
                                        }
1767
                                        trigger_error('BOARD_UNAVAILABLE');
1768
                                }
1769
                        }
1770
                }
1771
1772
                if (isset($this->data['session_viewonline']))
1773
                {
1774
                        // Make sure the user is able to hide his session
1775
                        if (!$this->data['session_viewonline'])
1776
                        {
1777
                                // Reset online status if not allowed to hide the session...
1778
                                if (!$auth->acl_get('u_hideonline'))
1779
                                {
1780
                                        $sql = 'UPDATE ' . SESSIONS_TABLE . '
1781
                                                SET session_viewonline = 1
1782
                                                WHERE session_user_id = ' . $this->data['user_id'];
1783
                                        $db->sql_query($sql);
1784
                                        $this->data['session_viewonline'] = 1;
1785
                                }
1786
                        }
1787
                        else if (!$this->data['user_allow_viewonline'])
1788
                        {
1789
                                // the user wants to hide and is allowed to  -> cloaking device on.
1790
                                if ($auth->acl_get('u_hideonline'))
1791
                                {
1792
                                        $sql = 'UPDATE ' . SESSIONS_TABLE . '
1793
                                                SET session_viewonline = 0
1794
                                                WHERE session_user_id = ' . $this->data['user_id'];
1795
                                        $db->sql_query($sql);
1796
                                        $this->data['session_viewonline'] = 0;
1797
                                }
1798
                        }
1799
                }
1800
1801
1802
                // Does the user need to change their password? If so, redirect to the
1803
                // ucp profile reg_details page ... of course do not redirect if we're already in the ucp
1804
                if (!defined('IN_ADMIN') && !defined('ADMIN_START') && $config['chg_passforce'] && !empty($this->data['is_registered']) && $auth->acl_get('u_chgpasswd') && $this->data['user_passchg'] < time() - ($config['chg_passforce'] * 86400))
1805
                {
1806
                        if (strpos($this->page['query_string'], 'mode=reg_details') === false && $this->page['page_name'] != "ucp.$phpEx")
1807
                        {
1808
                                redirect(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=profile&amp;mode=reg_details'));
1809
                        }
1810
                }
1811
1812
                return;
1813
        }
1814
1815
        /**
1816
        * More advanced language substitution
1817
        * Function to mimic sprintf() with the possibility of using phpBB's language system to substitute nullar/singular/plural forms.
1818
        * Params are the language key and the parameters to be substituted.
1819
        * This function/functionality is inspired by SHS` and Ashe.
1820
        *
1821
        * Example call: <samp>$user->lang('NUM_POSTS_IN_QUEUE', 1);</samp>
1822
        *
1823
        * If the first parameter is an array, the elements are used as keys and subkeys to get the language entry:
1824
        * Example: <samp>$user->lang(array('datetime', 'AGO'), 1)</samp> uses $user->lang['datetime']['AGO'] as language entry.
1825
        */
1826
        function lang()
1827
        {
1828
                $args = func_get_args();
1829
                $key = $args[0];
1830
1831
                if (is_array($key))
1832
                {
1833
                        $lang = &$this->lang[array_shift($key)];
1834
1835
                        foreach ($key as $_key)
1836
                        {
1837
                                $lang = &$lang[$_key];
1838
                        }
1839
                }
1840
                else
1841
                {
1842
                        $lang = &$this->lang[$key];
1843
                }
1844
1845
                // Return if language string does not exist
1846
                if (!isset($lang) || (!is_string($lang) && !is_array($lang)))
1847
                {
1848
                        return $key;
1849
                }
1850
1851
                // If the language entry is a string, we simply mimic sprintf() behaviour
1852
                if (is_string($lang))
1853
                {
1854
                        if (sizeof($args) == 1)
1855
                        {
1856
                                return $lang;
1857
                        }
1858
1859
                        // Replace key with language entry and simply pass along...
1860
                        $args[0] = $lang;
1861
                        return call_user_func_array('sprintf', $args);
1862
                }
1863
                else if (sizeof($lang) == 0)
1864
                {
1865
                        // If the language entry is an empty array, we just return the language key
1866
                        return $args[0];
1867
                }
1868
1869
                // It is an array... now handle different nullar/singular/plural forms
1870
                $key_found = false;
1871
1872
                // We now get the first number passed and will select the key based upon this number
1873
                for ($i = 1, $num_args = sizeof($args); $i < $num_args; $i++)
1874
                {
1875
                        if (is_int($args[$i]) || is_float($args[$i]))
1876
                        {
1877
                                if ($args[$i] == 0 && isset($lang[0]))
1878
                                {
1879
                                        // We allow each translation using plural forms to specify a version for the case of 0 things,
1880
                                        // so that "0 users" may be displayed as "No users".
1881
                                        $key_found = 0;
1882
                                        break;
1883
                                }
1884
                                else
1885
                                {
1886
                                        $use_plural_form = $this->get_plural_form($args[$i]);
1887
                                        if (isset($lang[$use_plural_form]))
1888
                                        {
1889
                                                // The key we should use exists, so we use it.
1890
                                                $key_found = $use_plural_form;
1891
                                        }
1892
                                        else
1893
                                        {
1894
                                                // If the key we need to use does not exist, we fall back to the previous one.
1895
                                                $numbers = array_keys($lang);
1896
1897
                                                foreach ($numbers as $num)
1898
                                                {
1899
                                                        if ($num > $use_plural_form)
1900
                                                        {
1901
                                                                break;
1902
                                                        }
1903
1904
                                                        $key_found = $num;
1905
                                                }
1906
                                        }
1907
                                        break;
1908
                                }
1909
                        }
1910
                }
1911
1912
                // Ok, let's check if the key was found, else use the last entry (because it is mostly the plural form)
1913
                if ($key_found === false)
1914
                {
1915
                        $numbers = array_keys($lang);
1916
                        $key_found = end($numbers);
1917
                }
1918
1919
                // Use the language string we determined and pass it to sprintf()
1920
                $args[0] = $lang[$key_found];
1921
                return call_user_func_array('sprintf', $args);
1922
        }
1923
1924
        /**
1925
        * Determine which plural form we should use.
1926
        * For some languages this is not as simple as for English.
1927
        *
1928
        * @param $number                int|float        The number we want to get the plural case for. Float numbers are floored.
1929
        * @param $force_rule        mixed        False to use the plural rule of the language package
1930
        *                                                                or an integer to force a certain plural rule
1931
        * @return        int                The plural-case we need to use for the number plural-rule combination
1932
        */
1933
        function get_plural_form($number, $force_rule = false)
1934
        {
1935
                $number = (int) $number;
1936
1937
                // Default to English system
1938
                $plural_rule = ($force_rule !== false) ? $force_rule : ((isset($this->lang['PLURAL_RULE'])) ? $this->lang['PLURAL_RULE'] : 1);
1939
1940
                return phpbb_get_plural_form($plural_rule, $number);
1941
        }
1942
1943
        /**
1944
        * Add Language Items - use_db and use_help are assigned where needed (only use them to force inclusion)
1945
        *
1946
        * @param mixed $lang_set specifies the language entries to include
1947
        * @param bool $use_db internal variable for recursion, do not use
1948
        * @param bool $use_help internal variable for recursion, do not use
1949
        * @param string $ext_name The extension to load language from, or empty for core files
1950
        *
1951
        * Examples:
1952
        * <code>
1953
        * $lang_set = array('posting', 'help' => 'faq');
1954
        * $lang_set = array('posting', 'viewtopic', 'help' => array('bbcode', 'faq'))
1955
        * $lang_set = array(array('posting', 'viewtopic'), 'help' => array('bbcode', 'faq'))
1956
        * $lang_set = 'posting'
1957
        * $lang_set = array('help' => 'faq', 'db' => array('help:faq', 'posting'))
1958
        * </code>
1959
        */
1960
        function add_lang($lang_set, $use_db = false, $use_help = false, $ext_name = '')
1961
        {
1962
                global $phpEx;
1963
1964
                if (is_array($lang_set))
1965
                {
1966
                        foreach ($lang_set as $key => $lang_file)
1967
                        {
1968
                                // Please do not delete this line.
1969
                                // We have to force the type here, else [array] language inclusion will not work
1970
                                $key = (string) $key;
1971
1972
                                if ($key == 'db')
1973
                                {
1974
                                        $this->add_lang($lang_file, true, $use_help, $ext_name);
1975
                                }
1976
                                else if ($key == 'help')
1977
                                {
1978
                                        $this->add_lang($lang_file, $use_db, true, $ext_name);
1979
                                }
1980
                                else if (!is_array($lang_file))
1981
                                {
1982
                                        $this->set_lang($this->lang, $this->help, $lang_file, $use_db, $use_help, $ext_name);
1983
                                }
1984
                                else
1985
                                {
1986
                                        $this->add_lang($lang_file, $use_db, $use_help, $ext_name);
1987
                                }
1988
                        }
1989
                        unset($lang_set);
1990
                }
1991
                else if ($lang_set)
1992
                {
1993
                        $this->set_lang($this->lang, $this->help, $lang_set, $use_db, $use_help, $ext_name);
1994
                }
1995
        }
1996
1997
        /**
1998
        * Add Language Items from an extension - use_db and use_help are assigned where needed (only use them to force inclusion)
1999
        *
2000
        * @param string $ext_name The extension to load language from, or empty for core files
2001
        * @param mixed $lang_set specifies the language entries to include
2002
        * @param bool $use_db internal variable for recursion, do not use
2003
        * @param bool $use_help internal variable for recursion, do not use
2004
        */
2005
        function add_lang_ext($ext_name, $lang_set, $use_db = false, $use_help = false)
2006
        {
2007
                if ($ext_name === '/')
2008
                {
2009
                        $ext_name = '';
2010
                }
2011
2012
                $this->add_lang($lang_set, $use_db, $use_help, $ext_name);
2013
        }
2014
2015
        /**
2016
        * Set language entry (called by add_lang)
2017
        * @access private
2018
        */
2019
        function set_lang(&$lang, &$help, $lang_file, $use_db = false, $use_help = false, $ext_name = '')
2020
        {
2021
                global $phpbb_root_path, $phpEx;
2022
2023
                // Make sure the language name is set (if the user setup did not happen it is not set)
2024
                if (!$this->lang_name)
2025
                {
2026
                        global $config;
2027
                        $this->lang_name = basename($config['default_lang']);
2028
                }
2029
2030
                // $lang == $this->lang
2031
                // $help == $this->help
2032
                // - add appropriate variables here, name them as they are used within the language file...
2033
                if (!$use_db)
2034
                {
2035
                        if ($use_help && strpos($lang_file, '/') !== false)
2036
                        {
2037
                                $filename = dirname($lang_file) . '/help_' . basename($lang_file);
2038
                        }
2039
                        else
2040
                        {
2041
                                $filename = (($use_help) ? 'help_' : '') . $lang_file;
2042
                        }
2043
2044
                        if ($ext_name)
2045
                        {
2046
                                global $phpbb_extension_manager;
2047
                                $ext_path = $phpbb_extension_manager->get_extension_path($ext_name, true);
2048
2049
                                $lang_path = $ext_path . 'language/';
2050
                        }
2051
                        else
2052
                        {
2053
                                $lang_path = $this->lang_path;
2054
                        }
2055
2056
                        if (strpos($phpbb_root_path . $filename, $lang_path . $this->lang_name . '/') === 0)
2057
                        {
2058
                                $language_filename = $phpbb_root_path . $filename;
2059
                        }
2060
                        else
2061
                        {
2062
                                $language_filename = $lang_path . $this->lang_name . '/' . $filename . '.' . $phpEx;
2063
                        }
2064
2065
                        if (!file_exists($language_filename))
2066
                        {
2067
                                global $config;
2068
2069
                                if ($this->lang_name == 'en')
2070
                                {
2071
                                        // The user's selected language is missing the file, the board default's language is missing the file, and the file doesn't exist in /en.
2072
                                        $language_filename = str_replace($lang_path . 'en', $lang_path . $this->data['user_lang'], $language_filename);
2073
                                        trigger_error('Language file ' . $language_filename . ' couldn\'t be opened.', E_USER_ERROR);
2074
                                }
2075
                                else if ($this->lang_name == basename($config['default_lang']))
2076
                                {
2077
                                        // Fall back to the English Language
2078
                                        $this->lang_name = 'en';
2079
                                        $this->set_lang($lang, $help, $lang_file, $use_db, $use_help, $ext_name);
2080
                                }
2081
                                else if ($this->lang_name == $this->data['user_lang'])
2082
                                {
2083
                                        // Fall back to the board default language
2084
                                        $this->lang_name = basename($config['default_lang']);
2085
                                        $this->set_lang($lang, $help, $lang_file, $use_db, $use_help, $ext_name);
2086
                                }
2087
2088
                                // Reset the lang name
2089
                                $this->lang_name = (file_exists($lang_path . $this->data['user_lang'] . "/common.$phpEx")) ? $this->data['user_lang'] : basename($config['default_lang']);
2090
                                return;
2091
                        }
2092
2093
                        // Do not suppress error if in DEBUG_EXTRA mode
2094
                        $include_result = (defined('DEBUG_EXTRA')) ? (include $language_filename) : (@include $language_filename);
2095
2096
                        if ($include_result === false)
2097
                        {
2098
                                trigger_error('Language file ' . $language_filename . ' couldn\'t be opened.', E_USER_ERROR);
2099
                        }
2100
                }
2101
                else if ($use_db)
2102
                {
2103
                        // Get Database Language Strings
2104
                        // Put them into $lang if nothing is prefixed, put them into $help if help: is prefixed
2105
                        // For example: help:faq, posting
2106
                }
2107
        }
2108
2109
        /**
2110
        * Format user date
2111
        *
2112
        * @param int $gmepoch unix timestamp
2113
        * @param string $format date format in date() notation. | used to indicate relative dates, for example |d m Y|, h:i is translated to Today, h:i.
2114
        * @param bool $forcedate force non-relative date format.
2115
        *
2116
        * @return mixed translated date
2117
        */
2118
        function format_date($gmepoch, $format = false, $forcedate = false)
2119
        {
2120
                static $midnight;
2121
                static $date_cache;
2122
2123
                $format = (!$format) ? $this->date_format : $format;
2124
                $now = time();
2125
                $delta = $now - $gmepoch;
2126
2127
                if (!isset($date_cache[$format]))
2128
                {
2129
                        // Is the user requesting a friendly date format (i.e. 'Today 12:42')?
2130
                        $date_cache[$format] = array(
2131
                                'is_short'                => strpos($format, '|'),
2132
                                'format_short'        => substr($format, 0, strpos($format, '|')) . '||' . substr(strrchr($format, '|'), 1),
2133
                                'format_long'        => str_replace('|', '', $format),
2134
                                'lang'                        => $this->lang['datetime'],
2135
                        );
2136
2137
                        // Short representation of month in format? Some languages use different terms for the long and short format of May
2138
                        if ((strpos($format, '\M') === false && strpos($format, 'M') !== false) || (strpos($format, '\r') === false && strpos($format, 'r') !== false))
2139
                        {
2140
                                $date_cache[$format]['lang']['May'] = $this->lang['datetime']['May_short'];
2141
                        }
2142
                }
2143
2144
                // Zone offset
2145
                $zone_offset = $this->timezone + $this->dst;
2146
2147
                // Show date < 1 hour ago as 'xx min ago' but not greater than 60 seconds in the future
2148
                // A small tolerence is given for times in the future but in the same minute are displayed as '< than a minute ago'
2149
                if ($delta < 3600 && $delta > -60 && ($delta >= -5 || (($now / 60) % 60) == (($gmepoch / 60) % 60)) && $date_cache[$format]['is_short'] !== false && !$forcedate && isset($this->lang['datetime']['AGO']))
2150
                {
2151
                        return $this->lang(array('datetime', 'AGO'), max(0, (int) floor($delta / 60)));
2152
                }
2153
2154
                if (!$midnight)
2155
                {
2156
                        list($d, $m, $y) = explode(' ', gmdate('j n Y', time() + $zone_offset));
2157
                        $midnight = gmmktime(0, 0, 0, $m, $d, $y) - $zone_offset;
2158
                }
2159
2160
                if ($date_cache[$format]['is_short'] !== false && !$forcedate && !($gmepoch < $midnight - 86400 || $gmepoch > $midnight + 172800))
2161
                {
2162
                        $day = false;
2163
2164
                        if ($gmepoch > $midnight + 86400)
2165
                        {
2166
                                $day = 'TOMORROW';
2167
                        }
2168
                        else if ($gmepoch > $midnight)
2169
                        {
2170
                                $day = 'TODAY';
2171
                        }
2172
                        else if ($gmepoch > $midnight - 86400)
2173
                        {
2174
                                $day = 'YESTERDAY';
2175
                        }
2176
2177
                        if ($day !== false)
2178
                        {
2179
                                return str_replace('||', $this->lang['datetime'][$day], strtr(@gmdate($date_cache[$format]['format_short'], $gmepoch + $zone_offset), $date_cache[$format]['lang']));
2180
                        }
2181
                }
2182
2183
                return strtr(@gmdate($date_cache[$format]['format_long'], $gmepoch + $zone_offset), $date_cache[$format]['lang']);
2184
        }
2185
2186
        /**
2187
        * Get language id currently used by the user
2188
        */
2189
        function get_iso_lang_id()
2190
        {
2191
                global $config, $db;
2192
2193
                if (!empty($this->lang_id))
2194
                {
2195
                        return $this->lang_id;
2196
                }
2197
2198
                if (!$this->lang_name)
2199
                {
2200
                        $this->lang_name = $config['default_lang'];
2201
                }
2202
2203
                $sql = 'SELECT lang_id
2204
                        FROM ' . LANG_TABLE . "
2205
                        WHERE lang_iso = '" . $db->sql_escape($this->lang_name) . "'";
2206
                $result = $db->sql_query($sql);
2207
                $this->lang_id = (int) $db->sql_fetchfield('lang_id');
2208
                $db->sql_freeresult($result);
2209
2210
                return $this->lang_id;
2211
        }
2212
2213
        /**
2214
        * Get users profile fields
2215
        */
2216
        function get_profile_fields($user_id)
2217
        {
2218
                global $db;
2219
2220
                if (isset($this->profile_fields))
2221
                {
2222
                        return;
2223
                }
2224
2225
                $sql = 'SELECT *
2226
                        FROM ' . PROFILE_FIELDS_DATA_TABLE . "
2227
                        WHERE user_id = $user_id";
2228
                $result = $db->sql_query_limit($sql, 1);
2229
                $this->profile_fields = (!($row = $db->sql_fetchrow($result))) ? array() : $row;
2230
                $db->sql_freeresult($result);
2231
        }
2232
2233
        /**
2234
        * Specify/Get image
2235
        */
2236
        function img($img, $alt = '')
2237
        {
2238
                $alt = (!empty($this->lang[$alt])) ? $this->lang[$alt] : $alt;
2239
                return '<span class="imageset ' . $img . '">' . $alt . '</span>';
2240
        }
2241
2242
        /**
2243
        * Get option bit field from user options.
2244
        *
2245
        * @param int $key option key, as defined in $keyoptions property.
2246
        * @param int $data bit field value to use, or false to use $this->data['user_options']
2247
        * @return bool true if the option is set in the bit field, false otherwise
2248
        */
2249
        function optionget($key, $data = false)
2250
        {
2251
                $var = ($data !== false) ? $data : $this->data['user_options'];
2252
                return phpbb_optionget($this->keyoptions[$key], $var);
2253
        }
2254
2255
        /**
2256
        * Set option bit field for user options.
2257
        *
2258
        * @param int $key Option key, as defined in $keyoptions property.
2259
        * @param bool $value True to set the option, false to clear the option.
2260
        * @param int $data Current bit field value, or false to use $this->data['user_options']
2261
        * @return int|bool If $data is false, the bit field is modified and
2262
        *                  written back to $this->data['user_options'], and
2263
        *                  return value is true if the bit field changed and
2264
        *                  false otherwise. If $data is not false, the new
2265
        *                  bitfield value is returned.
2266
        */
2267
        function optionset($key, $value, $data = false)
2268
        {
2269
                $var = ($data !== false) ? $data : $this->data['user_options'];
2270
2271
                $new_var = phpbb_optionset($this->keyoptions[$key], $value, $var);
2272
2273
                if ($data === false)
2274
                {
2275
                        if ($new_var != $var)
2276
                        {
2277
                                $this->data['user_options'] = $new_var;
2278
                                return true;
2279
                        }
2280
                        else
2281
                        {
2282
                                return false;
2283
                        }
2284
                }
2285
                else
2286
                {
2287
                        return $new_var;
2288
                }
2289
        }
2290
2291
        /**
2292
        * Funtion to make the user leave the NEWLY_REGISTERED system group.
2293
        * @access public
2294
        */
2295
        function leave_newly_registered()
2296
        {
2297
                global $db;
2298
2299
                if (empty($this->data['user_new']))
2300
                {
2301
                        return false;
2302
                }
2303
2304
                if (!function_exists('remove_newly_registered'))
2305
                {
2306
                        global $phpbb_root_path, $phpEx;
2307
2308
                        include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
2309
                }
2310
                if ($group = remove_newly_registered($this->data['user_id'], $this->data))
2311
                {
2312
                        $this->data['group_id'] = $group;
2313
2314
                }
2315
                $this->data['user_permissions'] = '';
2316
                $this->data['user_new'] = 0;
2317
2318
                return true;
2319
        }
2320
2321
        /**
2322
        * Returns all password protected forum ids the user is currently NOT authenticated for.
2323
        *
2324
        * @return array                Array of forum ids
2325
        * @access public
2326
        */
2327
        function get_passworded_forums()
2328
        {
2329
                global $db;
2330
2331
                $sql = 'SELECT f.forum_id, fa.user_id
2332
                        FROM ' . FORUMS_TABLE . ' f
2333
                        LEFT JOIN ' . FORUMS_ACCESS_TABLE . " fa
2334
                                ON (fa.forum_id = f.forum_id
2335
                                        AND fa.session_id = '" . $db->sql_escape($this->session_id) . "')
2336
                        WHERE f.forum_password <> ''";
2337
                $result = $db->sql_query($sql);
2338
2339
                $forum_ids = array();
2340
                while ($row = $db->sql_fetchrow($result))
2341
                {
2342
                        $forum_id = (int) $row['forum_id'];
2343
2344
                        if ($row['user_id'] != $this->data['user_id'])
2345
                        {
2346
                                $forum_ids[$forum_id] = $forum_id;
2347
                        }
2348
                }
2349
                $db->sql_freeresult($result);
2350
2351
                return $forum_ids;
2352
        }
2353
}