root/include/functions.php

Revision 335, 67.6 kB (checked in by Nafania, 1 year ago)

--

Line 
1 <?php
2
3 /**</span>
4 <span class="code-comment">* set_var
5 *
6 * Set variable, used by {@link request_var the request_var function}
7 *
8 * @access private
9 */
10 function set_var(&$result, $var, $type, $multibyte = false)</span>
11 <span class="code-keyword">{
12     settype($var, $type);
13     $result = $var;
14
15     if ($type == 'string')
16     {
17         $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result)));
18
19         if (!empty($result))
20         {
21             // Make sure multibyte characters are wellformed
22             if ($multibyte)
23             {
24                 if (!preg_match('/^./u', $result))
25                 {
26                     $result = '';
27                 }
28             }
29         }
30
31         $result = (STRIP) ? stripslashes($result) : $result;
32     }
33 }
34
35 /**</span>
36 <span class="code-comment">* request_var
37 *
38 * Used to get passed variable
39 */
40 function request_var($var_name, $default, $multibyte = false, $cookie = false)</span>
41 <span class="code-keyword">{
42     //
43     $_REQUEST = array_merge($_REQUEST, $_COOKIE);
44     //
45
46     if (!$cookie && isset($_COOKIE[$var_name]))
47     {
48         if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))
49         {
50             return (is_array($default)) ? array() : $default;
51         }
52         $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];
53     }
54
55     if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name])))
56     {
57         return (is_array($default)) ? array() : $default;
58     }
59
60     $var = $_REQUEST[$var_name];
61     if (!is_array($default))
62     {
63         $type = gettype($default);
64     }
65     else
66     {
67         list($key_type, $type) = each($default);
68         $type = gettype($type);
69         $key_type = gettype($key_type);
70         if ($type == 'array')
71         {
72             reset($default);
73             $default = current($default);
74             list($sub_key_type, $sub_type) = each($default);
75             $sub_type = gettype($sub_type);
76             $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
77             $sub_key_type = gettype($sub_key_type);
78         }
79     }
80
81     if (is_array($var))
82     {
83         $_var = $var;
84         $var = array();
85
86         foreach ($_var as $k => $v)
87         {
88             set_var($k, $k, $key_type);
89             if ($type == 'array' && is_array($v))
90             {
91                 foreach ($v as $_k => $_v)
92                 {
93                     if (is_array($_v))
94                     {
95                         $_v = null;
96                     }
97                     set_var($_k, $_k, $sub_key_type);
98                     set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
99                 }
100             }
101             else
102             {
103                 if ($type == 'array' || is_array($v))
104                 {
105                     $v = null;
106                 }
107                 set_var($var[$k], $v, $type, $multibyte);
108             }
109         }
110     }
111     else
112     {
113         set_var($var, $var, $type, $multibyte);
114     }
115
116     return $var;
117 }
118
119 function format_language ($lng) {
120     // You can add you ISO 639 country code here or remove unused codes
121     $iso639=array('albanian'=>'sq','arabic'=>'ar','azerbaijani'=>'az',
122         'bulgarian'=>'bg','chinese'=>'zh','chinese_simplified'=>'zh',
123         'chinese_traditional'=>'zh','croatian'=>'hr','czech'=>'cs',
124         'danish'=>'da','dutch'=>'nl','english'=>'en',
125         'esperanto'=>'eo','estonian'=>'et','finnish'=>'fi',
126         'french'=>'fr','japanese'=>'ja','galego'=>'gl',
127         'german'=>'de','greek'=>'el','hungarian'=>'hu',
128         'hebrew'=>'he','icelandic'=>'is','indonesian'=>'id',
129         'italian'=>'it','korean'=>'ko','kurdish'=>'ku',
130         'macedonian'=>'mk','moldavian'=>'mo','mongolian'=>'mn',
131         'norwegian'=>'no','polish'=>'pl','portuguese'=>'pt',
132         'romanian'=>'ro','russian'=>'ru','russian_tu'=>'ru',
133         'serbian'=>'sr','slovak'=>'sk','slovenian'=>'sl',
134         'spanish'=>'es','swedish'=>'sv','thai'=>'th',
135         'turkish'=>'tr','uigur'=>'ug','ukrainian'=>'uk',
136         'vietnamese'=>'vi','welsh'=>'cy');
137     $user_lang = ( isset($iso639[$lng]) ) ? $iso639[$lng] : '';
138     return $user_lang;
139 }
140
141 function get_row_count($table, $suffix = '', $ttl = 0) {
142         global $db;
143         if ($suffix) {
144                 $suffix = ' ' . $suffix;
145         }
146         $sql = 'SELECT COUNT(*) AS count FROM ' . $table . $suffix;
147         $result = $db->sql_query($sql, $ttl);
148         $count = ( $row = $db->sql_fetchrow($result) ) ? intval($row['count']) : 0;
149         $db->sql_freeresult($result);
150         return $count;
151 }
152
153 /**</span>
154 <span class="code-comment">* Return a nicely formatted backtrace (parts from the php manual by diz at ysagoon dot com)
155 */
156 function get_backtrace()</span>
157 <span class="code-keyword">{
158     global $root_path;
159
160     $output = '<div style="font-family: monospace;">';
161     $backtrace = debug_backtrace();
162     $path = realpath($root_path);
163
164     foreach ($backtrace as $number => $trace)
165     {
166         // We skip the first one, because it only shows this file/function
167         if ($number == 0)
168         {
169             continue;
170         }
171
172         // Strip the current directory from path
173         $trace['file'] = str_replace(array($path, '\\'), array('', '/'), $trace['file']);
174         $trace['file'] = ( substr($trace['file'], 0, 1) == '/' substr($trace['file'], 1) : $trace['file']);
175         $args = array();
176
177         // If include/require/include_once is not called, do not show arguments - they may contain sensible information
178         if (!in_array($trace['function'], array('include', 'require', 'include_once')))
179         {
180             unset($trace['args']);
181         }
182         else
183         {
184             // Path...
185             if (!empty($trace['args'][0]))
186             {
187                 $argument = htmlspecialchars($trace['args'][0]);
188                 $argument = str_replace(array($path, '\\'), array('', '/'), $argument);
189                 $argument = ( substr($argument, 0, 1) == '/' substr($argument, 1) : $argument);
190                 $args[] = "'{$argument}'";
191             }
192         }
193
194         $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
195         $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
196
197         $output .= '<br />';
198         $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
199         $output .= '<b>LINE:</b> ' . $trace['line'] . '<br />';
200
201         $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '(' . ((sizeof($args)) ? implode(', ', $args) : '') . ')<br />';
202     }
203     $output .= '</div>';
204     return $output;
205 }
206
207 function msg_handler($errno, $msg_text, $errfile, $errline)
208 {
209     global $db, $auth, $template, $config, $lang, $userdata;
210     global $root_path, $msg_title, $msg_long_text, $user_ip;
211
212     // Message handler is stripping text. In case we need it, we are possible to define long text...
213     if (isset($msg_long_text) && $msg_long_text && !$msg_text)
214     {
215         $msg_text = $msg_long_text;
216     }
217
218     switch ($errno)
219     {
220         case E_NOTICE:
221         case E_WARNING:
222
223             // Check the error reporting level and return if the error level does not match
224             // Additionally do not display notices if we suppress them via @
225             // If DEBUG is defined the default level is E_ALL
226             if (($errno & ((defined('DEBUG') && error_reporting()) ? ( defined('DEBUG_EXTRA') ? E_ALL : E_ALL & ~E_NOTICE ) : error_reporting())) == 0)
227             {
228                 return;
229             }
230
231             if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
232             {
233                 // remove complete path to installation, with the risk of changing backslashes meant to be there
234                 $errfile = str_replace(array(realpath($root_path), '\\'), array('', '/'), $errfile);
235                 $msg_text = str_replace(array(realpath($root_path), '\\'), array('', '/'), $msg_text);
236
237                 echo '<b>[TB Dev SZ Edition Debug] PHP Notice</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
238             }
239
240         break;
241
242         case E_USER_ERROR:
243             echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
244             echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
245             echo '<head>';
246             echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
247             echo '<title>' . $msg_title . '</title>';
248             echo '<link href="' . generate_base_url() . '/templates/admin/admin.css" rel="stylesheet" type="text/css" media="screen" />';
249             echo '</head>';
250             echo '<body id="errorpage">';
251             echo '<div id="wrap">';
252             echo '    <div id="page-header">';
253             echo '    </div>';
254             echo '    <div id="page-body">';
255             echo '        <div class="panel">';
256             echo '            <span class="corners-top"><span>&nbsp;</span></span>';
257             echo '            <div id="content">';
258             echo '                <h1>General Error</h1>';
259             echo '                <h2>' . $msg_text . '</h2>';
260             echo '                    <br /><br /><hr />';
261             if (!empty($config['sitemail']))
262             {
263                 echo '                <p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['sitemail'] . '">' . $config['sitemail'] . '</a></p>';
264             }
265             echo '            </div>';
266             echo '            <span class="corners-bottom"><span>&nbsp;</span></span>';
267             echo '        </div>';
268             echo '    </div>';
269             echo '</div>';
270             echo '<div id="page-footer">Powered by TB Dev SZ Edition &copy; ' . date('Y') . ' <a href="http://tbdevsz.ru/">TB Dev SZ Edition</a></div>';
271             echo '</body>';
272             echo '</html>';
273
274             gc();
275         break;
276
277         case E_USER_WARNING:
278         case E_USER_NOTICE:
279
280             define('IN_ERROR_HANDLER', true);
281
282             if ( empty($userdata) )
283             {
284                 $userdata = session_pagestart($user_ip);
285                 init_userprefs($userdata);
286             }
287
288             $msg_text = (!empty($lang[utf_strtolower($msg_text)])) ? $lang[utf_strtolower($msg_text)] : $msg_text;
289             $msg_title = (!isset($msg_title)) ? $lang['information'] : ((!empty($lang[$msg_title])) ? $lang[$msg_title] : $msg_title);
290
291             if (defined('IN_ADMIN') && isset($userdata['session_admin']) && $userdata['session_admin'])
292             {
293                 if (!defined('HEADER_INC')) {
294                     require ($root_path . 'admin/page_header_admin.php');
295                 }
296                 $body = '../admin/message_body.tpl';
297             }
298             else
299             {
300                 if ( defined('IN_PHPBB') ) {
301                     $body = 'forum/message_body.tpl';
302                     stdhead($msg_title, false);
303                 }
304                 else {
305                     $body = 'stderr.html';
306                     stdhead($msg_title);
307                 }
308             }
309
310             $template->assign_vars(array(
311                 'HEADING'        => $msg_title,
312                 'TEXT'                  => $msg_text,
313                 'MESSAGE_TITLE'         => $msg_title,
314                 'MESSAGE_TEXT'          => $msg_text,
315                 'S_USER_WARNING'    => ($errno == E_USER_WARNING) ? true : false,
316                 'S_USER_NOTICE'        => ($errno == E_USER_NOTICE) ? true : false)
317             );
318
319             $template->set_filenames(array(
320                 'body' => $body
321             ));
322
323             if (defined('IN_ADMIN') && isset($userdata['session_admin']) && $userdata['session_admin']) {
324                 $template->display('body');
325                 //include($root_path . 'admin/page_footer_admin.php');
326             }
327             else    {
328                 stdfoot();
329             }
330
331             exit;
332         break;
333     }
334 }
335
336 function get_user_class_name($class) {
337     global $lang;
338         switch ($class) {
339                 case UC_PEASANT: return $lang['peasant'];
340                 case UC_USER: return $lang['user'];
341                 case UC_POWER_USER: return $lang['power_user'];
342                 case UC_VIP: return $lang['vip'];
343                 case UC_UPLOADER: return $lang['uploader'];
344                 case UC_MODERATOR: return $lang['moderator'];
345                 case UC_ADMINISTRATOR: return $lang['administrator'];
346                 case UC_SYSOP: return $lang['sysop'];
347         }
348         return '';
349 }
350
351 function parse_username ( $data, $add_href = true, $link_options = array() ) {
352     global $lang, $images, $cache, $root_path, $seo;
353     static $ranks;
354
355     $username = ( !empty($data['username']) ? $data['username'] : $data['name'] );
356
357     if ( $data['uid'] == ANONYMOUS ) {
358         $username = '<i>' . $lang['unknown'] . '</i>';
359
360         $ret_string = $username;
361     }
362     else {
363         $seo->set_user_url($username, $data['uid']);
364
365         $pics = ( !empty($data['donor']) ? '<img src="' . $images['donor'] . '" alt="' . $lang['donor'] . '" />' : '' );
366         $pics .= ( !empty($data['parked']) ? '<img src="' . $images['parked'] . '" alt="' . $lang['parked'] . '" />' : '' );
367
368         if ( !empty($data['warneduntil']) ) {
369             $pics .= '<img src="' . $images['warned'] . '" alt="' . $lang['warned'] . '" />';
370         }
371         if ( isset($data['enabled']) && !$data['enabled'] ) {
372             $pics = '<img src="' . $images['disabled'] . '" alt="' . $lang['disabled'] . '" />';
373         }
374
375         if ( !empty($data['name_append']) ) {
376             $name_append = unserialize($data['name_append']);
377             foreach ( $name_append AS $type => $param ) {
378                 if ( $type == 'img' ) {
379                     foreach ( $param AS $img_alt => $img_path ) {
380                         $pics .= '<img src="' . $img_path . '" alt="' . $img_alt . '" title="' . $img_alt . '" />';
381                     }
382                 }
383             }
384         }
385
386         switch ( $data['class'] ) {
387             case UC_SYSOP:
388                 $style = 'color:#FF0000;';
389                 $title = $lang['sysop'];
390                 break;
391             case UC_ADMINISTRATOR:
392                 $style = 'color:#FFA500;';
393                 $title = $lang['administrator'];
394                 break;
395             case UC_MODERATOR:
396                 $style = 'color:#008000;';
397                 $title = $lang['moderator'];
398                 break;
399             case UC_UPLOADER:
400                 $style = 'color:#0000FF;';
401                 $title = $lang['uploader'];
402                 break;
403             case UC_VIP:
404                 $style = 'color:#FF00FF;';
405                 $title = $lang['vip'];
406                 break;
407             case UC_POWER_USER:
408                 $style = 'font-weight:bold;';
409                 $title = $lang['power_user'];
410                 break;
411             case UC_USER:
412                 $style = '';
413                 $title = $lang['user'];
414                 break;
415             case UC_PEASANT:
416                 $style = 'color:#808080;';
417                 $title = $lang['peasant'];
418                 break;
419         }
420
421         $rep_level = ( isset($data['user_reputation_level']) ? $data['user_reputation_level'] : false );
422
423         if ( $add_href ) {
424             $base_link_options = array(
425                 'style' => $style,
426                 'title' => $title,
427                 'href' => append_sid($root_path . 'userdetails.php?id=' . $data['uid']),
428                 'onclick' => '',
429             );
430
431             $link_params = '';
432
433             foreach ( $base_link_options AS $opt => $val ) {
434                 $param = '';
435                 if ( !empty($link_options[$opt]) ) {
436                     $param = $opt . '="' . $link_options[$opt] . '"';
437                 }
438                 elseif ( $val ) {
439                     $param = $opt . '="' . $val . '"';
440                 }
441
442                 $link_params .= ( $link_params ? ' ' : '' ) . $param;
443             }
444
445             $ret_string = '<a ' . $link_params . '>' . $username . '</a>';
446         }
447         else {
448             $ret_string = '<span' . ( $style ? ' style="' . $style . '"' : '' )  . ' title="' . $title . '">' . $username . '</span>';
449         }
450
451         $ret_string .= '&nbsp;' . $pics;
452
453         if ( $rep_level !== false && $data['uid'] <> ANONYMOUS ) {
454             if ( !isset($ranks) ) {
455                 $ranks = $cache->obtain_ranks();
456             }
457             $user_rank = ( isset($ranks[$data['user_rank_id']]['rank_name']) ? $ranks[$data['user_rank_id']]['rank_name'] : '' );
458
459             $ret_string .= '&nbsp;<span class="' . ( $rep_level < 0 ? 'badUserResp' : 'goodUserResp' ) . '" title="' . $user_rank . ', ' . $lang['reputation'] . ': ' . $data['user_reputation'] . '"><a href="javascript:;" onclick="window.open(\'' . append_sid($root_path . 'userdetails.php?id=' . $data['uid'] . '&amp;action=card') . '\', \'\', \'width=500,height=230,resizable=yes,scrollbars=yes,status=yes\')">' . $rep_level . '</a></span>';
460         }
461     }
462
463     return $ret_string;
464 }
465
466 function get_user_class_color($class, $username) {
467     global $lang;
468         switch ($class) {
469                 case UC_SYSOP:
470                         return '<span style="color:#FF0000;" title="' . $lang['sysop'] . '">' . $username . '</span>';
471                 break;
472                 case UC_ADMINISTRATOR:
473                         return '<span style="color:#FFA500;" title="' . $lang['administrator'] . '">' . $username . '</span>';
474                 break;
475                 case UC_MODERATOR:
476                         return '<span style="color:#008000;" title="' . $lang['moderator'] . '">' . $username . '</span>';
477                 break;
478                 case UC_UPLOADER:
479                         return '<span style="color:#0000FF;" title="' . $lang['uploader'] . '">' . $username . '</span>';
480                 break;
481                 case UC_VIP:
482                         return '<span style="color:#FF00FF;" title="' . $lang['vip'] . '">' . $username . '</span>';
483                 break;
484                 case UC_POWER_USER:
485                         return '<span style="font-weight: bold;" title="' . $lang['power_user'] . '">' . $username . '</span>';
486                 break;
487                 case UC_PEASANT:
488                         return '<span style="color:#808080;" title="' . $lang['peasant'] . '">' . $username . '</span>';
489                 break;
490         }
491         return $username;
492 }
493
494 function get_ratio($uploaded, $downloaded) {
495         if ($downloaded > 0) {
496                 $ratio = number_format($uploaded / $downloaded, 3);
497         }
498         elseif ($uploaded > 0) {
499                 $ratio = 'Inf.';
500         }
501         else {
502                 $ratio = '---';
503         }
504
505         return $ratio;
506 }
507
508 function get_ratio_color($ratio) {
509         if ($ratio == 'Inf.' || $ratio == '---') {
510             return '';
511         }
512         $n = 1;
513         $color = 16;
514         for ($i=0.1; $i<=$n; $i+=0.1) {
515              $color-=1;
516              $s = dechex($color);
517              if ($ratio < $i) {
518                 return '#' . $s . $s . '0000';
519              }
520
521         }
522         return '';
523 }
524
525 function set_config($config_name, $config_value, $is_dynamic = false)
526 {
527     global $db, $cache, $config;
528
529     $sql = 'UPDATE ' . CONFIG_TABLE . "
530         SET value = '" . $db->sql_escape($config_value) . "'
531         WHERE name = '" . $db->sql_escape($config_name) . "'";
532     $db->sql_query($sql);
533
534     if (!$db->sql_affectedrows() && !isset($config[$config_name]))
535     {
536         $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
537                'name'        => $config_name,
538                'value'        => $config_value,
539                'is_dynamic' => ($is_dynamic) ? 1 : 0));
540         $db->sql_query($sql);
541     }
542
543     $config[$config_name] = $config_value;
544
545     if (!$is_dynamic)
546     {
547         $cache->destroy('config');
548     }
549 }
550
551 function write_log($text, $level = LOG_VIEW_USER) {
552     global $db;
553
554     if ( strpos($text, 'sql error') !== false ) {
555         $db->sql_return_on_error(true);
556     }
557
558     $sql = 'INSERT INTO ' . SITELOG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
559                    'added'    => time(),
560                    'txt'    => trim($text),
561                    'log_view_level' => $level
562     ));
563
564     if ( !$db->sql_query($sql) ) {
565         trigger_error($text, E_USER_ERROR);
566     }
567     $db->sql_return_on_error(false);
568 }
569
570 function get_elapsed_time($ts) {
571         global $lang;
572         $mins = floor((time() - $ts) / 60);
573         $hours = floor($mins / 60);
574         $mins -= $hours * 60;
575         $days = floor($hours / 24);
576         $hours -= $days * 24;
577         $weeks = floor($days / 7);
578         $days -= $weeks * 7;
579         if ($weeks > 0) {
580                 return $weeks . ' '  . ($weeks > 1 ? $lang['weeks'] : $lang['week']) . ' ' . $lang['ago'];
581         }
582         if ($days > 0) {
583                 return $days . ' '  . ($days > 1 ? $lang['days'] : $lang['day']) . ' ' . $lang['ago'];
584         }
585         if ($hours > 0) {
586                 return $hours . ' '  . ($hours > 1 ? $lang['hours'] : $lang['hour']) . ' ' . $lang['ago'];
587         }
588         if ($mins > 0) {
589                 return $mins . ' '  . ($mins > 1 ? $lang['mins'] : $lang['min']) . ' ' . $lang['ago'];
590         }
591         return '< 1 ' . $lang['less_min'] . ' ' . $lang['ago'];
592 }
593
594 function mksize($bytes) {
595     global $lang;
596
597         if ($bytes < 1024 * 1024) {
598                 return number_format($bytes / 1024, 2) . ' ' . $lang['kilobytes'];
599         }
600         elseif ($bytes < 1024 * 1024 * 1024) {
601                 return number_format($bytes / ( 1024 * 1024 ), 2) . ' ' . $lang['megabytes'];
602         }
603         elseif ($bytes < 1024 * 1024 * 1024 * 1024) {
604                 return number_format($bytes / ( 1024 * 1024 * 1024 ), 2) . ' ' . $lang['gigabytes'];
605         }
606         else {
607                 return number_format($bytes / ( 1024 * 1024 * 1024 * 1024 ), 2) . ' ' . $lang['terabytes'];
608         }
609 }
610
611 function mkprettytime($s) {
612         global $lang;
613         if ($s < 0) {
614                 $s = 0;
615         }
616         $t = array();
617
618         foreach (array('60:sec','60:min','24:hour','0:day') as $x) {
619                 $y = explode(':', $x);
620                 if ($y[0] > 1) {
621                         $v = $s % $y[0];
622                         $s = floor($s / $y[0]);
623                 }
624                 else
625                         $v = $s;
626                 $t[$y[1]] = $v;
627         }
628         if ($t['day']) {
629                 return $t['day'] . $lang['days_short'] . ' ' . sprintf('%02d:%02d:%02d', $t['hour'], $t['min'], $t['sec']);
630         }
631         if ($t['hour']) {
632                 return sprintf('%d:%02d:%02d', $t['hour'], $t['min'], $t['sec']);
633         }
634         return sprintf('%d%s:%02d%s', $t['min'], $lang['minutes_short'], $t['sec'], $lang['secs_short']);
635 }
636
637 function mksecret($len = 20) {
638         $ret = '';
639         for ($i = 0; $i < $len; $i++) {
640                 $ret .= chr(mt_rand(65, 122));
641         }
642         return $ret;
643 }
644
645 function loggedinorreturn() {
646     global $userdata, $template;
647
648     $current_page = extract_current_page();
649     $current_page = $current_page['page'];
650
651     $template->assign_vars(array(
652         'RETURN_TO' => urlencode($current_page)
653     ));
654
655     if ( !$userdata['session_logged_in'] ) {
656         show_login_box();
657      }
658 }
659
660 function pager($rpp, $count, $href, $opts = array()) {
661     global $lang, $root_path;
662
663
664     $page = request_var('page', 0);
665
666     $pages = ceil($count / $rpp);
667
668     if ( !isset($opts['lastpagedefault']) ) {
669         $pagedefault = 0;
670     }
671     else {
672         $pagedefault = $opts['lastpagedefault'];
673           if ( $pagedefault < 0 ) {
674               $pagedefault = 0;
675         }
676     }
677
678     if ( $page ) {
679          if ( $page < 0 ) {
680               $page = $pagedefault;
681          }
682           elseif ( $page > $pages ) {
683               $page = ( $pages ? $pages : 0 );
684           }
685     }
686     else {
687         $page = $pagedefault;
688     }
689
690      $pager = '';
691      $mp = $pages;
692      $as = '<b>&lt;&lt;&nbsp;' . $lang['prev'] . '</b>';
693
694      if ( $page >= 2 ) {
695           $pager .= '<a href="' . append_sid($root_path . $href . 'page=' . ($page - 1)) . '">';
696           $pager .= $as;
697           $pager .= '</a>';
698      }
699      else {
700           $pager .= $as;
701      }
702      $pager .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
703      $as = '<b>' . $lang['next'] . '&nbsp;&gt;&gt;</b>';
704
705      $page = ( !$page ? 1 : $page );
706
707      if ( $page < $mp && $mp >= 0 ) {
708          $pager .= '<a href="' . append_sid($root_path . $href . 'page=' . ($page + 1)) . '">';
709           $pager .= $as;
710           $pager .= "</a>";
711      }
712      else {
713           $pager .= $as;
714      }
715
716      if ( $count > $rpp ) {
717         $pagerarr = array();
718         $dotted = 0;
719         $dotspace = 3;
720         $dotend = $pages - $dotspace;
721         $curdotend = $page - $dotspace;
722         $curdotstart = $page + $dotspace;
723
724         for ($i = 1; $i <= $pages; $i++) {
725             if (($i >= $dotspace && $i <= $curdotend) || ($i >= $curdotstart && $i < $dotend)) {
726                 if (!$dotted) {
727                     $pagerarr[] = '&hellip;';
728                 }
729                 $dotted = 1;
730                 continue;
731             }
732             $dotted = 0;
733             $start = ( $i - 1 ) * $rpp + 1;
734             $end = $start + $rpp - 1;
735             if ($end > $count) {
736                 $end = $count;
737             }
738             $text = $start . '&nbsp;-&nbsp;' . $end;
739             if ($i != $page) {
740                 $pagerarr[] = '<a href="' . append_sid($root_path . $href . 'page=' . $i) . '"><b>' . $text . '</b></a>';
741             }
742             else {
743                 $pagerarr[] = '<b>' . $text . '</b>';
744             }
745         }
746         $pagerstr = implode(' | ', $pagerarr);
747         $pagertop = '<p style="text-align: center;">' . $pager . '<br />' . $pagerstr . '</p>';
748         $pagerbottom = '<p style="text-align: center;">' . $pagerstr . '<br />' . $pager . '</p>';
749     }
750     else {
751         $pagertop = '';
752         $pagerbottom = $pagertop;
753     }
754
755     $start = ( $page - 1 ) * $rpp;
756
757     return array($pagertop, $pagerbottom, $start, $rpp);
758 }
759
760 function ratingpic( $numratings, $ratingsum, $return_pic = true ) {
761     global $root_path, $lang, $images, $config;
762
763     $rating = ($numratings ? round($ratingsum / $numratings, 1) : 0);
764     $rating = round($rating * 2) / 2;
765     $rating = str_replace(',', '.', $rating); //on some locales may be symbol ',' instead of '.'
766     if ( $numratings > $config['minvotes'] ) {
767         if ( $return_pic ) {
768             $title = $lang['rating'] . ': ' . $rating . ' / 5';
769             return '<span class="all-ratings" title="' . $title .'"><span style="width:' . ( $rating * $config['rating_pic_width'] ) . 'px">' .$title .'</span></span>';
770         }
771         else {
772             return $rating;
773         }
774     }
775     else {
776         if ( $return_pic ) {
777             return '<span class="all-ratings">&nbsp;</span>';
778         }
779         else {
780             return 0;
781         }
782     }
783 }
784
785 function get_user_icons($arr, $big = false) {
786         global $lang, $images;
787
788         if ( $big ) {
789                 $donorpic = $images['donor_big'];
790                 $warnedpic = $images['warned_big'];
791                 $disabledpic = $images['disabled_big'];
792                 $parked = $images['parked_big'];
793                 $style = 'style="margin-left: 4pt"';
794         }
795         else {
796                 $donorpic = $images['donor'];
797                 $warnedpic = $images['warned'];
798                 $disabledpic = $images['disabled'];
799                 $parked = $images['parked'];
800                 $style = 'style="margin-left: 2pt"';
801         }
802         $pics = ( $arr['donor'] ? '<img src="' . $donorpic . '" alt="' . $lang['donor'] . '" ' . $style . ' />' : '' );
803         $pics .= ( $arr['parked'] ? '<img src="' . $parked . '" alt="' . $lang['parked'] . '" ' . $style . ' />' : '' );
804
805         if ( $arr['enabled'] ) {
806                 $pics .= ( $arr['warneduntil'] ? '<img src="' . $warnedpic . '" alt="' . $lang['warned'] . '" ' . $style . ' />' : '' );
807         }
808         else {
809                 $pics .= '<img src="' . $disabledpic . '" alt="' . $lang['disabled'] . '" ' . $style . ' />';
810         }
811         return $pics;
812 }
813
814 function get_free_icon ( $free ) {
815     global $images;
816
817     switch ( $free ) {
818         //1 = 100% free
819         case 1:
820             return $images['free_download_gold'];
821         break;
822         //2 = 50% free
823         case 2:
824             return $images['free_download_silver'];
825         break;
826         //4 = 25% free
827         case 4:
828             return $images['free_download_bronze'];
829         break;
830         default:
831             return '';
832         break;
833     }
834 }
835
836 function parked() {
837         global $userdata, $lang;
838
839         if ($userdata['parked']) {
840                 trigger_error($lang['account_parked']);
841         }
842 }
843
844 function warn_panel($warn) {
845         global $images, $config;
846
847         $img = '<img src="' . $images['warned_good'] . '" alt="" />';
848         for ($i = 1; $i < $config['max_warn_for_user'] + 1; $i++) {
849             $img .= '<img src="' . ( $warn >= $i? $images["warned_$i"] : $images['warned_empty'] ) .  '" alt="" />';
850         }
851         $img .= '<img src="' . $images['warned_full'] . '" alt="" />';
852         return $img;
853
854 }
855
856 function get_age($birthday) {
857     global $userdata;
858
859         list($year, $month, $day) = explode('-', $birthday);
860         $current = gmdate('Y-m-d', time() + $userdata['tzoffset'] * 60);
861         list($year2, $month2, $day2) = explode('-', $current);
862         if($month2 < $month) {
863                 $age = $year2 - $year - 1;
864         }
865         if($month2 == $month) {
866                 if($day2 < $day) {
867                         $age = $year2 - $year - 1;
868                 }
869                 else {
870                         $age = $year2 - $year;
871                 }
872         }
873         if($month2 > $month) {
874                 $age = $year2 - $year;
875         }
876         return $age;
877 }
878
879 function censor_text($text)
880 {
881     static $censors;
882     global $cache;
883
884     if (!isset($censors) || !is_array($censors))
885     {
886         // obtain_word_list is taking care of the users censor option and the board-wide option
887         $censors = $cache->obtain_word_list();
888     }
889
890     if ( sizeof($censors) )
891     {
892         return preg_replace( $censors['match'], $censors['replace'], $text);
893     }
894
895     return $text;
896 }
897
898 function getagent($httpagent, $peer_id) {
899
900     $peer_ids = array(
901         'BC0([0-9])([0-9])([0-9])' => 'BitComet/',
902         'FG[0-9]+([0-9]+)([0-9]+)([0-9]+)' => 'FlashGet/',
903         'exbc\08' => 'BitComet/0.56',
904         'exbc\09' => 'BitComet/0.57',
905         'exbc\0:' => 'BitComet/0.58',
906         'exbc\0L' => 'BitLord/1.0',
907         'exbcL' => 'BitLord/1.1',
908         'UDP0' => 'BitSpirit v.3',
909         'ML([0-9]+).([0-9]+).([0-9]+)' => 'MLDonkey/',
910         'UT([0-9]+)([0-9]+)([0-9]+)([0-9A-Z]+)' => '&mu;Torrent/',
911         'CT([0-9]+)([0-9]+)([0-9]+)([0-9]+)' => 'cTorrent/',
912         'CD[0-9]+([0-9]+)[0-9]+([0-9]+)' => 'Enhanced CTorrent/',
913         'KT([0-9])([0-9])([0-9A-Z])([0-9A-Z])' => 'KTorrent/',
914         'btpd\/([0-9]+\.[0-9]{2})' => 'btpd/\\1',
915         'M([0-9])-([0-9])-([0-9])' => 'BitTorrent/',
916         '-G3' => 'G3 Torrent',
917         'AZ([0-2])([0-5])([0-9])([0-9])' => 'Azureus/',
918         'AZ([3-9])([0-9])([0-9])([0-9])' => 'Vuze/',
919         'LP[0-9]([0-9])([0-9])([0-9])' => 'Lphant/',
920         'DE([0-9])([0-9])([0-9])([0-9])' => 'Deluge/',
921         'XX([0-9])([0-9])([0-9])([0-9])' => 'Xtorrent/',
922         'TR([0-9])([0-9])([0-9])([0-9])' => 'Transmission/',
923         'LT([0-9])([0-9A-Z])([0-9])([0-9])' => 'libtorrent/',
924         'UM([0-9]+)([0-9]+)([0-9]+)([0-9A-Z]+)' => 'Mac &mu;Torrent/',
925     );
926
927     foreach ( $peer_ids as $pattern => $recog ) {
928         if ( preg_match('/' . $pattern . '/si', $peer_id, $matches) ) {
929             unset($matches[0]);
930             return $recog . implode('.', $matches);
931         }
932     }
933
934     $httpagents = array(
935         'Bitcomet Turbo ([0-9]+\.[0-9]+\.[0-9]+\.[0-9])' => 'Bitcomet Turbo/',
936         'BitTorrent\/S-([0-9]+\.[0-9]+\.[0-9]+)' => 'Shadow\'s/',
937         'BitTorrent\/([0-9]+\.[0-9]+\.[0-9]+)' => 'Bittorrent/',
938         'BitTorrent\/U-([0-9]+\.[0-9]+\.[0-9]+)' => 'UPnP/',
939         'BitTor(rent|nado)\/T-(.+)' => 'BitTornado/',
940         'ABC-([0-9]+\.[0-9]+\.[0-9])' => 'ABC/',
941         'Fast Torrent ([0-9]+\.[0-9]+\.[0-9]+\.[0-9])' => 'Fast Torrent/',
942         'rtorrent\/([0-9]+\.[0-9]+\.[0-9])' => 'rtorrent/',
943         'Python-urllib\/.+?, BitTorrent\/([0-9]+\.[0-9]+\.[0-9]+)' => 'BitTorrent/',
944         'DansClient' => 'XanTorrent',
945         'BitTorrent\/brst.' => 'Burst/',
946         'Shareaza ([0-9]+\.[0-9]+\.[0-9]+\.[0-9])' => 'Shareaza/',
947         'Rufus\/([0-9]+\.[0-9]+\.[0-9]+)' => 'Rufus/',
948         'eXeem ([0-9]+\.[0-9]{2})' => 'eXeem/',
949         'BinTorrent ([0-9]+\.[0-9]+)' => 'BinTorrent/',
950         'ML(Donkey)\/([0-9]+)\.([0-9]+)(\.([0-9]+)|)' => 'MLDonkey/',
951         'ed2k_plugin v([0-9]+\.[0-9]+)' => 'eDonkey/',
952         '0P3R4H' => 'Opera BT Client',
953         'Opera\/([0-9]+)\.([0-9]+)' => 'Opera/',
954         'qBittorrent v([0-9]+)\.([0-9]+)\.([0-9]+)' => 'qBittorrent/',
955         'Ares ([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)' => 'Ares/',
956         'LimeWire\/([0-9]+)\.([0-9]+)\.([0-9]+)' => 'LimeWire/',
957         'supertorrent' => 'SuperTorrent',
958         'Halite v ([0-9]+)\.([0-9]+)\.([0-9]+)' => 'Halite/\\1.\\2.\\3',
959     );
960
961     foreach ( $httpagents as $pattern => $recog ) {
962         if ( preg_match('/' . $pattern . '/si', $httpagent, $matches) ) {
963             unset($matches[0]);
964             return $recog . implode('.', $matches);
965         }
966     }
967     return '---';
968 }
969
970 function meta_refresh($time, $url)
971 {
972     global $template;
973
974     $template->assign_vars(array(
975         'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />')
976     );
977 }
978
979 function split_string ($string, $length, $hellip = true) {
980     if ( utf_strlen($string) <= $length ) {
981         return $string;
982     }
983     else {
984         $line = '';
985         $length = $length - 3;
986         $words = preg_split("/[\s]+/u", $string, 0PREG_SPLIT_DELIM_CAPTURE);
987         for($i = 0; $i < sizeof($words); $i++) {
988             if ( utf_strlen($line . $words[$i] . ' ') < $length){
989                 $line .= $words[$i] . ' ';
990             }
991         }
992         return substr($line, 0, -1) . (  $hellip ? '&hellip;' : '...' );
993     }
994 }
995
996 /**</span>
997 <span class="code-comment">* Generate board url (example: http://www.example.com/phpBB)
998 * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
999 */
1000 function generate_base_url($without_script_path = false)</span>
1001 <span class="code-keyword">{
1002     global $config;
1003
1004     $server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
1005     $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
1006
1007     // Forcing server vars is the only way to specify/override the protocol
1008     if ($config['force_server_vars'] || !$server_name)
1009     {
1010         $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
1011         $server_name = $config['server_name'];
1012         $server_port = (int) $config['server_port'];
1013         $script_path = $config['script_path'];
1014
1015         $url = $server_protocol . $server_name;
1016     }
1017     else
1018     {
1019         // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
1020         $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
1021         $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
1022
1023         $script_path = extract_current_page();
1024         $script_path = $script_path['root_script_path'];
1025     }
1026
1027     if ($server_port && (($config['cookie_secure'] && $server_port <> 443) || (!$config['cookie_secure'] && $server_port <> 80)))
1028     {
1029         $url .= ':' . $server_port;
1030     }
1031
1032     if (!$without_script_path)
1033     {
1034         $url .= $script_path;
1035     }
1036
1037     // Strip / from the end
1038     if (substr($url, -1, 1) == '/')
1039     {
1040         $url = substr($url, 0, -1);
1041     }
1042
1043     return $url;
1044 }
1045 //</span>
1046 <span class="code-comment">// This function is for compatibility with PHP 4.x's realpath()
1047 // function.  In later versions of PHP, it needs to be called
1048 // to do checks with some functions.  Older versions of PHP don't
1049 // seem to need this, so we'll just return the original value.
1050 // dougk_ff7 <October 5, 2002>
1051 function phpbb_realpath($path) {</span>
1052 <span class="code-keyword">        global $root_path;
1053
1054         return (!@function_exists('realpath') || !@realpath($root_path . 'include/functions.php.')) ? $path : @realpath($path);
1055 }
1056
1057 /**</span>
1058 <span class="code-comment">* Redirects the user to another page then exits the script nicely
1059 */
1060 function redirect($url, $return = false)</span>
1061 <span class="code-keyword">{
1062     global $db, $cache, $config, $root_path, $lang;
1063
1064     /*if (!$return)
1065     {
1066         if (!empty($cache)) {
1067             $cache->unload();
1068         }
1069         if (!empty($db)) {
1070             $db->sql_close();
1071          }
1072     }*/
1073     $current_page = extract_current_page();
1074
1075     // Make sure no &amp;'s are in, this will break the redirect
1076     $url = str_replace('&amp;', '&', $url);
1077
1078     // Determine which type of redirect we need to handle...
1079     $url_parts = parse_url($url);
1080
1081     if ($url_parts === false)
1082     {
1083         // Malformed url, redirect to current page...
1084         $url = generate_base_url() . '/' . $current_page['page'];
1085     }
1086     else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
1087     {
1088         // Full URL
1089     }
1090     else if ($url[0] == '/')
1091     {
1092         // Absolute uri, prepend direct url...
1093         $url = generate_base_url(true) . $url;
1094     }
1095     else
1096     {
1097         // Relative uri
1098         $pathinfo = pathinfo($url);
1099
1100         // Is the uri pointing to the current directory?
1101         if ($pathinfo['dirname'] == '.')
1102         {
1103             $url = str_replace('./', '', $url);
1104
1105             // Strip / from the beginning
1106             if ($url && substr($url, 0, 1) == '/')
1107             {
1108                 $url = substr($url, 1);
1109             }
1110
1111             if ($current_page['page_dir'])
1112             {
1113                 $url = generate_base_url() . '/' . $current_page['page_dir'] . '/' . $url;
1114             }
1115             else
1116             {
1117                 $url = generate_base_url() . '/' . $url;
1118             }
1119         }
1120         else
1121         {
1122             // Used ./ before, but $root_path is working better with urls within another root path
1123             $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
1124             $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
1125             $intersection = array_intersect_assoc($root_dirs, $page_dirs);
1126
1127             $root_dirs = array_diff_assoc($root_dirs, $intersection);
1128             $page_dirs = array_diff_assoc($page_dirs, $intersection);
1129
1130             $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
1131             // Strip / from the end
1132             if ($dir && substr($dir, -1, 1) == '/')
1133             {
1134                 $dir = substr($dir, 0, -1);
1135             }
1136
1137             // Strip / from the beginning
1138             if ($dir && substr($dir, 0, 1) == '/')
1139             {
1140                 $dir = substr($dir, 1);
1141             }
1142
1143             $url = str_replace($pathinfo['dirname'] . '/', '', $url);
1144
1145             // Strip / from the beginning
1146             if (substr($url, 0, 1) == '/')
1147             {
1148                 $url = substr($url, 1);
1149             }
1150             $url = $dir . '/' . $url;
1151             $url = generate_base_url() . '/' . $url;
1152         }
1153
1154     }
1155
1156     // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
1157     if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
1158     {
1159         trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
1160     }
1161
1162     // Now, also check the protocol and for a valid url the last time...
1163     $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
1164     $url_parts = parse_url($url);
1165
1166     if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
1167     {
1168         trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
1169     }
1170
1171     if ($return)
1172     {
1173         return $url;
1174     }
1175
1176     // Redirect via an HTML form for PITA webservers
1177     if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
1178     {
1179         header('Refresh: 0; URL=' . $url);
1180
1181         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
1182         echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $lang['content_direction'] . '">';
1183         echo '<head>';
1184         echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
1185         echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
1186         echo '<title>' . $lang['redirect'] . '</title>';
1187         echo '</head>';
1188         echo '<body>';
1189         echo '<div style="text-align: center;">' . sprintf($lang['url_redirect'], '<a href="' . str_replace('&', '&amp;', $url) . '">', '</a>') . '</div>';
1190         echo '</body>';
1191         echo '</html>';
1192
1193         gc();
1194     }
1195
1196     // Behave as per HTTP/1.1 spec for others
1197     header('Location: ' . $url);
1198     gc();
1199 }
1200
1201 function show_login_box ( $redirect = false, $admin = false ) {
1202     global $lang, $template, $root_path, $userdata;
1203
1204     stdhead($lang['login']);
1205     $template->assign_vars(array(
1206         'S_LOGIN_ACTION' => append_sid($root_path . 'login.php'),
1207         'REDIRECT' => $redirect,
1208         'ADMIN' => ( $userdata['class'] >= UC_ADMINISTRATOR ? $admin : 0 ),
1209         'LOST_PASS_RECOVER' => sprintf($lang['lost_pass_recover'], append_sid($root_path . 'signup.php?type=recover')),
1210         'NO_ACC_REGISTER' => sprintf($lang['no_account_register'], append_sid($root_path . 'signup.php'))
1211     ));
1212     $template->set_filenames(array(
1213         'body' => 'login.html')
1214     );
1215     stdfoot();
1216 }
1217
1218 function highlight_text ( $highlight, $text ) {
1219
1220     $highlight_match = '';
1221
1222     foreach (explode(' ', trim($highlight)) as $word)
1223     {
1224         if (trim($word))
1225         {
1226             $word = str_replace('\*', '\w+?', preg_quote($word, '#'));
1227             $word = preg_replace('#(^|\s)\\\\w\*\?(\s|$)#', '$1\w+?$2', $word);
1228             $highlight_match .= (($highlight_match != '') ? '|' : '') . $word;
1229         }
1230     }
1231     $text = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#isu', '<span style="background-color:yellow">\1</span>', $text);
1232
1233     return $text;
1234 }
1235
1236 function undo_htmlspecialchars ( $text ) {
1237     $search = array('&lt;', '&gt;', '&quot;', '&amp;');
1238     $replace = array('<', '>', '"', '&');
1239
1240     return str_replace($search, $replace, $text);
1241 }
1242
1243 function send_pm ( $pm_ary, $force_send = false ) {
1244     global $config, $db, $root_path, $lang, $seo;
1245
1246     if ( !sizeof($pm_ary) ) {
1247         return;
1248     }
1249
1250     require_once($root_path . 'include/functions_messenger.php');
1251     $messenger = new messenger(true);
1252
1253     $current_time = time();
1254     $receiver_ary = array();
1255     $count_ary = array();
1256     $base_url = generate_base_url();
1257
1258     foreach ( $pm_ary AS $_null => $ary ) {
1259         $sql = 'INSERT INTO ' . PRIVATE_MESSAGES_TABLE . ' ' . $db->sql_build_array('INSERT', array(
1260                  'sender'   => $ary['sender'],
1261                  'receiver' => $ary['receiver'],
1262                  'added'    => $current_time,
1263                  'msg'      => $ary['msg'],
1264                  'subject'  => $ary['subject'],
1265                  'saved'    => ( isset($ary['saved']) ? $ary['saved'] : 0 ),
1266                  'location' => 1,
1267                 'reply_to' => ( isset($ary['reply_to']) ? $ary['reply_to'] : 0 )
1268             ));
1269         $db->sql_query($sql);
1270         $sended_id = $db->sql_nextid();
1271
1272         $sql = 'UPDATE ' . USERS_TABLE . ' SET user_unread_pms = user_unread_pms + 1 WHERE uid = ' . $ary['receiver'];
1273         $db->sql_query($sql);
1274
1275
1276         if ( strpos($ary['notifs'], '[pm]') !== false || $force_send ) {
1277             $receiver_ary[$ary['receiver']] = array(
1278                 'language' => $ary['language'],
1279                 'class' => $ary['class'],
1280                 'email' => $ary['email'],
1281                 'name' => $ary['name'],
1282                 'sender_name' => ( isset($ary['sender_name']) ? $ary['sender_name'] : $lang['system'] ),
1283                 'message_id' => $sended_id,
1284                 'count' => 0
1285             );
1286
1287             if ( $ary['class'] < UC_MODERATOR ) {
1288                 $count_ary[] = $ary['receiver'];
1289             }
1290         }
1291     }
1292
1293     if ( sizeof($count_ary) ) {
1294         $sql = 'SELECT COUNT(*) AS count, receiver
1295                 FROM ' . PRIVATE_MESSAGES_TABLE . '
1296                 WHERE receiver IN (' . implode(', ', $count_ary) . ')
1297                 AND location = ' . PM_INBOX . '
1298                 GROUP BY receiver';
1299         $result = $db->sql_query($sql);
1300
1301         if ( $row = $db->sql_fetchrow($result) ) {
1302             do {
1303                 $receiver_ary[$row['receiver']] = array_merge($receiver_ary[$row['receiver']], array('count' => $row['count']));
1304             }
1305             while ( $row = $db->sql_fetchrow($result) );
1306         }
1307     }
1308
1309     foreach ( $receiver_ary AS $receiver_id => $ary ) {
1310         $to_language = $ary['language'];
1311
1312         if ( $ary['count'] > $config['max_inbox_privmsgs'] ) {
1313             $messenger->template('pm_received_but_limit_reached', $to_language);
1314         }
1315         else {
1316             $messenger->template('pm_received', $to_language);
1317         }
1318
1319         $messenger->to($ary['email'], $ary['name']);
1320
1321         $u_link = $base_url . '/message.php' . ( $ary['count'] > $config['max_inbox_privmsgs'] ? '' : '?action=viewmessage&id=' . $ary['message_id']);
1322
1323         $messenger->assign_vars(array(
1324             'BOARD_EMAIL' => $config['sitemail'],
1325             'USERNAME' => html_entity_decode($ary['sender_name']),
1326             'U_LINK' => $u_link
1327         ));
1328         $messenger->send(NOTIFY_EMAIL);
1329     }
1330
1331     $messenger->save_queue();
1332 }
1333 /*</span>
1334 <span class="code-comment">
1335     Header and footer functions start
1336
1337 */
1338 function stdhead($title = '', $right_menu = true) {</span>
1339 <span class="code-keyword">    global $userdata, $config, $template, $lang, $db, $images, $root_path, $theme, $cache, $seo;
1340     global $bb_code;
1341     global $page_description;
1342     static $ranks;
1343
1344     if ( !isset($ranks) ) {
1345         $ranks = $cache->obtain_ranks();
1346     }
1347
1348     $find = array('&quot;', '&lt;', '&gt;');
1349
1350     $theme['is_use_right_menu'] = ( $theme['is_use_right_menu'] ? $right_menu : 0 );
1351
1352     $title = strip_tags($title);
1353
1354     $page = request_var('page', 0);
1355     $start = request_var('start', 0);
1356
1357     if ( $page ) {
1358         $title .= ' - ' . $lang['page'] . ' ' . $page;
1359     }
1360     elseif ( $start ) {
1361         $title .= ' - ' . $lang['page'] . ' ' . ( ceil( $start / $config['posts_per_page'] ) + 1 );
1362     }
1363
1364     $keywords = $title;
1365     $page_description = ( empty($page_description) ? str_replace( $find, '', $title) : $page_description );
1366     $title = ( !$title ? $config['sitename'] : $config['sitename'] . ' :: ' . $title);
1367     $title = implode(' :: ', array_reverse(explode(' :: ', $title)));
1368
1369     $keywords = str_replace( $find, '', $keywords);
1370     $keywords = preg_split('/([\W])/u', $keywords, -1PREG_SPLIT_NO_EMPTY);
1371     $keywords = $config['site_keywords'] . ', ' . implode(', ', $keywords);
1372
1373
1374     // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1375     global $seo;
1376     $template->assign_vars( array(
1377             'TRACKER_FULL_URL' => $seo->seo_path['url'],
1378             'SEO_BASE_HREF' => $seo->seo_opt['seo_base_href'],
1379     ));
1380     $seo->set_user_url($userdata['name'], $userdata['uid']);
1381     // www.phpBB-SEO.com SEO TOOLKIT END
1382
1383     //start active users
1384     $l_online_users = '';
1385     $online_userlist = '';
1386     if ( $config['show_online_users'] ) {
1387         $online_userlist = $lang['none'];
1388         $user_forum_sql = '';
1389
1390         if ( defined('IN_PHPBB') ) {
1391             $f = request_var('f', 0);
1392
1393             if ( $f ) {
1394                 $user_forum_sql = " AND s.session_page LIKE '%phpbb2.php%f={$f}%'";
1395             }
1396             else {
1397                 $user_forum_sql = " AND s.session_page LIKE '%phpbb2.php%'";
1398             }
1399             }
1400
1401             $time = ( time() - $config['online_time'] );
1402
1403         $sql = "SELECT u.name, u.uid, u.class, u.parked, u.warneduntil, u.enabled, u.name_append, u.donor, s.session_logged_in, s.session_ip, s.session_user_id
1404                 FROM ".USERS_TABLE." u, ".SESSIONS_TABLE." s
1405                         WHERE u.uid = s.session_user_id
1406                     AND s.session_time >= ". ($time - ((int) ($time % 30))) . "
1407                   $user_forum_sql";
1408          $result = $db->sql_query($sql);
1409
1410         $online_users = array(
1411             'online_users'            => array(),
1412             'total_online'            => 0,
1413             'visible_online'        => 0,
1414             'guests_online'            => 0,
1415         );
1416
1417         if ( $row = $db->sql_fetchrow($result) ) {
1418             $online_userlist = '';
1419
1420             do {
1421                 // Skip multiple sessions for one user
1422                 if ( $row['uid'] <> ANONYMOUS ) {
1423                     if (!isset($online_users['online_users'][$row['session_user_id']])) {
1424                         $online_users['online_users'][$row['session_user_id']] = 1;
1425
1426                         $online_users['visible_online']++;
1427
1428                         // www.phpBB-SEO.com SEO TOOLKIT START
1429                         $seo->set_user_url($row['name'], $row['uid']);
1430                         // www.phpBB-SEO.com SEO TOOLKIT END
1431
1432                         $user_online_link = '<a href="' . append_sid($root_path . 'userdetails.php?id=' . $row['uid']) . '">' . parse_username($row) . '</a>';
1433                         $online_userlist .= ( $online_userlist != '' ) ? ', ' . $user_online_link : $user_online_link;
1434                     }
1435                 }
1436                 else {
1437                     if (!isset($online_users['online_users'][$row['session_ip']])) {
1438                         $online_users['online_users'][$row['session_ip']] = 1;
1439                         $online_users['guests_online']++;
1440                     }
1441                 }
1442             }
1443             while ( $row = $db->sql_fetchrow($result) );
1444         }
1445         $db->sql_freeresult($result);
1446
1447         $online_users['total_online'] = $online_users['visible_online'] + $online_users['guests_online'];
1448
1449         if ( $online_users['total_online'] > $config['record_online_users']) {
1450             $config['record_online_users'] = $online_users['total_online'];
1451              $config['record_online_date'] = time();
1452
1453                 set_config('record_online_users', $online_users['total_online'], true);
1454                set_config('record_online_date'$config['record_online_date'], true);
1455         }
1456         if ( $online_users['total_online'] == 0 ) {
1457             $l_t_user_s =  ( defined('IN_PHPBB') ?  $lang['online_users_at_forum_zero_total'] : $lang['online_users_at_tracker_zero_total'] );
1458         }
1459         else if ( $online_users['total_online'] == 1 ) {
1460             $l_t_user_s = ( defined('IN_PHPBB') ?  $lang['online_user_at_forum_total'] : $lang['online_user_at_tracker_total'] );
1461         }
1462         else {
1463             $l_t_user_s = ( defined('IN_PHPBB') ?  $lang['online_users_at_forum_total'] : $lang['online_users_at_tracker_total'] );
1464         }
1465
1466         if ( $online_users['visible_online'] == 0 ) {
1467             $l_r_user_s = $lang['reg_users_zero_total'];
1468         }
1469         else if ( $online_users['visible_online'] == 1 ) {
1470                 $l_r_user_s = $lang['reg_user_total'];
1471         }
1472         else {
1473             $l_r_user_s = $lang['reg_users_total'];
1474         }
1475
1476         if ( $online_users['guests_online'] == 0 ) {
1477             $l_g_user_s = $lang['guest_users_zero_total'];
1478         }
1479         else if ( $online_users['guests_online'] == 1 )
1480         {
1481                 $l_g_user_s = $lang['guest_user_total'];
1482         }
1483             else
1484         {
1485                 $l_g_user_s = $lang['guest_users_total'];
1486         }
1487         $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
1488         $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
1489         $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
1490     }
1491
1492     $template->assign_vars(array(
1493         'LOGGED_IN_USER_LIST' => $online_userlist,
1494           'TOTAL_USERS_ONLINE' => $l_online_users,
1495           'RECORD_ONLINE_USERS' => sprintf($lang['record_online_users'], $config['record_online_users'], create_date($config['record_online_date'])) )
1496      );
1497      //end active users
1498
1499      $user_rank = ( isset($ranks[$userdata['user_rank_id']]['rank_name']) ? $ranks[$userdata['user_rank_id']]['rank_name'] : '' );
1500
1501      if ( $seo->seo_opt['url_rewrite'] ) {
1502          $current_page = generate_base_url(true) . ( isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI') );
1503     }
1504     else {
1505         $current_page = build_url(true);
1506     }
1507
1508      $template->assign_vars(array(
1509                 'PAGE_TITLE' => $title,
1510                 'KEYWORDS' => $keywords,
1511                 'PAGE_DESCRIPTION' => $page_description,
1512                 'S_USER_LOGGED_IN' => $userdata['session_logged_in'],
1513
1514                 'RSS_FEED' => '<link rel="alternate" type="application/rss+xml" title="' . $config['sitename'] . '" href="' . generate_base_url() . '/rss.php' . ( $userdata['session_logged_in'] ? '?passkey=' . $userdata['torrent_pass'] : '' ) . '" />' . "\n",
1515
1516                 'S_USER_IS_MOD' => ( $userdata['class'] >= UC_MODERATOR ) ? 1 : 0,
1517
1518                 'CURRENT_USER_ID' => $userdata['uid'],
1519
1520                 'CURRENT_USER_POINTS_LEVEL' => $userdata['user_reputation_level'],
1521                 'CURRENT_USER_POINTS' => $userdata['user_reputation'],
1522                 'CURRENT_USER_RANK_NAME' => $user_rank,
1523                 'SITE_DESC' => $config['site_desc'],
1524                 'SITENAME' => $config['sitename'],
1525                 'RIGHT_MENU' => ( $right_menu ? TRUE : FALSE ),
1526                 'SITENAME' => $config['sitename'],
1527                 'SITE_DESC' => $config['site_desc'],
1528                 'SID' => $userdata['session_id'],
1529                 'CURRENT_PAGE' => $current_page,
1530                 'ROOT_PATH'            => $root_path,
1531                 'L_LANGUAGE_CHARSET' => 'utf-8',
1532                 'CURRENT_TIME' => create_date(time(), 'Y-m-d H:i:s'),
1533                 'U_INDEX' => append_sid($root_path . 'index.php'),
1534                 'U_BROWSE' => append_sid($root_path . 'browse.php'),
1535                 'U_UPLOADAPP' => append_sid($root_path . 'uploadapp.php'),
1536                 'U_UPLOAD' => append_sid($root_path . 'upload.php'),
1537                 'U_LOGIN' => append_sid($root_path . 'login.php'),
1538                 'U_SIGNUP' => append_sid($root_path . 'signup.php'),
1539                 'U_FORUM' => append_sid($root_path . 'phpbb2.php'),
1540                 'U_RULES' => append_sid($root_path . 'rules.php'),
1541                 'U_FAQ' => append_sid($root_path . 'faq.php'),
1542                 'U_HELPDESC' => append_sid($root_path . 'helpdesk.php'),
1543                 'U_STAFF' => append_sid($root_path . 'staff.php'),
1544                 'U_BROWSE_WITHOUT_SEED' => append_sid($root_path . 'browse.php?incldead=4'),
1545                 'U_REQUESTS' => append_sid($root_path . 'requests.php'),
1546                 'U_OFFERS' => append_sid($root_path . 'offers.php'),
1547                 'U_USERS' => append_sid($root_path . 'users.php'),
1548                 'U_TOPTEN' => append_sid($root_path . 'topten.php'),
1549                 'U_CHAT' => append_sid($root_path . 'chat.php'),
1550                 'U_MY' => append_sid($root_path . 'my.php'),
1551                 'U_BOOKMARKS' => append_sid($root_path . 'bookmarks.php'),
1552                 'U_MY_SIMPATY' => append_sid($root_path . 'my.php?type=simpaty'),
1553                 'U_MY_CHECKCOMM' => append_sid($root_path . 'my.php?type=checkcomm'),
1554                 'U_MY_BONUS' => ( $config['allow_my_bonus'] ? append_sid($root_path . 'my.php?type=bonus') : '' ),
1555                 'U_MY_INVITES' => ( $config['allow_invite'] ? append_sid($root_path . 'my.php?type=my_invites') : '' ),
1556                 'U_GETRSS' => append_sid($root_path . 'getrss.php'),
1557                 'U_DONATE' => append_sid($root_path . 'donate.php'),
1558                 'U_LOG' => append_sid($root_path . 'log.php'),
1559                 'U_REPORTS' => append_sid($root_path . 'reports.php'),
1560                 'U_USERSEARCH' => append_sid($root_path . 'usersearch.php'),
1561                 'U_RELEASES_ADD' => append_sid($root_path . 'releases.php?action=add'),
1562                 'U_CHEATERS' => append_sid($root_path . 'cheaters.php'),
1563                 'U_NEW_FORUM_POSTS' => append_sid($root_path . 'phpbb2.php?page=search&amp;search_id=newposts'),
1564                 'U_NEW_SITE_COMMENTS' => append_sid($root_path . 'modtask.php?action=new_comments'),
1565     ));
1566
1567     if ( $userdata['session_logged_in'] ) {
1568         if ( strpos($_SERVER['PHP_SELF'], 'index.php') === false ) {
1569             $sql = 'SELECT * FROM news WHERE ( added + news_announce_time * 24 * 60 * 60 ) > UNIX_TIMESTAMP(NOW()) ORDER BY added DESC';
1570             $result = $db->sql_query($sql, 24 * 60 * 60);
1571
1572             if( $row = $db->sql_fetchrow($result) ) {
1573                 $show_news = false;
1574                 $news_ary = array();
1575
1576                 do {
1577                     $n_a_u_c = explode(',', $row['news_announce_user_classes']);
1578                     if ( $n_a_u_c[0] == '' || in_array(strval($userdata['class']), $n_a_u_c, true) || $userdata['class'] >= UC_MODERATOR ) {
1579                         $show_news = true;
1580                         $news_ary[] = $row;
1581                     }
1582                 }
1583                 while ( $row = $db->sql_fetchrow($result) );
1584
1585                 if ( $show_news ) {
1586
1587                     if ( !isset($bb_code) ) {
1588                         require_once($root_path . 'include/bbcode/bbcode.lib.php');
1589                         $bb_code = new bbcode;
1590                     }
1591
1592                     $template->assign_block_vars('news_annoucment', array());
1593
1594                     foreach ( $news_ary AS $key => $ary ) {
1595
1596                         $body = $ary['body'];
1597                             $bb_code->parse($body);
1598                             $body = $bb_code->get_html();
1599
1600                         $template->assign_block_vars('news_annoucment.news_annoucment_row', array(
1601                             'NEWS_ID' => $ary['id'],
1602                             'NEWS_ADDED' => create_date($ary['added'], 'M d'),
1603                             'NEWS_TITLE' => $ary['title'],
1604                             'NEWS_BODY' =>  $body,
1605                             'U_ADD_COMMENT' => append_sid($root_path . 'comment.php', 'type=' . TYPE_NEWS . '&amp;action=add&amp;tid=' . $ary['id']),
1606                             'COMMENTS_COUNT' => $ary['news_comments'],
1607                             'DISABLE_COMMENTS' => $ary['news_disable_comments'],
1608                         ));
1609                     }
1610                 }
1611             }
1612         }
1613
1614
1615         $uped = mksize($userdata['uploaded']);
1616         $downed = mksize($userdata['downloaded']);
1617         $ratio = get_ratio ($userdata['uploaded'], $userdata['downloaded']);
1618         $color = get_ratio_color($ratio);
1619         $ratio = '<span style="color:' . $color . ';">' . $ratio . '</span>';
1620         $avatar = get_user_avatar($userdata['uid'], $userdata['avatar']);
1621         $title = get_user_class_name($userdata['class']);
1622
1623         $template->assign_vars(array(
1624             'S_YOU_HAVE_INVITES' => sprintf($lang['you_have_invites'], $userdata['invites']),
1625             'U_LOGOUT' => append_sid($root_path . 'login.php?action=logout'),
1626             'U_MESSAGES_INBOX' => append_sid($root_path . 'message.php'),
1627             'U_MESSAGES_SENTBOX' => append_sid($root_path . 'message.php?action=viewmailbox&amp;box=' . PM_SENTBOX),
1628             'U_MY_FRIENDS' => append_sid($root_path . 'my.php?type=friends'),
1629             'U_USERDETAILS_LINK' => append_sid($root_path . 'userdetails.php?id=' . $userdata['uid']),
1630
1631             'HELPDESC_NUM' => $config['count_helpdesk_not_solved'],
1632             'REPORTS_NUM' => $config['count_reports_not_solved'],
1633             'CANDIDATES_NUM' => $config['count_candidates_waiting'],
1634             'PM_TITLE' =>( $userdata['user_unread_pms'] ? $lang['new_inbox_pms'] : $lang['no_new_inbox_pms'] ),
1635             'INBOX_PM_PIC' => ( $userdata['user_unread_pms'] ? $images['inboxnew'] : $images['inbox'] ),
1636             'SENTBOX_PIC' => $images['sentbox'],
1637             'BUDDYLIST_PIC' => $images['buddylist'],
1638
1639             'CURRENT_USER_RATIO' => $ratio,
1640             'CURRENT_USER_UPED' => $uped,
1641             'CURRENT_USER_DOWNED' => $downed,
1642             'CURRENT_USER_WARN_PANEL' => ( $userdata['class'] < UC_MODERATOR ? $lang['warns'] . ': ' . warn_panel($userdata['warn']) : '' ),
1643             'CURRENT_USER_NAME' => parse_username($userdata),
1644             'S_CURRENT_TIME' => sprintf($lang['current_time'], '<span id="clock">&nbsp;</span>'),
1645             'CURRENT_USER_AVATAR' => $avatar,
1646             'CURRENT_USER_TITLE' => $title
1647         ));
1648
1649         if ( $userdata['class'] >= $config['min_class_allow_upload'] ) {
1650             $template->assign_block_vars('switch_uploader_view', array());
1651         }
1652         else {
1653             $template->assign_block_vars('switch_non_uploader_view', array());
1654         }
1655
1656         if ( $userdata['class'] >= UC_ADMINISTRATOR ) {
1657             $template->assign_block_vars('switch_admin_view', array());
1658         }
1659         if ( $userdata['class'] == UC_SYSOP ) {
1660             $template->assign_block_vars('switch_sysop_view', array());
1661         }
1662         if ( $userdata['user_unread_pms'] ) {
1663             $template->assign_block_vars('new_messages', array(
1664                 'UNREAD_MESSAGES' => sprintf($lang['unread_messages'], $userdata['user_unread_pms'])
1665             ));
1666         }
1667     }
1668
1669     if ( defined('IN_PHPBB') ) {
1670         define('HEADER_INC', TRUE);
1671
1672         // Start add - Online/Offline/Hidden Mod
1673         // Define global text color
1674         $online_color = ' style="color: #' . $theme['online_color'] . '"';
1675         $offline_color = ' style="color: #' . $theme['offline_color'] . '"';
1676         $hidden_color = ' style="color: #' . $theme['hidden_color'] . '"';
1677         // End add - Online/Offline/Hidden Mod
1678         // Format Timezone. We are unable to use array_pop here, because of PHP3 compatibility
1679         $l_timezone = explode('.', $config['board_timezone']);
1680         $l_timezone = (sizeof($l_timezone) > 1 && $l_timezone[sizeof($l_timezone)-1] != 0) ? $lang['tz'][sprintf('%.1f', $config['board_timezone'])] : $lang['tz'][number_format($config['board_timezone'])];
1681
1682         //
1683         // The following assigns all _common_ variables that may be used at any point
1684         // in a template.
1685         //
1686         $template->assign_vars(array(
1687             'S_INDEX_SEARCH' => sprintf($lang['forum_index_search'], $config['sitename']),
1688
1689             'L_INDEX_SEARCH' => sprintf($lang['forum_index_search'], $config['sitename']),
1690             'L_SEARCH_SELF' => $lang['search_your_posts'],
1691
1692             'U_SEARCH_UNANSWERED' => append_sid($root_path . 'phpbb2.php?page=search&amp;search_id=unanswered'),
1693             'U_SEARCH_SELF' => append_sid($root_path . 'phpbb2.php?page=search&amp;search_id=egosearch'),
1694             'U_SEARCH_NEW' => append_sid($root_path . 'phpbb2.php?page=search&amp;search_id=newposts'),
1695             'U_SEARCH' => append_sid($root_path . 'phpbb2.php?page=search'),
1696             'U_MODCP' => append_sid($root_path . 'phpbb2.php?page=modcp'),
1697             'U_GROUP_CP' => append_sid($root_path . 'phpbb2.php?page=groupcp'),
1698               // [start] DST
1699             'S_TIMEZONE' => sprintf($lang['all_times'], $l_timezone) . ( (($userdata['uid'] != ANONYMOUS && $userdata['user_dst']) || ($userdata['uid'] == ANONYMOUS && $config['board_dst']) ) ? ' ' . $lang['dst'] : '' ),
1700             // [end] DST
1701         ));
1702     }
1703
1704     $GLOBALS['do_gzip_compress'] = false;
1705     if ( $config['gzip_compress'] ) {
1706         $phpver = phpversion();
1707
1708         $useragent = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : getenv('HTTP_USER_AGENT');
1709
1710         if ( $phpver >= '4.0.4pl1' && ( strstr($useragent,'compatible') || strstr($useragent,'Gecko') ) ) {
1711              if ( @extension_loaded('zlib') && !headers_sent() ) {
1712                     ob_start('ob_gzhandler');
1713                  }
1714          }
1715           else if ( $phpver > '4.0' ) {
1716              if ( strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) {
1717                  if ( @extension_loaded('zlib') && !headers_sent() ) {
1718                      $GLOBALS['do_gzip_compress'] = true;
1719                      ob_start();
1720                      ob_implicit_flush(0);
1721                      header('Content-Encoding: gzip');
1722                  }
1723              }
1724          }
1725     }
1726
1727     // application/xhtml+xml not used because of IE
1728     header('Content-type: text/html; charset=UTF-8');
1729
1730     return;
1731 }
1732
1733 function stdfoot() {
1734     global $userdata, $lang, $template, $starttime, $theme, $db, $do_gzip_compress, $config, $cache, $root_path, $user_ip;
1735     global $seo;
1736
1737     // Server Load START
1738     // We are trying to obtain current processor load
1739     $os = strtolower(PHP_OS);
1740     $cur_load = $lang['na'];
1741     if(strpos($os, 'win') === false) {
1742         if(@file_exists('/proc/loadavg')) {
1743                 if ($load = @file('/proc/loadavg')) {
1744                     list($cur_load) = explode(' ', $load[0]);
1745                 }
1746             }
1747             elseif($uptime = @exec("uptime")) {
1748                 preg_match( "/\: ([0-9\.]+),[\s]+([0-9\.]+),[\s]+([0-9\.]+)/", $uptime, $load );
1749                 $cur_load = $load[1];
1750             }
1751     }
1752      // Server Load END
1753
1754     $admin_link = ( $userdata['class'] >= UC_ADMINISTRATOR ? '<a href="' . append_sid($root_path . 'admin/index.php', false, true, $userdata['session_id']) . '">' . $lang['admin_panel'] . '</a><br />' : '' );
1755
1756     if ( $theme['is_use_right_menu'] ) {
1757         $template->assign_block_vars('right_menu', array());
1758
1759         $sql = "SELECT f.*,  t.topic_title, t.topic_id
1760                     FROM " . FORUMS_TABLE . " f, " . POSTS_TABLE . " p
1761                     LEFT JOIN " . TOPICS_TABLE . " t ON t.topic_id = p.topic_id
1762                     WHERE f.forum_last_post_id = p.post_id
1763                     ORDER BY t.topic_last_post_time DESC";
1764           $result = $db->sql_query($sql, 10 * 60);
1765
1766         $forum_data = array();
1767         while( $row = $db->sql_fetchrow($result) ) {
1768             $forum_data[] = $row;
1769          }
1770         $db->sql_freeresult($result);
1771
1772         $auth_forums = array();
1773         $is_auth_ary = auth(AUTH_VIEW, AUTH_LIST_ALL, $userdata, $forum_data);
1774
1775         foreach ( $is_auth_ary AS $forum_id => $forum_ary ) {
1776             if ( $forum_ary['auth_view'] ) {
1777                 $auth_forums[] = $forum_id;
1778             }
1779         }
1780
1781         if ( sizeof($auth_forums) ) {
1782
1783             $sql = 'SELECT t.topic_id, t.topic_title, t.topic_last_post_id, f.forum_id, f.forum_name
1784                     FROM ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . ' f
1785                         WHERE t.topic_moved_id = 0
1786                     AND t.forum_id=f.forum_id
1787                     AND f.forum_id IN (' . implode(', '$auth_forums ) . ')
1788                         ORDER BY t.topic_last_post_time DESC';
1789               $result = $db->sql_query_limit($sql, 10, 0, 10 * 60);
1790
1791               if ( $row = $db->sql_fetchrow($result) ) {
1792                 do {
1793                     // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1794                     $seo->set_url($row['topic_title'], $row['topic_id'], $seo->seo_static['topic']);
1795                     // www.phpBB-SEO.com SEO TOOLKIT END
1796
1797                     $row['topic_title'] = split_string($row['topic_title'], 54);
1798
1799                     $template->assign_block_vars('right_menu.new_at_forum', array(
1800                         'U_TOPIC' => append_sid($root_path . 'phpbb2.php?page=viewtopic&amp;f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id'] . '&amp;p=' . $row['topic_last_post_id']) . '#' . $row['topic_last_post_id'],
1801                         'TOPIC_TITLE' => $row['topic_title']
1802                     ));
1803                    }
1804                    while ( $row = $db->sql_fetchrow($result) );
1805               }
1806
1807             $sql = 'SELECT t.topic_id, t.topic_title, t.topic_last_post_id, f.forum_id, f.forum_name, f2.forum_id AS p_forum_id, f2.forum_name AS p_forum_name, c.cat_id, c.cat_title
1808                     FROM ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . ' f
1809                     LEFT JOIN ' . FORUMS_TABLE . ' f2 ON ( f.forum_parent = f2.forum_id ),
1810                     ' . FORUM_CATEGORIES_TABLE . ' c
1811                         WHERE t.topic_moved_id = 0
1812                     AND t.forum_id = f.forum_id
1813                     AND f.cat_id = c.cat_id
1814                     AND f.forum_id IN (' . implode(', '$auth_forums ) . ')
1815                         ORDER BY t.topic_replies + t.topic_views DESC';
1816               $result = $db->sql_query_limit($sql, 10, 0, 10 * 60);
1817
1818               if ( $row = $db->sql_fetchrow($result) ) {
1819                 do {
1820                     // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1821                     $seo->set_url($row['cat_title'], $row['cat_id'], $seo->seo_static['forum_cat']);
1822                     $seo->set_parent($row['forum_id'], $seo->seo_static['forum'], $row['cat_id'], $seo->seo_static['forum_cat']);
1823
1824                     if ( !empty($row['p_forum_id']) ) {
1825                         $seo->set_url($row['p_forum_name'], $row['p_forum_id'], $seo->seo_static['forum']);
1826                         $seo->set_parent($row['forum_id'], $seo->seo_static['forum'], $row['p_forum_id'], $seo->seo_static['forum']);
1827                     }
1828
1829                     $seo->set_url($row['forum_name'], $row['forum_id'], $seo->seo_static['forum']);
1830
1831                     $seo->set_parent($row['topic_id'], $seo->seo_static['topic'], $row['forum_id'], $seo->seo_static['forum']);
1832                     $seo->set_url($row['topic_title'], $row['topic_id'], $seo->seo_static['topic']);
1833                     // www.phpBB-SEO.com SEO TOOLKIT END
1834
1835                     $row['topic_title'] = split_string($row['topic_title'], 54);
1836
1837                     $template->assign_block_vars('right_menu.pop_at_forum', array(
1838                         'U_TOPIC' => append_sid($root_path . 'phpbb2.php?page=viewtopic&amp;f=' . $row['forum_id'] . '&amp;t=' . $row['topic_id']),
1839                         'TOPIC_TITLE' => $row['topic_title']
1840                     ));
1841                    }
1842                    while ( $row = $db->sql_fetchrow($result) );
1843               }
1844          }
1845
1846         $sql = 'SELECT t.fid, t.name, c.name AS cat_name, c.id AS category
1847                 FROM ' . TORRENTS_TABLE . ' t, ' . CATEGORIES_TABLE . ' c
1848                     WHERE t.category = c.id
1849                 AND t.banned = 0
1850                 AND t.leechers > 0 ' .
1851                 ( !$userdata['session_logged_in'] ? ' AND c.anonymous_view = 1' : '' )  . '
1852                     ORDER BY t.seeders + t.leechers DESC';
1853           $result = $db->sql_query_limit($sql, 10, 0, 10 * 60);
1854           if ( $row = $db->sql_fetchrow($result) ) {
1855             do {
1856                 $dispname = censor_text($row['name']);
1857                 // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1858                 $seo->set_torrent_url($row['fid'], $row['name'], $row['category']);
1859                 // www.phpBB-SEO.com SEO TOOLKIT END
1860
1861                 $template->assign_block_vars('right_menu.active_torrents', array(
1862                     'U_TORRENT' => append_sid($root_path . 'details.php?id=' . $row['fid']),
1863                     'TORRENT_NAME' => split_string($dispname, 54)
1864                 ));
1865                }
1866                while ( $row = $db->sql_fetchrow($result) );
1867           }
1868
1869         $sql = 'SELECT t.fid, t.name, c.name AS cat_name, c.id AS category
1870                 FROM ' . TORRENTS_TABLE . ' t, ' . CATEGORIES_TABLE . ' c
1871                 WHERE t.category = c.id
1872                 AND t.banned = 0
1873                 AND t.leechers > 0 ' .
1874                 ( !$userdata['session_logged_in'] ? ' AND c.anonymous_view = 1' : '' )  . '
1875                     ORDER BY completed DESC';
1876           $result = $db->sql_query_limit($sql, 10, 0, 10 * 60);
1877         if ( $row = $db->sql_fetchrow($result) ) {
1878             do {
1879                 $dispname = censor_text($row['name']);
1880                 // www.phpBB-SEO.com SEO TOOLKIT BEGIN
1881                 $seo->set_torrent_url($row['fid'], $row['name'], $row['category']);
1882                 // www.phpBB-SEO.com SEO TOOLKIT END
1883
1884                 $template->assign_block_vars('right_menu.popular_torrents', array(
1885                     'U_TORRENT' => append_sid($root_path . 'details.php?id=' . $row['fid']),
1886                     'TORRENT_NAME' => split_string($dispname, 54)
1887                 ));
1888                }
1889                while ( $row = $db->sql_fetchrow($result) );
1890           }
1891     }
1892     // Output page creation time
1893     if (defined('DEBUG'))
1894     {
1895         $mtime = explode(' ', microtime());
1896         $totaltime = $mtime[0] + $mtime[1] - $starttime;
1897
1898         if (!empty($_REQUEST['explain']) && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report') && $userdata['class'] >= UC_ADMINISTRATOR)
1899         {
1900             $db->sql_report('display');
1901         }
1902
1903         $debug_output = sprintf($lang['time'] . ' : %.3fs | ' . $db->sql_num_queries() . ' ' . $lang['sql_queries'] . ' | ' . $lang['gzip'] . ' : ' .  (($config['gzip_compress']) ? $lang['on'] : $lang['off']) . ' | ' . $lang['load'] . ' : ' . $cur_load, $totaltime);
1904
1905         if (defined('DEBUG_EXTRA'))
1906         {
1907             if (function_exists('memory_get_usage'))
1908             {
1909                 if ($memory_usage = memory_get_usage())
1910                 {
1911                     global $base_memory_usage;
1912                     $memory_usage -= $base_memory_usage;
1913                     $memory_usage = mksize($memory_usage);
1914
1915                     $debug_output .= ' | ' . $lang['memory_usage'] . ': ' . $memory_usage;
1916                 }
1917             }
1918             if ( $userdata['class'] >= UC_ADMINISTRATOR && defined('DEBUG_EXTRA') ) {
1919                 $current_page = build_url();
1920                 $debug_output .= ' | <a href="' . append_sid($current_page . ( strpos( $current_page, '?' ) ? '&amp;' : '?' ) . 'explain=1') . '">Explain</a>';
1921             }
1922         }
1923     }
1924
1925     $lang_copyright = ( isset($lang['lang_copyright']) && !empty($lang['lang_copyright']) ? sprintf($lang['translated_by'], $lang['lang_copyright']) : '' );
1926
1927         $template->assign_vars(array(
1928                 'LANG_COPYRIGHT' => $lang_copyright,
1929                 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
1930                 'ADMIN_LINK'   => $admin_link)
1931         );
1932
1933         $template->display('body');
1934
1935         if ( !defined('IN_ERROR_HANDLER')  && !defined('IN_CLEANUP') ) {
1936             require_once($root_path . 'include/class.cleanup.php');
1937             $cleanup = new cleanup();
1938         }
1939
1940         if ( $do_gzip_compress ) {
1941             //
1942             // Borrowed from php.net!
1943             //
1944              $gzip_contents = ob_get_contents();
1945                ob_end_clean();
1946
1947              $gzip_size = strlen($gzip_contents);
1948              $gzip_crc = crc32($gzip_contents);
1949
1950              $gzip_contents = gzcompress($gzip_contents, 9);
1951              $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
1952
1953              echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
1954              echo $gzip_contents;
1955              echo pack('V', $gzip_crc);
1956              echo pack('V', $gzip_size);
1957      }
1958
1959     gc();
1960 }
1961 /*</span>
1962 <span class="code-comment">
1963     Header and footer functions end
1964
1965 */
1966
1967 function gc ( $msg = '' ) {</span>
1968 <span class="code-keyword">    global $cache, $db;
1969
1970     if ( !empty($cache) ) {
1971         $cache->unload();
1972     }
1973     if ( !empty($db) ) {
1974         $db->sql_close();
1975     }
1976     exit($msg);
1977 }
1978
1979 function set_tracking ( $type, $id ) {
1980     global $config, $userdata;
1981     static $tracking;
1982
1983     if ( !isset($tracking) ) {
1984         $tracking = ( isset( $_COOKIE[$config['cookie_name'] . '_tt'] ) ) ? unserialize( $_COOKIE[$config['cookie_name'] . '_tt'] ) : array();
1985     }
1986
1987     $onlinesince = (int) $config['onlinesince'];
1988
1989     foreach ( $tracking AS $_key => $_val ) {
1990         $time = $tracking[$_key][key($_val)];
1991         //more then 7 days old
1992         if ( ( $time + $onlinesince ) < ( time() - 7 * 24 * 60 * 60 )  ) {
1993         unset($tracking[$_key][key($_val)]);
1994         }
1995     }
1996
1997     $tracking[$type][$id] = time() - $onlinesince;
1998
1999     set_cookie('tt', serialize($tracking));
2000 }
2001
2002 function get_tracking ( $type, $id ) {
2003     global $config, $userdata;
2004     static $tracking;
2005
2006     if ( !isset($tracking) ) {
2007         $tracking = ( isset( $_COOKIE[$config['cookie_name'] . '_tt'] ) ) ? unserialize( $_COOKIE[$config['cookie_name'] . '_tt'] ) : array();
2008     }
2009
2010     $user_lastvisit = ( $userdata['session_logged_in'] ? $userdata['user_lastvisit'] : time() );
2011
2012     return ( !empty($tracking[$type][$id]) ? $tracking[$type][$id] + $config['onlinesince'] : $user_lastvisit );
2013 }
2014 ?>
Note: See TracBrowser for help on using the browser.