root/include/sessions.php

Revision 337, 45.0 kB (checked in by Nafania, 1 year ago)

Небольшой фикс для поиска сфинкса и фикс ошибки sql error Duplicate entry '***' for key 1 occured in sql query INSERT INTO sessions...

Line 
1 <?php
2 /***************************************************************************</span>
3 <span class="code-comment"> *                                sessions.php
4  *                            -------------------
5  *   begin                : Saturday, Feb 13, 2001
6  *   copyright            : (C) 2001 The phpBB Group
7  *   email                : support@phpbb.com
8  *
9  *   $Id: sessions.php,v 1.58.2.16 2005/10/30 15:17:14 acydburn Exp $
10  *
11  *
12  ***************************************************************************/
13
14 /***************************************************************************
15  *
16  *   This program is free software; you can redistribute it and/or modify
17  *   it under the terms of the GNU General Public License as published by
18  *   the Free Software Foundation; either version 2 of the License, or
19  *   (at your option) any later version.
20  *
21  ***************************************************************************/
22
23 //
24 // Adds/updates a new session to the database for the given userid.
25 // Returns the new session ID on success.
26 //
27 function session_begin($user_id, $user_ip, $auto_create = 0, $enable_autologin = 0, $admin = 0)</span>
28 <span class="code-keyword">{
29     global $db, $config;
30     global $SID;
31
32     $cookiename = $config['cookie_name'];
33     $cookiepath = $config['cookie_path'];
34     $cookiedomain = $config['cookie_domain'];
35     $cookiesecure = $config['cookie_secure'];
36
37     $current_page = extract_current_page();
38     $current_page = $current_page['page'];
39
40     if ( isset($_COOKIE[$cookiename . '_sid']) || isset($_COOKIE[$cookiename . '_u']))
41     {
42         $session_id = request_var($cookiename . '_sid', '', false, true);
43         $sessiondata['k'] = request_var($cookiename . '_k', '', false, true);
44         $sessiondata['u'] = request_var($cookiename . '_u', 0, false, true);
45         $sessionmethod = SESSION_METHOD_COOKIE;
46     }
47     else
48     {
49         $sessiondata = array();
50         $sessiondata['k'] = '';
51         $sessiondata['u'] = ANONYMOUS;
52         $session_id = request_var('sid', '');
53         $sessionmethod = SESSION_METHOD_GET;
54     }
55
56     //
57     if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
58     {
59         $session_id = '';
60     }
61
62     $last_visit = 0;
63     $current_time = time();
64     $cookie_expire = $current_time + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
65
66     //
67     // Are auto-logins allowed?
68     // If allow_autologin is not set or is true then they are
69     // (same behaviour as old 2.0.x session code)
70     //
71     if (isset($config['allow_autologin']) && !$config['allow_autologin'])
72     {
73         $enable_autologin = $sessiondata['k'] = false;
74     }
75
76     //
77     // First off attempt to join with the autologin value if we have one
78     // If not, just use the user_id value
79     //
80     $userdata = array();
81
82     if ( $user_id != ANONYMOUS )
83     {
84         if ( $sessiondata['k'] != '' && $user_id )
85         {
86             $sql = 'SELECT u.*
87                 FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
88                 WHERE u.uid = ' . $user_id . "
89                 AND u.enabled = 1
90                 AND k.user_id = u.uid
91                 AND k.key_id = '" . md5($sessiondata['k']) . "'";
92             $result = $db->sql_query($sql);
93
94             $userdata = $db->sql_fetchrow($result);
95             $db->sql_freeresult($result);
96
97             $enable_autologin = $login = 1;
98         }
99         else if (!$auto_create)
100         {
101             $sessiondata['k'] = '';
102             $sessiondata['u'] = $user_id;
103
104             $sql = 'SELECT *
105                 FROM ' . USERS_TABLE . '
106                 WHERE uid = ' . (int) $user_id . '
107                 AND enabled = 1';
108             $result = $db->sql_query($sql);
109
110             $userdata = $db->sql_fetchrow($result);
111             $db->sql_freeresult($result);
112
113             $login = 1;
114         }
115     }
116
117     //
118     // At this point either $userdata should be populated or
119     // one of the below is true
120     // * Key didn't match one in the DB
121     // * User does not exist
122     // * User is inactive
123     //
124     if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
125     {
126         $sessiondata['k'] = '';
127         $sessiondata['u'] = $user_id = ANONYMOUS;
128         $enable_autologin = $login = 0;
129
130         $sql = 'SELECT *
131             FROM ' . USERS_TABLE . '
132             WHERE uid = ' . (int) $user_id;
133         $result = $db->sql_query($sql);
134
135         $userdata = $db->sql_fetchrow($result);
136         $db->sql_freeresult($result);
137     }
138
139
140     //
141     // Initial ban check against user id, IP and email address
142     //
143     //preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);
144
145     $sql = "SELECT ban_ip, ban_email
146             FROM " . BANLIST_TABLE . "
147             WHERE ban_ip = '" . $user_ip . "'";
148     if ( $user_id != ANONYMOUS )
149     {
150         $email_part = substr($userdata['email'], strpos($userdata['email'], '@'));
151
152         $sql .= " OR ban_email LIKE '" . $db->sql_escape($userdata['email']) . "'
153             OR ban_email LIKE '" . $db->sql_escape($email_part) . "'";
154     }
155     $result = $db->sql_query($sql);
156
157     if ( $ban_info = $db->sql_fetchrow($result) )
158     {
159         if ( $ban_info['ban_ip'] && $user_id <> ANONYMOUS ) {
160             $sql = 'UPDATE ' . USERS_TABLE . ' SET enabled = 1 WHERE uid = ' . $user_id;
161             $db->sql_query($sql);
162         }
163         if ( $ban_info['ban_ip'] || $ban_info['ban_email'] ) {
164             if ( $session_id && $user_id <> ANONYMOUS ) {
165                 session_end($session_id, $user_id);
166             }
167             trigger_error('This account disabled', E_USER_ERROR);
168         }
169     }
170
171     //
172     // Create or update the session
173     //
174     /*$sql = "UPDATE " . SESSIONS_TABLE . "
175         SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = '" . $db->sql_escape($current_page) . "', session_logged_in = $login, session_admin = $admin
176         WHERE session_id = '" . $session_id . "'
177         AND session_ip = '$user_ip'";*/
178        $sql_ip = ( $user_id == ANONYMOUS ? " AND session_ip = '$user_ip'" : '' );
179        $sql = "UPDATE " . SESSIONS_TABLE . "
180               SET session_ip = '$user_ip', session_start = $current_time, session_time = $current_time, session_page = '" . $db->sql_escape($current_page) . "', session_logged_in = $login, session_admin = $admin
181               WHERE session_id = '" . $session_id . "' $sql_ip
182          AND session_user_id = '$user_id'";
183     if ( !$db->sql_query($sql) || !$db->sql_affectedrows() )
184     {
185         $session_id = md5(dss_rand());
186
187         $sql = "INSERT INTO " . SESSIONS_TABLE . "
188             (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
189             VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', '" . $db->sql_escape($current_page) . "', $login, $admin)";
190         $db->sql_query($sql);
191     }
192
193     if ( $user_id != ANONYMOUS )
194     {
195         $last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;
196
197         if (!$admin)
198         {
199             $sql = 'UPDATE ' . USERS_TABLE . '
200                 SET user_session_time = ' . $current_time . ', user_session_page = \'' . $db->sql_escape($current_page) . '\', user_lastvisit = ' . $last_visit . '
201                 WHERE uid = ' . $user_id;
202             $db->sql_query($sql);
203         }
204
205         $userdata['user_lastvisit'] = $last_visit;
206
207         //
208         // Regenerate the auto-login key
209         //
210         if ($enable_autologin)
211         {
212             $auto_login_key = dss_rand() . dss_rand();
213
214             if ( $sessiondata['k'] != '' )
215             {
216                 $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
217                     SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
218                     WHERE key_id = '" . md5($sessiondata['k']) . "'";
219             }
220             else
221             {
222                 $sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
223                     VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
224             }
225
226             $db->sql_query($sql);
227
228             $sessiondata['k'] = $auto_login_key;
229             unset($auto_login_key);
230         }
231         else
232         {
233             $sessiondata['k'] = '';
234         }
235         $sessiondata['u'] = $user_id;
236     }
237
238     $userdata['session_id'] = $session_id;
239     $userdata['session_ip'] = $user_ip;
240     $userdata['session_user_id'] = $user_id;
241     $userdata['session_logged_in'] = $login;
242     $userdata['session_page'] = $current_page;
243     $userdata['session_start'] = $current_time;
244     $userdata['session_time'] = $current_time;
245     $userdata['session_admin'] = $admin;
246     $userdata['session_key'] = $sessiondata['k'];
247
248     set_cookie('k', $sessiondata['k'], $cookie_expire);
249     set_cookie('u', $sessiondata['u'], $cookie_expire);
250     set_cookie('sid', $session_id, $cookie_expire);
251
252     //$SID = $session_id;
253     $SID = ( $user_id <> ANONYMOUS ? $session_id : '' );
254
255     return $userdata;
256 }
257
258 //</span>
259 <span class="code-comment">// Checks for a given user session, tidies session table and updates user
260 // sessions at each page refresh
261 //
262 function session_pagestart($user_ip, $force_update = false)</span>
263 <span class="code-keyword">{
264     global $db, $lang, $config;
265     global $SID;
266
267     $cookiename = $config['cookie_name'];
268     $cookiepath = $config['cookie_path'];
269     $cookiedomain = $config['cookie_domain'];
270     $cookiesecure = $config['cookie_secure'];
271
272     $current_page = extract_current_page();
273     $current_page = $current_page['page'];
274
275     $session_id = request_var('sid', '');
276
277     $current_time = time();
278     $cookie_expire = $current_time + (($config['max_autologin_time']) ? 86400 * (int) $config['max_autologin_time'] : 31536000);
279     unset($userdata);
280
281     if ( $session_id && empty($_COOKIE[$cookiename . '_sid']) ) {
282         $sessiondata = array();
283         $sessiondata['k'] = '';
284         $sessiondata['u'] = ANONYMOUS;
285         $sessionmethod = SESSION_METHOD_GET;
286     }
287     else {
288         $session_id = request_var($cookiename . '_sid', '', false, true);
289         $sessiondata['k'] = request_var($cookiename . '_k', '', false, true);
290         $sessiondata['u'] = request_var($cookiename . '_u', 0, false, true);
291         $sessionmethod = SESSION_METHOD_COOKIE;
292     }
293
294     //
295     if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
296     {
297         $session_id = '';
298     }
299
300     //
301     // Does a session exist?
302     //
303     if ( !empty($session_id) )
304     {
305         //
306         // session_id exists so go ahead and attempt to grab all
307         // data in preparation
308         //
309         $sql = 'SELECT u.*, s.*
310             FROM ' . SESSIONS_TABLE . ' s, ' . USERS_TABLE . ' u
311             WHERE s.session_id = \'' . $db->sql_escape($session_id) . '\'
312             AND u.uid = s.session_user_id';
313         $result = $db->sql_query($sql);
314
315         $userdata = $db->sql_fetchrow($result);
316
317         //
318         // Did the session exist in the DB?
319         //
320         if ( isset($userdata['uid']) )
321         {
322             //
323             // Do not check IP assuming equivalence, if IPv4 we'll check only first 24
324             // bits ... I've been told (by vHiker) this should alleviate problems with
325             // load balanced et al proxies while retaining some reliance on IP security.
326             //
327             $ip_check_s = substr($userdata['session_ip'], 0, 6);
328             $ip_check_u = substr($user_ip, 0, 6);
329
330             if ($ip_check_s == $ip_check_u)
331             {
332                 //$SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? $session_id : '';
333                 $SID = ( $userdata['uid'] <> ANONYMOUS ? (($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? $session_id : '') : '' );
334
335                 //
336                 // Only update session DB a 1 minute or so after last update
337                 //
338                 if ( $current_time - $userdata['session_time'] > 5 * 60 || ( $force_update && $current_time - $userdata['session_time'] > 1 * 60 ) )
339                 {
340                     // A little trick to reset session_admin on session re-usage
341                     $update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($config['session_length'] + 60 )) ? ', session_admin = 0' : '';
342                     //$update_forum_sql = ( defined('IN_PHPBB') || ( strpos($current_page, 'phpbb2.php') === true ) ? ', user_lastvisit = ' . $current_time : '' );
343
344                     $sql = 'UPDATE ' . SESSIONS_TABLE . '
345                         SET session_time = ' . $current_time . ', session_page = \'' . $db->sql_escape($current_page) . '\'' . $update_admin . '
346                         WHERE session_id = \'' . $userdata['session_id'] . '\'';
347                     $db->sql_query($sql);
348                     if ( $userdata['uid'] != ANONYMOUS )
349                     {
350                         $sql = 'UPDATE ' . USERS_TABLE . '
351                             SET user_session_time =  ' . $current_time . ', user_session_page = \'' . $db->sql_escape($current_page) . '\', ip = \'' . $user_ip . '\'
352                             WHERE uid = ' . $userdata['uid'];
353                         $db->sql_query($sql);
354                     }
355
356                     set_cookie('k', $sessiondata['k'], $cookie_expire);
357                     set_cookie('u', $sessiondata['u'], $cookie_expire);
358                     set_cookie('sid', $session_id, $cookie_expire);
359                 }
360
361                 // Add the session_key to the userdata array if it is set
362                 if ( isset($sessiondata['k']) && $sessiondata['k'] != '' )
363                 {
364                     $userdata['session_key'] = $sessiondata['k'];
365                 }
366
367                 return $userdata;
368             }
369         }
370     }
371
372     //
373     // If we reach here then no (valid) session exists. So we'll create a new one,
374     // using the cookie user_id if available to pull basic user prefs.
375     //
376     $user_id = ( isset($sessiondata['u']) ) ? (int) $sessiondata['u'] : ANONYMOUS;
377
378     if ( !$userdata = session_begin($user_id, $user_ip, true) )
379     {
380         trigger_error('Error creating user session');
381     }
382     return $userdata;
383
384 }
385
386 /**</span>
387 <span class="code-comment">* Terminates the specified session
388 * It will delete the entry in the sessions table for this session,
389 * remove the corresponding auto-login key and reset the cookies
390 */
391 function session_end($session_id, $user_id)</span>
392 <span class="code-keyword">{
393     global $db, $lang, $config, $userdata;
394     global $_COOKIE, $_GET, $SID;
395
396     $cookiename = $config['cookie_name'];
397     $cookiepath = $config['cookie_path'];
398     $cookiedomain = $config['cookie_domain'];
399     $cookiesecure = $config['cookie_secure'];
400
401     $autologinkey = request_var($cookiename . '_k', '', false, true);
402
403     $current_time = time();
404     $cookie_expire = $current_time - 31536000;
405
406     if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
407     {
408         return;
409     }
410
411     //
412     // Delete existing session
413     //
414     $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
415         WHERE session_id = \'' . $db->sql_escape($session_id) . '\'
416         AND session_user_id = ' . $user_id;
417     $db->sql_query($sql);
418
419     //
420     // Remove this auto-login entry (if applicable)
421     //
422     if ( $autologinkey != '' )
423     {
424         $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
425             WHERE user_id = ' . (int) $user_id . '
426             AND key_id = \'' . md5($autologinkey) . '\'';
427         $db->sql_query($sql);
428     }
429
430     //
431     // We expect that message_die will be called after this function,
432     // but just in case it isn't, reset $userdata to the details for a guest
433     //
434     $sql = 'SELECT *
435         FROM ' . USERS_TABLE . '
436         WHERE uid = ' . ANONYMOUS;
437     $result = $db->sql_query($sql);
438     $userdata = $db->sql_fetchrow($result);
439     $db->sql_freeresult($result);
440
441     set_cookie('sid', '', $cookie_expire);
442     set_cookie('u', '', $cookie_expire);
443     set_cookie('k', '', $cookie_expire);
444
445     return true;
446 }
447
448 /**</span>
449 <span class="code-comment">* Reset all login keys for the specified user
450 * Called on password changes
451 */
452 function session_reset_keys($user_id, $user_ip)</span>
453 <span class="code-keyword">{
454     global $db, $userdata, $config;
455
456     $key_sql = ($user_id == $userdata['uid'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';
457
458     $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
459         WHERE user_id = ' . (int) $user_id . "
460             $key_sql";
461
462     $db->sql_query($sql);
463
464     $where_sql = 'session_user_id = ' . (int) $user_id;
465     $where_sql .= ($user_id == $userdata['uid']) ? " AND session_id <> '" . $userdata['session_id'] . "'" : '';
466     $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
467         WHERE $where_sql";
468     $db->sql_query($sql);
469
470     if ( !empty($key_sql) )
471     {
472         $auto_login_key = dss_rand() . dss_rand();
473
474         $current_time = time();
475         $cookie_expire = $current_time + 31536000;
476
477         $sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
478             SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
479             WHERE key_id = '" . md5($userdata['session_key']) . "'";
480
481         $db->sql_query($sql);
482
483         // And now rebuild the cookie
484         $sessiondata['u'] = $user_id;
485         $sessiondata['k'] = $auto_login_key;
486         $cookiename = $config['cookie_name'];
487         $cookiepath = $config['cookie_path'];
488         $cookiedomain = $config['cookie_domain'];
489         $cookiesecure = $config['cookie_secure'];
490
491         set_cookie('k', $sessiondata['k'], $cookie_expire);
492         set_cookie('u', $sessiondata['u'], $cookie_expire);
493
494         $userdata['session_key'] = $auto_login_key;
495         unset($sessiondata);
496         unset($auto_login_key);
497     }
498 }
499
500 function set_cookie($name, $cookiedata, $cookietime = 0 )
501 {
502     global $config;
503
504     $name_data = rawurlencode($config['cookie_name'] . '_' . $name) . '=' . rawurlencode($cookiedata);
505     $expire = gmdate('D, d-M-Y H:i:s \\G\\M\\T', $cookietime);
506     $domain = (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain'];
507
508     //setcookie(rawurlencode($config['cookie_name'] . '_' . $name), rawurlencode($cookiedata), $cookietime, $config['cookie_path'], (!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : $config['cookie_domain']);
509     //setcookie($config['cookie_name'] . '_' . $name, $cookiedata, $cookietime, $config['cookie_path'], $config['cookie_domain'], $config['cookie_secure']);
510
511     header('Set-Cookie: ' . $name_data . (($cookietime) ? '; expires=' . $expire : '') . '; path=' . $config['cookie_path'] . $domain . ((!$config['cookie_secure']) ? '' : '; secure') . '; HttpOnly', false);
512 }
513
514 //</span>
515 <span class="code-comment">// Initialise user settings on page load
516 function init_userprefs(&$userdata)</span>
517 <span class="code-keyword">{
518     global $config, $theme, $images;
519     global $template, $lang, $lang_js, $phpEx, $root_path, $db, $seo;
520
521     if ( $userdata['uid'] != ANONYMOUS )
522     {
523         if ( !empty($userdata['language']))
524         {
525             $default_lang = $userdata['language'];
526         }
527     }
528
529     else
530     {
531         $default_lang = $config['default_lang'];
532         $userdata['tzoffset'] = number_format($config['board_timezone']);
533     }
534
535     if ( !@file_exists($root_path . 'languages/lang_' . $default_lang . '/lang_main.php') )
536     {
537         if ( $userdata['uid'] != ANONYMOUS )
538         {
539             // For logged in users, try the board default language next
540             $default_lang = $config['default_lang'];
541         }
542         else
543         {
544             // For guests it means the default language is not present, try english
545             // This is a long shot since it means serious errors in the setup to reach here,
546             // but english is part of a new install so it's worth us trying
547             $default_lang = 'english';
548         }
549
550         if ( !@file_exists($root_path . 'languages/lang_' . $default_lang . '/lang_main.php') )
551         {
552             trigger_error("Could not locate valid language pack");
553         }
554     }
555
556     // If we've had to change the value in any way then let's write it back to the database
557     // before we go any further since it means there is something wrong with it
558     if ( $userdata['uid'] != ANONYMOUS && $userdata['language'] !== $default_lang )
559     {
560         $sql = 'UPDATE ' . USERS_TABLE . " SET language = '" . $default_lang . "' WHERE language = '" . $db->sql_escape($userdata['language']) . "'";
561
562         $db->sql_query($sql);
563
564         $userdata['language'] = $default_lang;
565     }
566     elseif ( $userdata['uid'] === ANONYMOUS && $config['default_lang'] !== $default_lang )
567     {
568         set_config('default_lang', $default_lang);
569     }
570
571     include($root_path . 'languages/lang_' . $default_lang . '/lang_main.php');
572     include($root_path . 'languages/lang_' . $default_lang . '/lang_js.php');
573
574     if ( defined('IN_PHPBB') )
575     {
576         include($root_path . 'languages/lang_' . $default_lang . '/lang_forum.php');
577     }
578
579     if ( defined('IN_ADMIN') )
580     {
581         include($root_path . 'languages/lang_' . $default_lang . '/lang_admin.php');
582     }
583
584     //
585     // Set up style
586     //
587     if ( !$config['override_user_style'] )
588     {
589         if ( $userdata['uid'] != ANONYMOUS && $userdata['user_style'] > 0 )
590         {
591             if ( $theme = setup_style($userdata['user_style']) )
592             {
593                 return;
594             }
595         }
596     }
597
598     $theme = setup_style($config['default_style']);
599
600     return;
601 }
602
603 function setup_style($style) {
604     global $db, $config, $template, $root_path, $lang, $images, $template_path, $userdata, $lang_js;
605
606     require_once ($root_path . 'include/class.template.php');
607
608     $sql = 'SELECT * FROM ' . THEMES_TABLE . ' WHERE themes_id = ' . $style;
609      $result = $db->sql_query($sql, 31536000);
610      if ( !$row = $db->sql_fetchrow($result) ) {
611         $db->sql_freeresult($result);
612
613         if ( $style != $config['default_style'] ) {
614             $sql = 'SELECT * FROM ' . THEMES_TABLE . ' WHERE themes_id = ' . $config['default_style'];
615             $result = $db->sql_query($sql, 31536000);
616
617             if ( $row = $db->sql_fetchrow($result) ) {
618                 $db->sql_freeresult($result);
619                 $sql = 'UPDATE ' . USERS_TABLE . '
620                         SET user_style = ' . $config['default_style'] . '
621                         WHERE user_style = ' . $style;
622                 $db->sql_query($sql);
623              }
624             else {
625                 trigger_error("Could not get theme data for themes_id [$style]", E_USER_ERROR);
626              }
627         }
628         else {
629             trigger_error("Could not get theme data for themes_id [$style]", E_USER_ERROR);
630         }
631         return;
632     }
633     $db->sql_freeresult($result);
634      $template_name = $row['style_name'];
635
636      $template = new template;
637      $template_path = $root_path . 'templates/' . $row['template_name'];
638      $template->set_template($row['template_name']);
639
640     if ( $template ) {
641         $images = array();
642         $current_template_images = $root_path . 'templates/' . $row['template_name'];
643         @include($template_path . '/' . $row['template_name'] . '.cfg');
644
645         if ( !defined('TEMPLATE_CONFIG') ) {
646             trigger_error("Could not open $template_name template config file");
647         }
648
649         $img_lang = ( file_exists($template_path . '/images/lang_' . $userdata['language']) ) ? $userdata['language'] : $config['default_lang'];
650         foreach ( $images AS $key => $value ) {
651             if ( !is_array($value) ) {
652                 $value = str_replace('{LANG}', 'lang_' . $img_lang, $value);
653                 $images[$key] = $value;
654
655                 $template->assign_vars(array(
656                     'TEMPLATE_IMAGE_' . strtoupper($key) => $value
657                 ));
658              }
659         }
660         $userdata['template_path'] = $template_path;
661
662         $template->assign_vars(array(
663             'TEMPLATE_PATH' => $template_path
664         ));
665
666         foreach ( $lang_js AS $key => $value ) {
667             $template->assign_block_vars('javascript_lang', array(
668                 'KEY' => 'L_' . strtoupper($key),
669                 'VALUE' => str_replace("'", "\'", $value)
670             ));
671         }
672     }
673     else {
674         trigger_error("Could not initialize template [$style]");
675      }
676      return $row;
677 }
678
679 /**</span>
680 <span class="code-comment">* Our own generator of random values
681 * This uses a constantly changing value as the base for generating the values
682 * The board wide setting is updated once per page if this code is called
683 * With thanks to Anthrax101 for the inspiration on this one
684 * Added in phpBB 2.0.20
685 */
686 function dss_rand()</span>
687 <span class="code-keyword">{
688     global $config, $dss_seeded;
689
690     $val = uniqid(rand(),true) . $config['rand_seed'] . uniqid(rand(),true);
691     $val = md5($val);
692     $config['rand_seed'] = md5($config['rand_seed'] . $val . 'a');
693
694     if($dss_seeded !== true)
695     {
696         set_config('rand_seed', $config['rand_seed'], true);
697
698         $dss_seeded = true;
699     }
700
701     return substr($val, 4, 16);
702 }
703
704 /**</span>
705 <span class="code-comment">* Extract current session page
706 *
707 * @param string $root_path current root path ($root_path)
708 * copyright by phpBB
709 */
710
711 function extract_current_page()</span>
712 <span class="code-keyword">{
713     global $root_path;
714
715     $page_array = array();
716
717     // First of all, get the request uri...
718     $script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
719     $args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
720
721     // 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...
722     if (!$script_name)
723     {
724         $script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
725         $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
726         $page_array['failover'] = 1;
727     }
728
729     // Replace backslashes and doubled slashes (could happen on some proxy setups)
730     $script_name = str_replace(array('\\', '//'), '/', $script_name);
731
732     // Now, remove the sid and let us get a clean query string...
733     $use_args = array();
734
735     // Since some browser do not encode correctly we need to do this with some "special" characters...
736     // " -> %22, ' => %27, < -> %3C, > -> %3E
737     $find = array('"', "'", '<', '>');
738     $replace = array('%22', '%27', '%3C', '%3E');
739
740     foreach ($args as $key => $argument)
741     {
742         if (strpos($argument, 'sid=') === 0 || strpos($argument, '_f_=') === 0)
743         {
744             continue;
745         }
746
747         $use_args[str_replace($find, $replace, $key)] = str_replace($find, $replace, $argument);
748     }
749     unset($args);
750
751     // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
752
753     // The current query string
754     $query_string = trim(implode('&', $use_args));
755
756     // basenamed page name (for example: index.php)
757     $page_name = basename($script_name);
758     $page_name = urlencode(htmlspecialchars($page_name));
759
760     // current directory within the phpBB root (for example: adm)
761     $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
762     $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
763     $intersection = array_intersect_assoc($root_dirs, $page_dirs);
764
765     $root_dirs = array_diff_assoc($root_dirs, $intersection);
766     $page_dirs = array_diff_assoc($page_dirs, $intersection);
767
768     $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
769
770     if ($page_dir && substr($page_dir, -1, 1) == '/')
771     {
772         $page_dir = substr($page_dir, 0, -1);
773     }
774
775     // Current page from phpBB root (for example: adm/index.php?i=10&b=2)
776     $page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');
777     $page = ( strlen($page) > 255 ? substr($page, 0, 255) : $page );
778
779     // The script path from the webroot to the current directory (for example: /phpBB3/adm/) : always prefixed with / and ends in /
780     $script_path = trim(str_replace('\\', '/', dirname($script_name)));
781
782     // The script path from the webroot to the phpBB root (for example: /phpBB3/)
783     $script_dirs = explode('/', $script_path);
784     array_splice($script_dirs, -sizeof($page_dirs));
785     $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
786
787     // We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
788     if (!$root_script_path)
789     {
790         $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
791     }
792
793     $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
794     $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
795
796     $page_array += array(
797         'page_name'            => $page_name,
798         'page_dir'            => $page_dir,
799
800         'query_string'        => $query_string,
801         'script_path'        => str_replace(' ', '%20', htmlspecialchars($script_path)),
802         'root_script_path'    => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
803
804         'page'                => $page
805     );
806
807     return $page_array;
808 }
809
810 function _checkdnsrr($host, $type = '')
811 {
812     $type = (!$type) ? 'MX' : $type;
813
814     if (strpos(PHP_OS, 'WIN') !== false)
815     {
816         if (!function_exists('exec'))
817         {
818             return NULL;
819         }
820
821         @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
822
823         // If output is empty, the nslookup failed
824         if (empty($output))
825         {
826             return NULL;
827         }
828
829         foreach ($output as $line)
830         {
831             if (!trim($line))
832             {
833                 continue;
834             }
835
836             // Valid records begin with host name:
837             if (strpos($line, $host) === 0)
838             {
839                 return true;
840             }
841         }
842
843         return false;
844     }
845     else if (function_exists('checkdnsrr'))
846     {
847         return (checkdnsrr($host, $type)) ? true : false;
848     }
849
850     return NULL;
851 }
852
853 function check_dnsbl($mode, $ip = false)
854 {
855     global $user_ip;
856
857     if ($ip === false)
858     {
859         $ip = $user_ip;
860     }
861
862     $dnsbl_check = array(
863 //        'list.dsbl.org'            => 'http://dsbl.org/listing?',</span>
864 <span class="code-comment">        'sbl-xbl.spamhaus.org'        => 'http://www.spamhaus.org/query/bl?ip=',
865     );
866
867     if ($mode == 'register')
868     {
869         $dnsbl_check['bl.spamcop.net'] = 'http://spamcop.net/bl.shtml?';
870     }
871
872     if ($ip)
873     {
874         $quads = explode('.', $ip);
875         $reverse_ip = $quads[3] . '.' . $quads[2] . '.' . $quads[1] . '.' . $quads[0];
876
877         // Need to be listed on all servers...
878         $listed = true;
879         $info = array();
880
881         foreach ($dnsbl_check as $dnsbl => $lookup)
882         {
883             if (_checkdnsrr($reverse_ip . '.' . $dnsbl . '.', 'A') === true)
884             {
885                 $info = array($dnsbl, $lookup . $ip);
886             }
887             else
888             {
889                 $listed = false;
890             }
891         }
892
893         if ($listed)
894         {
895             return $info;
896         }
897     }
898
899     return false;
900 }
901
902
903 /**</span>
904 <span class="code-comment">* Append session id to url.
905 *
906 * @param string $url The url the session id needs to be appended to (can have params)
907 * @param mixed $params String or array of additional url parameters
908 * @param bool $is_amp Is url using &amp; (true) or & (false)
909 * @param string $session_id Possibility to use a custom session id instead of the global one
910 *
911 * Examples:
912 * <code>
913 * append_sid("{$root_path}viewtopic.$phpEx?t=1&amp;f=2");
914 * append_sid("{$root_path}viewtopic.$phpEx", 't=1&amp;f=2');
915 * append_sid("{$root_path}viewtopic.$phpEx", 't=1&f=2', false);
916 * append_sid("{$root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
917 * </code>
918 *
919 */
920 function append_sid($url, $params = false, $is_amp = true, $session_id = false)</span>
921 <span class="code-keyword">{
922     global $SID, $_EXTRA_URL;
923     // www.phpBB-SEO.com SEO TOOLKIT BEGIN
924     // We bypass the hook function here, the same effect as a standalone hook, which we want, but faster ;-)
925     global $seo;
926     if (!empty($seo->seo_opt['url_rewrite'])) {
927         return $seo->url_rewrite($url, $params, $is_amp, $session_id);
928     } else
929     // www.phpBB-SEO.com SEO TOOLKIT END
930
931     // Assign sid if session id is not specified
932     if ($session_id === false)
933     {
934         $session_id = $SID;
935     }
936
937     $amp_delim = ($is_amp) ? '&amp;' : '&';
938     $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
939
940     // Appending custom url parameter?
941     $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
942
943     $anchor = '';
944     if (strpos($url, '#') !== false)
945     {
946         list($url, $anchor) = explode('#', $url, 2);
947         $anchor = '#' . $anchor;
948     }
949     else if (!is_array($params) && strpos($params, '#') !== false)
950     {
951         list($params, $anchor) = explode('#', $params, 2);
952         $anchor = '#' . $anchor;
953     }
954     // Use the short variant if possible ;)
955     if ($params === false)
956     {
957         // Append session id
958         if (!$session_id)
959         {
960             return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
961         }
962         else
963         {
964             return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
965         }
966     }
967
968     // Build string if parameters are specified as array
969     if (is_array($params))
970     {
971         $output = array();
972
973         foreach ($params as $key => $item)
974         {
975             if ($item === NULL)
976             {
977                 continue;
978             }
979
980             if ($key == '#')
981             {
982                 $anchor = '#' . $item;
983                 continue;
984             }
985
986             $output[] = $key . '=' . $item;
987         }
988
989         $params = implode($amp_delim, $output);
990     }
991
992     // Append session id and parameters (even if they are empty)
993     // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
994     return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
995 }
996
997 /**</span>
998 <span class="code-comment">* Re-Apply session id after page reloads
999 */
1000 function reapply_sid($url)</span>
1001 <span class="code-keyword">{
1002     global $root_path;
1003
1004     if ($url === "index.php")
1005     {
1006         return append_sid("index.php");
1007     }
1008     else if ($url === "{$root_path}index.php")
1009     {
1010         return append_sid("{$root_path}index.php");
1011     }
1012
1013     // Remove previously added sid
1014     if (strpos($url, '?sid=') !== false)
1015     {
1016         $url = preg_replace('/(\?)sid=[a-z0-9]+(&amp;|&)?/', '\1', $url);
1017     }
1018     else if (strpos($url, '&sid=') !== false)
1019     {
1020         $url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
1021     }
1022     else if (strpos($url, '&amp;sid=') !== false)
1023     {
1024         $url = preg_replace('/&amp;sid=[a-z0-9]+(&amp;)?/', '\1', $url);
1025     }
1026
1027     return append_sid($url);
1028 }
1029
1030 /**</span>
1031 <span class="code-comment">* Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
1032 */
1033 function build_url($strip_vars = false)</span>
1034 <span class="code-keyword">{
1035     global $root_path;
1036
1037     // Append SID
1038     $current_page = extract_current_page();
1039     $redirect = append_sid($current_page['page'], false, false);
1040
1041     // Add delimiter if not there...
1042     if (strpos($redirect, '?') === false)
1043     {
1044         $redirect .= '?';
1045     }
1046
1047     // Strip vars...
1048     if ($strip_vars !== false && strpos($redirect, '?') !== false)
1049     {
1050         if (!is_array($strip_vars))
1051         {
1052             $strip_vars = array($strip_vars);
1053         }
1054
1055         $query = $_query = array();
1056
1057         $args = substr($redirect, strpos($redirect, '?') + 1);
1058         $args = ($args) ? explode('&', $args) : array();
1059         $redirect = substr($redirect, 0, strpos($redirect, '?'));
1060
1061         foreach ($args as $argument)
1062         {
1063             $arguments = explode('=', $argument);
1064             $key = $arguments[0];
1065             unset($arguments[0]);
1066
1067             $query[$key] = implode('=', $arguments);
1068         }
1069
1070         // Strip the vars off
1071         foreach ($strip_vars as $strip)
1072         {
1073             if (isset($query[$strip]))
1074             {
1075                 unset($query[$strip]);
1076             }
1077         }
1078
1079         // Glue the remaining parts together... already urlencoded
1080         foreach ($query as $key => $value)
1081         {
1082             $_query[] = $key . '=' . $value;
1083         }
1084         $query = implode('&', $_query);
1085
1086         $redirect .= ($query) ? '?' . $query : '';
1087     }
1088
1089     return $root_path . str_replace('&', '&amp;', $redirect);
1090 }
1091
1092 //</span>
1093 <span class="code-comment">// Create date/time from format and timezone
1094 //
1095 function create_date( $gmepoch, $format = '' )</span>
1096 <span class="code-keyword">{
1097     global $config, $lang, $userdata;
1098     static $midnight;
1099     static $date_cache;
1100
1101     $format = (!$format) ? $config['default_dateformat'] : $format;
1102     $now = time();
1103     $delta = $now - $gmepoch;
1104
1105     $zone_offset = $userdata['tzoffset'];
1106     // [start] DST
1107     if ( ($userdata['uid'] != ANONYMOUS && $userdata['user_dst']) || ( $userdata['uid'] == ANONYMOUS && $config['board_dst'] ) ) {
1108         $zone_offset += date('I', $gmepoch);
1109     }
1110     $zone_offset *= 3600;
1111     // [end] DST
1112
1113     if (!isset($date_cache[$format]))
1114     {
1115         // Is the user requesting a friendly date format (i.e. 'Today 12:42')?
1116         $date_cache[$format] = array(
1117             'is_short'        => strpos($format, '|'),
1118             'format_short'    => substr($format, 0, strpos($format, '|')) . '||' . substr(strrchr($format, '|'), 1),
1119             'format_long'    => str_replace('|', '', $format),
1120             'lang'            => $lang['datetime'],
1121         );
1122
1123         // Short representation of month in format? Some languages use different terms for the long and short format of May
1124         if ((strpos($format, '\M') === false && strpos($format, 'M') !== false) || (strpos($format, '\r') === false && strpos($format, 'r') !== false))
1125         {
1126             $date_cache[$format]['lang']['may'] = $lang['datetime']['May_short'];
1127         }
1128     }
1129
1130     // Show date <= 1 hour ago as 'xx min ago'
1131     // A small tolerence is given for times in the future but in the same minute are displayed as '< than a minute ago'
1132     if ($delta <= 3600 && ($delta >= -5 || (($now / 60) % 60) == (($gmepoch / 60) % 60)) && $date_cache[$format]['is_short'] !== false && isset($lang['datetime']['ago']))
1133     {
1134         $_null = max(0, (int) floor($delta / 60));
1135         $numbers = array_keys($lang['datetime']['ago']);
1136
1137         foreach ($numbers as $num)
1138         {
1139             if ($num > $_null)
1140             {
1141                 break;
1142             }
1143             $key_found = $num;
1144         }
1145         return sprintf($lang['datetime']['ago'][$key_found], $_null);
1146         //return $this->lang(array('datetime', 'AGO'), max(0, (int) floor($delta / 60)));
1147     }
1148
1149     if (!$midnight)
1150     {
1151         list($d, $m, $y) = explode(' ', gmdate('j n Y', time() + $zone_offset));
1152         $midnight = gmmktime(0, 0, 0, $m, $d, $y) - $zone_offset;
1153     }
1154
1155     if ($date_cache[$format]['is_short'] !== false && !($gmepoch < $midnight - 86400 || $gmepoch > $midnight + 172800))
1156     {
1157         $day = false;
1158
1159         if ($gmepoch > $midnight + 86400)
1160         {
1161             $day = 'tomorrow';
1162         }
1163         else if ($gmepoch > $midnight)
1164         {
1165             $day = 'today';
1166         }
1167         else if ($gmepoch > $midnight - 86400)
1168         {
1169             $day = 'yesterday';
1170         }
1171
1172         if ($day !== false)
1173         {
1174             return str_replace('||', $lang['datetime'][$day], strtr(@gmdate($date_cache[$format]['format_short'], $gmepoch + $zone_offset), $date_cache[$format]['lang']));
1175         }
1176     }
1177
1178     return strtr(@gmdate($date_cache[$format]['format_long'], $gmepoch + $zone_offset), $date_cache[$format]['lang']);
1179 }
1180
1181 function update_reputation ( $user_ary, $type, $state = 1, $points = 0 ) {
1182     global $db, $config, $cache;
1183     static $ranks;
1184
1185     if ( isset($user_ary['uid']) ) {
1186         $user_ary = array($user_ary);
1187     }
1188
1189     if ( !isset($ranks) ) {
1190         $ranks = $cache->obtain_ranks();
1191     }
1192
1193     if ( $type <> SIMPATY_CUSTOM ) {
1194         $points_settings = unserialize($config['points_settings']);
1195         $points = ( isset($points_settings[$type]) ? (int) $points_settings[$type] : 0 );
1196     }
1197
1198     if ( !sizeof($user_ary) ) {
1199         return;
1200     }
1201
1202     if ( !$state ) {
1203         $points = -$points;
1204     }
1205
1206     $field = $add_sql = '';
1207     switch( $type ) {
1208         case SIMPATY_TORRENT:
1209             $field = 'user_torrents_uploaded';
1210         break;
1211
1212         case SIMPATY_REQUEST:
1213             $field = 'user_requests_created';
1214         break;
1215
1216         case SIMPATY_OFFER:
1217             $field = 'user_offers_created';
1218         break;
1219
1220         case SIMPATY_FILL_REQUEST:
1221             $field = 'user_requests_filled';
1222         break;
1223
1224         case SIMPATY_FILL_OFFER:
1225             $field = 'user_offers_filled';
1226         break;
1227     }
1228
1229     if ( $field ) {
1230         $add_sql = ', ' . $field . ' = ' . $field . ( $state ? ' + ' : ' - ') . 1;
1231     }
1232
1233     if ( !$points && !$add_sql ) {
1234         return;
1235     }
1236
1237     foreach ( $user_ary AS $_null => $ary ) {
1238         if ( $ary['uid'] == ANONYMOUS ) {
1239             continue;
1240         }
1241         $user_reputation_level = $ary['user_reputation_level'];
1242         $user_rank_id = $ary['user_rank_id'];
1243
1244
1245         $rank_founded = false;
1246         reset($ranks);
1247         foreach ( $ranks AS $rank_id => $rank_ary ) {
1248             if ( ( $ary['user_reputation'] + $points ) >= $rank_ary['rank_points'] ) {
1249                 $user_rank_id = $rank_id;
1250                 $user_reputation_level = $rank_ary['rank_level'];
1251                 $rank_founded = true;
1252             }
1253         }
1254
1255         if ( !$rank_founded && ( $ary['user_reputation'] + $points ) < 0 ) {
1256             $min_rank = $ranks;
1257             $min_rank = array_shift($min_rank);
1258
1259             if ( $min_rank['rank_points'] < 0 ) {
1260                 $user_reputation_level = $min_rank['rank_level'];
1261                 $user_rank_id = $min_rank['rank_id'];
1262             }
1263             else {
1264                 $user_reputation_level = 0;
1265                 $user_rank_id = 0;
1266             }
1267
1268             $rank_founded = true;
1269         }
1270
1271         if ( $points || $add_sql ) {
1272             $sql = 'UPDATE ' . USERS_TABLE . ' SET user_reputation = user_reputation + ' . $points . ', user_reputation_level = ' . $user_reputation_level . ', user_rank_id = ' . $user_rank_id . $add_sql . ' WHERE uid = ' . $ary['uid'];
1273             $db->sql_query($sql);
1274         }
1275     }
1276     return;
1277 }
1278
1279 function check_ban ( $ban_type = BAN_GLOBAL ) {
1280     global $db, $userdata, $lang;
1281
1282     $uid = $userdata['uid'];
1283     $bans_ary = explode(':', $userdata['user_bans']);
1284
1285     if ( !empty($bans_ary[$ban_type]) ) {
1286         $sql = 'SELECT * FROM ' . BANLIST_TABLE . ' WHERE ban_userid = ' . $uid . ' AND ban_type = ' . $ban_type;
1287         $result = $db->sql_query($sql);
1288         if ( $row = $db->sql_fetchrow($result) ) {
1289             switch( $ban_type ){
1290                 case BAN_CHAT:
1291                     $msg = array('you_have_been_banned_in_chat', 'you_have_been_banned_in_chat_until');
1292                 break;
1293
1294                 case BAN_COMMENTS:
1295                     $msg = array('comments_for_you_disabled', 'comments_for_you_disabled_until');
1296                 break;
1297
1298                 case BAN_FORUM_POST:
1299                     $msg = array('forum_post_for_you_disabled', 'forum_post_for_you_disabled_until');
1300                 break;
1301             }
1302             $msg = ( !$row['ban_until'] ? $lang[$msg[0]] : sprintf($lang[$msg[1]], create_date($row['ban_until'], 'Y-m-d H:i:s')) . ' (' . sprintf($lang['warned_ago'], mkprettytime($row['ban_until'] - time())) . ')' );
1303             trigger_error($msg);
1304         }
1305         else {
1306             set_ban($ban_type, $uid, $userdata['user_bans']);
1307         }
1308     }
1309
1310     return;
1311 }
1312
1313 function set_ban ( $ban_type = BAN_GLOBAL, $ban_time, $remove = false, $uid = 0, &$current_ban_set = '' ) {
1314     global $db, $userdata, $lang;
1315
1316     if ( !$uid ) {
1317         $uid = $userdata['uid'];
1318         $current_ban_set = $userdata['user_bans'];
1319     }
1320
1321     $bans_ary = explode(':', $current_ban_set);
1322     $bans_ary[$ban_type] = ( $remove ? 0 : 1 );
1323     $current_ban_set = implode(':', $bans_ary);
1324
1325     $sql = 'UPDATE ' . USERS_TABLE . ' SET user_bans = \'' . $db->sql_escape($current_ban_set) . '\' WHERE uid = ' . $uid;
1326     $db->sql_query($sql);
1327
1328     if ( !$remove )
1329         $sql = 'INSERT INTO ' . BANLIST_TABLE . ' ' . $db->sql_build_array('INSERT', array(
1330                 'ban_userid' => $uid,
1331                 'ban_type' => $ban_type,
1332                 'ban_until' => ( $ban_time ? ( time() + $ban_time * 60 ) : 0 ),
1333                 'ban_added' => time(),
1334         ));
1335     else {
1336         $sql = 'DELETE FROM ' . BANLIST_TABLE . ' WHERE ban_userid = ' . $uid . ' AND ban_type = ' . $ban_type;
1337     }
1338     $db->sql_query($sql);
1339
1340     return;
1341 }
1342
1343 function get_user_avatar ( $uid, $avatar ) {
1344     global $config, $images, $root_path;
1345
1346     $avatar_prefix = ( ( strpos($avatar, 'user_avatar_' . $uid) === false && strpos($avatar, '/') !== false ) || !$avatar ? '' : $root_path . $config['avatar_path'] . '/' );
1347     $avatar = ( !$avatar ? $images['default_avatar'] : $avatar_prefix . $avatar );
1348
1349     return $avatar;
1350
1351 }
1352
1353 //</span>
1354 <span class="code-comment">// Handle user notification
1355 //
1356 function user_notification($notify_user, $notify_type, $info_data)</span>
1357 <span class="code-keyword">{
1358     global $config, $lang, $db, $root_path, $phpEx, $cache;
1359     global $userdata, $user_ip;
1360     // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1361     global $seo;
1362     // www.phpBB-SEO.com SEO TOOLKIT END
1363
1364     $current_time = time();
1365     $base_url = generate_base_url();
1366
1367     switch ( $notify_type ) {
1368         case TYPE_FORUM_POST:
1369
1370             $post_id = $info_data['post_id'];
1371             $topic_id = $info_data['topic_id'];
1372
1373             $for_id = $topic_id;
1374             $last_id = $post_id;
1375             $notifs_type = '[forum]';
1376
1377             if ( $info_data['mode'] <> 'reply' ) {
1378                 break;
1379             }
1380
1381             $email_template = 'topic_notify';
1382
1383             $title = censor_text(unprepare_message($info_data['topic_title']));
1384
1385             // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1386             if ( $seo->seo_opt['url_rewrite'] ) {
1387                 $seo->set_url(htmlspecialchars_decode($title), $topic_id, $seo->seo_static['topic']);
1388
1389                 $u_view_url = append_sid($root_path . "phpbb2.php?page=viewtopic&" . POST_POST_URL . "=$post_id#$post_id", false, false);
1390                 $u_view_url = $seo->drop_sid($u_view_url);
1391
1392                 $u_stop_watching = append_sid($root_path . "phpbb2.php?page=viewtopic&" . POST_TOPIC_URL . "=$topic_id&unwatch=topic", false, false);
1393                 $u_stop_watching = $seo->drop_sid($u_stop_watching);
1394             }
1395             // www.phpBB-SEO.com SEO TOOLKIT END
1396             else {
1397                 $u_view_url = $base_url . "/phpbb2.php?page=viewtopic&" . POST_POST_URL . "=$post_id#$post_id";
1398                 $u_stop_watching = $base_url . "/phpbb2.php?page=viewtopic&" . POST_TOPIC_URL . "=$topic_id&unwatch=topic";
1399             }
1400         break;
1401
1402         case TYPE_TORRENT:
1403         case TYPE_REQUEST:
1404         case TYPE_OFFER:
1405         case TYPE_NEWS:
1406
1407             $for_id = $info_data['for_id'];
1408             $last_id = $info_data['last_id'];
1409             $notifs_type = '[comments]';
1410
1411             $title = $info_data['name'];
1412
1413             $email_template = 'comments_notify';
1414
1415             // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1416             if ( $seo->seo_opt['url_rewrite'] ) {
1417                 $u_stop_watching = append_sid($root_path . "comment.php?type=$notify_type&action=checkoff&tid=$for_id", false, false);
1418                 $u_stop_watching = $seo->drop_sid($u_stop_watching);
1419
1420                 $u_view_url = append_sid($root_path . 'comment.php?cid=' . $last_id, false, false);
1421                 $u_view_url = $seo->drop_sid($u_view_url);
1422             }
1423             // www.phpBB-SEO.com SEO TOOLKIT END
1424             else {
1425                 $u_stop_watching = $base_url . "/comment.php?type=$notify_type&action=checkoff&tid=$for_id";
1426                 $u_view_url = $base_url . '/comment.php?cid=' . $last_id;
1427             }
1428
1429         break;
1430     }
1431
1432     if ( $notify_type <> TYPE_FORUM_POST || $info_data['mode'] == 'reply' ) {
1433
1434         $sql = "SELECT u.uid, u.email, u.language, u.notifs
1435                 FROM " . COMMENTS_NOTIFY_TABLE . " tw, " . USERS_TABLE . " u
1436                 WHERE tw.checkcomm_for_id = " . $for_id . "
1437                 AND tw.checkcomm_userid NOT IN (" . $userdata['uid'] . ", " . ANONYMOUS . ")
1438                 AND tw.checkcomm_notify_status = " . NOTIFY_STATUS_UN_NOTIFIED . "
1439                 AND u.uid = tw.checkcomm_userid
1440                 AND u.enabled = 1
1441                 AND tw.checkcomm_type = " . $notify_type;
1442         $result = $db->sql_query($sql);
1443
1444         $update_watched_sql = '';
1445         $bcc_list_ary = array();
1446
1447         if ( $row = $db->sql_fetchrow($result) ) {
1448             // Sixty second limit
1449             @set_time_limit(60);
1450
1451             do
1452             {
1453                 if ( strpos($row['notifs'], $notifs_type) !== false )
1454                 {
1455                     $bcc_list_ary[$row['language']][] = $row['email'];
1456                 }
1457                 $update_watched_sql .= ($update_watched_sql != '') ? ', ' . $row['uid'] : $row['uid'];
1458             }
1459             while ( $row = $db->sql_fetchrow($result) );
1460
1461             if ( sizeof($bcc_list_ary) )
1462             {
1463                 include_once($root_path . 'include/functions_messenger.php');
1464                 $messenger = new messenger(true);
1465
1466                 foreach ( $bcc_list_ary AS $user_lang => $bcc_list ) {
1467
1468                     foreach ( $bcc_list AS $_null => $email ) {
1469
1470                         $messenger->template($email_template, $user_lang);
1471
1472                         $messenger->to($email);
1473
1474                         $messenger->assign_vars(array(
1475                             'TITLE' => $title,
1476                             'U_VIEW_URL' => $u_view_url,
1477                             'U_STOP_WATCHING' => $u_stop_watching
1478                         ));
1479
1480                         $messenger->send(NOTIFY_EMAIL);
1481                     }
1482                 }
1483                 $messenger->save_queue();
1484             }
1485         }
1486         $db->sql_freeresult($result);
1487
1488         if ( $update_watched_sql )
1489         {
1490             $sql = 'UPDATE ' . COMMENTS_NOTIFY_TABLE . ' SET ' . $db->sql_build_array('UPDATE', array(
1491                 'checkcomm_notify_status' => NOTIFY_STATUS_NOTIFIED,
1492                 'checkcomm_last_comment_id' => $last_id,
1493                 'checkcomm_view_status' => VIEW_STATUS_NOT_VIEWED,
1494                 )) . '
1495                 WHERE checkcomm_for_id = ' . $for_id . '
1496                 AND checkcomm_type = ' . $notify_type . '
1497                 AND checkcomm_userid IN (' . $update_watched_sql . ')';
1498             $db->sql_query($sql);
1499         }
1500     }
1501
1502     if ( $notify_user ) {
1503         $sql = "SELECT checkcomm_for_id
1504             FROM " . COMMENTS_NOTIFY_TABLE . "
1505             WHERE checkcomm_for_id = $for_id
1506             AND checkcomm_type = " . $notify_type . "
1507             AND checkcomm_userid = " . $userdata['uid'];
1508         $result = $db->sql_query($sql);
1509
1510         if ( !$row = $db->sql_fetchrow($result) )
1511         {
1512             $sql = 'INSERT INTO ' . COMMENTS_NOTIFY_TABLE . ' ' . $db->sql_build_array('INSERT', array(
1513                 'checkcomm_userid' => $userdata['uid'],
1514                 'checkcomm_for_id' => $for_id,
1515                 'checkcomm_type' => $notify_type,
1516                 'checkcomm_notify_status' => NOTIFY_STATUS_UN_NOTIFIED,
1517                 'checkcomm_view_status' => VIEW_STATUS_VIEWED,
1518                 'checkcomm_last_comment_id' => $last_id,
1519             ));
1520             $db->sql_query($sql);
1521         }
1522     }
1523 }
1524
1525 ?>
Note: See TracBrowser for help on using the browser.