| 
 
        
          |  |  |  |  |  
          |  |  | 
            
              | แก้โคดให้หน่อยครับ 
 <?php
 /*****************************************************************************/
 /* Subs.php                                                                  */
 /*****************************************************************************/
 /* YaBB SE: Yet another Bulletin Board Splinter Edition                      */
 /* Open-Source Project inspired by Zef Hemel ([email protected])              */
 /* Software Version:           YaBB SE 1.5.1                                 */
 /* Software by:                The YaBB SE Development Team                  */
 /* ========================================================================= */
 /* Software Distributed by:    http://www.yabbse.org                         */
 /* Copyright 2001-2003 by:     http://www.lewismedia.com (Lewis Media)       */
 /* Support, News, Updates at:  http://www.yabbse.org/community               */
 /* Inspired and Ported From:   http://www.yabbforum.com                      */
 /*****************************************************************************/
 /* This program is free software; you may redistribute it and/or modify it   */
 /* under the terms of the provided license as published by Lewis Media.      */
 /*                                                                           */
 /* This program is distributed in the hope that it will be useful, but       */
 /* WITHOUT ANY WARRANTY; without even the implied warranty of                */
 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the provided    */
 /* license for more information.                                             */
 /*                                                                           */
 /* See license.txt for details of the YaBB SE license. The latest version    */
 /* of this license can be found at the distributor's site seen above.        */
 /*****************************************************************************/
 
 $subsphpver = 'YaBB SE 1.5.1';
 
 ### Set the Cookie Exp. Date and the Current Date###
 $Cookie_Exp_Date = 'Sun, 17-Jan-2038 00:00:00 GMT'; # default just in case
 #&SetCookieExp;
 #&get_date;
 
 $board = (isset($board) ? trim($board) : '');
 $currentboard = $board;
 
 $pwseed = 'ys';
 
 $scripturl = "$boardurl/index.php";
 $cgi = "$scripturl?board=$board";
 
 $yyheaderdone = 0;	// this is used to make the fatal error thing work better
 
 //Speedup Boardindex function
 function updateLastMessage($board)
 {
 global $db_prefix;
 $result = mysql_query("
 SELECT m.ID_TOPIC
 FROM {$db_prefix}messages AS m,{$db_prefix}topics as t
 WHERE m.ID_MSG=t.ID_LAST_MSG
 AND t.ID_BOARD=$board
 ORDER BY m.posterTime DESC
 LIMIT 1") or database_error(__FILE__, __LINE__);
 if (mysql_num_rows($result) > 0)
 {
 list($lastTopicID) = mysql_fetch_array($result);
 $request = mysql_query("UPDATE {$db_prefix}boards SET ID_LAST_TOPIC=$lastTopicID WHERE ID_BOARD=$board") or database_error(__FILE__, __LINE__);
 }
 elseif (strlen(mysql_error()))
 fatal_error(mysql_error());
 else
 $request = mysql_query("UPDATE {$db_prefix}boards SET ID_LAST_TOPIC=0 WHERE ID_BOARD=$board") or database_error(__FILE__, __LINE__);
 }
 
 function updateStats($type)
 {
 global $db_prefix;
 
 switch ($type)
 {
 case 'member' :
 $result = mysql_query("SELECT memberName,realName FROM {$db_prefix}members ORDER BY dateRegistered DESC LIMIT 1") or database_error(__FILE__, __LINE__);
 list($latestmember,$latestRealName) = mysql_fetch_row($result);
 $result = mysql_query("SELECT COUNT(*) FROM {$db_prefix}members;") or database_error(__FILE__, __LINE__);
 list($memberCount) = mysql_fetch_row($result);
 $request = mysql_query("
 REPLACE INTO {$db_prefix}settings (variable,value)
 VALUES ('latestMember','$latestmember'),('latestRealName','$latestRealName'),('memberCount','$memberCount')") or database_error(__FILE__, __LINE__);
 break;
 case 'message' :
 $result = mysql_query("
 SELECT COUNT(*) as totalMessages
 FROM {$db_prefix}messages") or database_error(__FILE__, __LINE__);
 $row = mysql_fetch_assoc($result);
 $request = mysql_query("
 UPDATE {$db_prefix}settings SET value='$row[totalMessages]'
 WHERE variable='totalMessages'") or database_error(__FILE__, __LINE__);
 break;
 case 'topic' :
 $result = mysql_query("
 SELECT COUNT(*)  as totalTopics
 FROM {$db_prefix}topics") or database_error(__FILE__, __LINE__);
 $row = mysql_fetch_assoc($result);
 $request = mysql_query("
 UPDATE {$db_prefix}settings SET value='$row[totalTopics]'
 WHERE variable='totalTopics'") or database_error(__FILE__, __LINE__);
 break;
 }
 }
 
 function footer()
 {
 global $yyboardname, $yytitle, $yyuname, $yyim, $yytime, $yymenu, $yymain;
 global $yytemplate, $yycopyin, $yytemplatemain, $yycopyright, $settings, $yyVBStyleLogin, $yynews;
 global $modSettings, $time_start, $txt;
 
 for ($i = $yytemplatemain; $i < sizeof($yytemplate); $i++)
 {
 $curline = $yytemplate[$i];
 if (!$yycopyin && strstr($curline,'<yabb copyright>'))
 $yycopyin = 1;
 $tags = array();
 while (preg_match("/<yabb\s+(\w+)>/", $curline, $tags))
 {
 $temp = "yy$tags[1]";
 if (function_exists($temp))
 {
 ob_start();
 $temp();
 $str = ob_get_contents();
 $curline = preg_replace("/<yabb\s+$tags[1]>/", $str, $curline);
 ob_end_clean();
 }
 else
 $curline = preg_replace("/<yabb\s+$tags[1]>/",$$temp,$curline);
 }
 if ($modSettings['timeLoadPageEnable'] == 1 && stristr($curline, '</body>'))
 {
 $time_end = getmicrotime();
 $time = round($time_end - $time_start, 3);
 $curline = preg_replace('/<\/body>/i', '<div align="center"><font size="1">' . $txt['yse301'] . $time . $txt['yse302'] . '</font></div></body>', $curline);
 }
 
 echo "$curline\n";
 }
 # Do not remove hard-coded text - it's in here so users cannot change the text easily (as if it were in .lng)
 if ($yycopyin == 0)
 echo '
 <div align="center"><font size="5"><b>Sorry, the copyright tag <yabb copyright> must be in the template.<br />Please notify this ' . "forum's" . ' administrator that this site is using an ILLEGAL copy of YaBB!</b></font></div>';
 }
 
 function template_header()
 {
 global $yytemplate, $yyboardname, $yytitle, $yyuname, $yyim, $yytime, $yymenu, $yymain, $yycopyright;
 global $yynews, $menusep, $enable_notification, $enable_news, $username, $db_prefix, $locale, $boarddir;
 global $maintenance, $txt, $mbname, $date, $settings, $cgi, $img, $scripturl, $helpfile, $realname, $yyheaderdone;
 global $yycopyin, $yytemplatemain, $yytitle, $yyVBStyleLogin, $timeformatstring, $timeoffset, $modSettings, $imagesdir;
 global $mnum, $munred, $ID_MEMBER;
 
 // print stuff to prevent cacheing of pages
 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
 header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
 if ($modSettings['disableCaching'] == 1)
 {
 header("Cache-Control: no-cache, must-revalidate");
 header("Pragma: no-cache");
 }
 
 $yymenu = "<a href=\"$scripturl\">$img[home]</a>$menusep<a href=\"$helpfile\" target=\"_blank\">$img[help]</a>$menusep<a href=\"$cgi;action=search\">$img[search]</a>";
 if ($settings[7] == 'Administrator')
 $yymenu .= "$menusep<a href=\"$cgi;action=admin\">$img[admin]</a>";
 if ($username == 'Guest')
 $yymenu .= "$menusep<a href=\"$cgi;action=login\">$img[login]</a>$menusep<a href=\"$cgi;action=register\">$img[register]</a>";
 else
 {
 $euser = urlencode($username);
 $yymenu .= "$menusep<a href=\"$cgi;action=profile;user=$euser\">$img[profile]</a>";
 if ($enable_notification)
 $yymenu .= "$menusep<a href=\"$cgi;action=shownotify\">$img[notification]</a>";
 if ($modSettings['cal_enabled'] == 1)
 $yymenu .= "$menusep<a href=\"$scripturl?action=calendar\">$img[calendar]</a>";
 $yymenu .= "$menusep<a href=\"$cgi;action=logout;sesc=" . session_id() . "\">$img[logout]</a>";
 }
 
 if ($enable_news == 1)
 {
 $newsmessages = explode("\n", str_replace("\r", '', trim(stripslashes($modSettings['news']))));
 // if we've disabled the fader....
 srand(time());
 // then some bum decided we should display a random news item
 $newstring = '';
 if (sizeof($newsmessages) == 1)
 $newstring = $newsmessages[0];
 elseif (sizeof($newsmessages) > 1)
 $newstring = $newsmessages[floor(rand(0,(sizeof($newsmessages) - 1)))];
 $yynews = '<b>' . $txt[102] . ':</b> ' . DoUBBC($newstring);
 }
 if ($username != 'Guest')
 {
 $request = mysql_query("SELECT COUNT(*), readBy FROM {$db_prefix}instant_messages WHERE (ID_MEMBER_TO=$ID_MEMBER AND deletedBy != 1) GROUP BY readBy") or database_error(__FILE__, __LINE__);
 if (mysql_num_rows($request) == 0)
 $munred = $mnum = 0;
 elseif (mysql_num_rows($request) == 1)
 {
 list($mnum, $readBy) = mysql_fetch_row($request);
 if ($readBy == 0)
 $munred = $mnum;
 else
 $munred = 0;
 }
 else
 {
 list($munred, $dummy) = mysql_fetch_row($request);
 list($mnum, $dummy) = mysql_fetch_row($request);
 $mnum += $munred;
 }
 if ($munred == 1)
 $isare = $txt['newmessages0'];
 else
 $isare = $txt['newmessages1'];
 if ($mnum == '1')
 $yyim = "$txt[152] <a href=\"$cgi;action=im\">$mnum $txt[471]</a>$txt[newmessages4] $munred $isare $txt[newmessages2].";
 else
 $yyim = "$txt[152] <a href=\"$cgi;action=im\">$mnum $txt[153]</a>$txt[newmessages4] $munred $isare $txt[newmessages2].";
 if ($maintenance)
 $yyim .= "<br /><b>$txt[616]</b>";
 }
 
 ob_start();
 $templateFile = "$boarddir/template.php";
 if (!file_exists($templateFile))
 $templateFile = "$boarddir/template.html";
 include($templateFile);
 $yytemplate = explode("\n", ob_get_contents());
 ob_end_clean();
 
 if (!sizeof($yytemplate))
 die("$txt[23]: $templateFile");
 
 $yyboardname = $mbname;
 $time = (isset($settings[18]) ? $settings[18] : 0);
 
 $yytime = lang_strftime(time() + (($timeoffset + $time) * 3600));
 // display their username if they haven't set their real name yet.
 $tmp = ($realname == '' ? $username : $realname);
 $yyuname = ($username == 'Guest' ? "$txt[248] <b>$txt[28]</b>. $txt[249] <a href=\"$cgi;action=login\">$txt[34]</a> $txt[377] <a href=\"$cgi;action=register\">$txt[97]</a>." : "$txt[247] <b>$tmp</b>, ");
 $yycopyin = 0;
 
 $yyVBStyleLogin = '<br />';
 if ($modSettings['enableVBStyleLogin'] == '1' && $username == 'Guest')
 $yyVBStyleLogin = '
 <form action="' . $cgi . ';action=login2" method="post"><br />
 <input type="text" name="user" size="7" />
 <input type="password" name="passwrd" size="7" />
 <select name="cookielength">
 <option value="60">' . $txt['yse53'] . '</option>
 <option value="1440">' . $txt['yse47'] . '</option>
 <option value="10080">' . $txt['yse48'] . '</option>
 <option value="302400">' . $txt['yse49'] . '</option>
 <option value="' . $txt['yse50'] . '" selected="selected">' . $txt['yse50'] . '</option>
 </select>
 <input type="submit" value="' . $txt[34] .'" /><br />
 ' . $txt['yse52'] . '
 </form>';
 
 for ($yytemplatemain = 0; $yytemplatemain < sizeof($yytemplate); $yytemplatemain++)
 {
 $curline = $yytemplate[$yytemplatemain];
 if (strstr($curline,'<yabb main>'))
 {
 $yytemplatemain++;
 break;
 }
 if (!$yycopyin && strstr($curline, '<yabb copyright>'))
 $yycopyin = 1;
 $tags = array();
 while (preg_match("/<yabb\s+(\w+)>/", $curline, $tags))
 {
 $temp = "yy$tags[1]";
 if (function_exists($temp))
 {
 ob_start();
 $temp();
 $str = ob_get_contents();
 $curline = preg_replace("/<yabb\s+$tags[1]>/", $str, $curline);
 ob_end_clean();
 }
 else
 $curline = preg_replace("/<yabb\s+$tags[1]>/", $$temp, $curline);
 }
 
 echo "$curline\n";
 }
 
 if ($settings[7] == 'Administrator')
 {
 $securityFiles = array('install.php', 'upgrade.php');
 $message = '';
 foreach ($securityFiles as $securityFile)
 if (file_exists($securityFile))
 $message .= '<br />   ' . $txt['yse300'] . $securityFile . '!';
 
 if ($message != '')
 echo '<font color="red">' . $txt['yse299'] . $message . '</font>';
 }
 
 $yyheaderdone = 1;
 }
 
 function url_parts()
 {
 global $boardurl, $modSettings;
 $cookie_dom = ''; $cookie_dir = '/';
 
 if ($modSettings['localCookies'] == '1') {
 $url .= $boardurl . "/";
 $pos = strpos($url, '//');
 if ($pos > 0 && strncmp(strtolower($url), 'http:', $pos) == 0)	//Valid protocol
 {
 $urlpos = strpos($url, '/', $pos + 2);
 
 if ($urlpos > 0)
 {
 $cookie_dom = substr($url, $pos + 2, $urlpos - $pos - 2);
 $cookie_dir = substr($url, $urlpos);
 }
 }
 }
 
 return "$cookie_dom<yse_sep>$cookie_dir";
 }
 
 
 function jeffsdatediff($now, $old)
 {
 $dis = $now - $old;	// Diff In Secs
 $secs = $dis % 60; // modulo
 $dis -= $secs;
 $days = floor($dis / (24 * 60 * 60));
 $dis -= $days * (24 * 60 * 60);
 $hours = floor($dis / (60 * 60));
 $dis -= $hours * (60 * 60);
 $mins = floor($dis / 60);
 $dis -= $mins * 60;
 return $days;
 }
 
 function lang_strftime($currtime)
 {
 global $locale, $days, $months, $days_short, $months_short, $username, $settings, $timeformatstring;
 
 if ($username == 'Guest' || $settings[17] == '')
 $str = stripslashes($timeformatstring);
 else
 $str = stripslashes($settings[17]);
 
 if (setlocale(LC_TIME, $locale))
 {
 $str = ereg_replace('%a', ucwords(strftime('%a', $currtime)), $str);
 $str = ereg_replace('%A', ucwords(strftime('%A', $currtime)), $str);
 $str = ereg_replace('%b', ucwords(strftime('%b', $currtime)), $str);
 $str = ereg_replace('%B', ucwords(strftime('%B', $currtime)), $str);
 }
 else
 {
 $str = ereg_replace('%a', $days_short[(int)strftime('%w', $currtime)], $str);
 $str = ereg_replace('%A', $days[(int)strftime('%w', $currtime)], $str);
 $str = ereg_replace('%b', $months_short[(int)strftime('%m', $currtime) - 1], $str);
 $str = ereg_replace('%B', $months[(int)strftime('%m', $currtime) - 1], $str);
 $str = ereg_replace('%p', ((int)strftime('%H', $currtime) < 12 ? "am" : "pm"), $str);
 }
 
 return strftime($str, $currtime);
 }
 
 function timeformat($logTime)
 {
 global $timeformatstring, $username, $settings, $timeoffset, $txt, $db_prefix, $locale, $modSettings;
 
 $time = (isset($settings[18]) ? $settings[18] : 0);
 $time = ($timeoffset + $time) * 3600;
 $nowtime = $time + time();
 $time += $logTime;
 if ($modSettings['todayMod'] >= 1)
 {
 $t1 = getdate($time);
 $t2 = getdate($nowtime);
 $strtfmt = (($username == 'Guest' || $settings[17] == '') ? $timeformatstring : $settings[17]);
 
 if ((strpos($strtfmt, '%H') === false) && (strpos($strtfmt, '%T') === false))
 $today_fmt = 'h:i:sa';
 else
 $today_fmt = 'H:i:s';
 
 if ($t1['yday'] == $t2['yday'] && $t1['year'] == $t2['year'])
 return $txt['yse10'] . date($today_fmt, $time);
 if ((($t1['yday'] == $t2['yday'] - 1 && $t1['year'] == $t2['year']) || ($t2['yday'] == 0 && $t1['year'] == $t2['year'] - 1) && $t1['mon'] == 12 && $t1['mday'] == 31) && $modSettings['todayMod'] == '2')
 return $txt['yse10b'] . date($today_fmt, $time);
 }
 return lang_strftime ($time);
 }
 
 function jumpto()
 {
 global $board, $txt, $settings, $scripturl, $db_prefix;
 $request = mysql_query("
 SELECT name,ID_CAT
 FROM {$db_prefix}categories
 WHERE (FIND_IN_SET('$settings[7]',memberGroups) != 0 OR memberGroups='' OR '$settings[7]'='Administrator' OR '$settings[7]'='Global Moderator')
 ORDER BY catOrder") or database_error(__FILE__, __LINE__);
 
 $selecthtml = "<select name=\"values\" onchange=\"if (this.options[this.selectedIndex].value) window.location.href='$scripturl' + this.options[this.selectedIndex].value;\">";
 $selecthtml .= "<option value=\"\">$txt[251]:</option>\n";
 while ($row = mysql_fetch_row($request))
 {
 $selecthtml .= "<option value=\"\">-----------------------------</option>\n";
 $selecthtml .= "<option value=\"#$row[1]\">$row[0]</option>\n";
 $selecthtml .= "<option value=\"\">-----------------------------</option>\n";
 $request2 = mysql_query("SELECT name,ID_BOARD FROM {$db_prefix}boards WHERE ID_CAT=$row[1] ORDER BY boardOrder") or database_error(__FILE__, __LINE__);
 while ($row2 = mysql_fetch_row($request2))
 {
 if ($board == $row2[1])
 $selecthtml .= "<option value=\"?board=$row2[1]\" selected=\"selected\"> =>$row2[0]</option>\n";
 else
 $selecthtml .= "<option value=\"?board=$row2[1]\"> =>$row2[0]</option>\n";
 }
 }
 $selecthtml .= "</select> <input type=\"button\" value=\"$txt[161]\" onclick=\"if (values.options[values.selectedIndex].value) window.location.href='$scripturl' + values.options[values.selectedIndex].value;\" />";
 return $selecthtml;
 }
 
 
 function sendmail($to, $subject, $message, $from = null)
 {
 global $mailtype, $webmaster_email, $modSettings;
 
 $chunkSize = 50;
 
 $to_array = (is_array($to) ? $to : array($to));
 
 if ($from == null)
 $from = $webmaster_email;
 $subject = stripslashes($subject);
 $subject = str_replace(array('"', ''', '&', '<', '>'), array('"', '\'', '&', '<', '>'), $subject);
 $message = stripslashes($message);
 $headers = "MIME-Version: 1.0\r\n";
 $headers .= "From: <$webmaster_email>\r\n";
 $headers .= "Return-Path: $webmaster_email";
 
 if ($modSettings['mail_type'] == 'sendmail')
 foreach ($to_array as $to)
 $mail_result = mail($to, $subject, $message, $headers);
 else
 smtp_mail($to_array, $subject, $message, $headers);
 
 return $mail_result;
 }
 
 function smtp_mail($mail_to_array, $subject, $message, $headers)
 {
 global $modSettings, $webmaster_email;
 
 if (!$socket = fsockopen($modSettings['smtp_host'], 25, $errno, $errstr, 20))
 fatal_error("Could not connect to smtp host : $errno : $errstr");
 
 server_parse($socket, '220');
 
 if ($modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
 {
 fputs($socket, "EHLO $modSettings[smtp_host]\r\n");
 server_parse($socket, '250');
 fputs($socket, "AUTH LOGIN\r\n");
 server_parse($socket, '334');
 fputs($socket, base64_encode($modSettings['smtp_username']) . "\r\n");
 server_parse($socket, '334');
 fputs($socket, base64_encode($modSettings['smtp_password']) . "\r\n");
 server_parse($socket, '235');
 }
 else
 {
 fputs($socket, 'HELO ' . $modSettings['smtp_host'] . "\r\n");
 server_parse($socket, '250');
 }
 foreach($mail_to_array as $mail_to)
 {
 fputs($socket, "MAIL FROM: <$webmaster_email>\r\n");
 server_parse($socket, '250');
 $to_header = "To: <$mail_to>";
 fputs($socket, "RCPT TO: <$mail_to>\r\n");
 server_parse($socket, '250');
 fputs($socket, "DATA\r\n");
 server_parse($socket, '354');
 fputs($socket, "Subject: $subject\r\n");
 if (strlen($mail_to))
 fputs($socket, "$to_header\r\n");
 fputs($socket, "$headers\r\n\r\n");
 fputs($socket, "$message\r\n");
 fputs($socket, ".\r\n");
 server_parse($socket, '250');
 fputs($socket, "RSET\r\n");
 server_parse($socket, '250');
 }
 fputs($socket, "QUIT\r\n");
 fclose($socket);
 }
 
 function server_parse($socket, $response)
 {
 while (substr($server_response, 3, 1) != ' ')
 if (!($server_response = fgets($socket, 256)))
 fatal_error('Couldn\'t get mail server response codes');
 
 if (!(substr($server_response, 0, 3) == $response))
 fatal_error("Ran into problems sending Mail. Error: $server_response");
 }
 
 function spam_protection()
 {
 global $timeout, $REMOTE_ADDR, $txt, $db_prefix;
 
 $time = time();
 $ip = $REMOTE_ADDR;
 
 $request = mysql_query("DELETE FROM {$db_prefix}log_floodcontrol WHERE ($time-logTime > $timeout)") or database_error(__FILE__, __LINE__);
 $request = mysql_query("SELECT ip FROM {$db_prefix}log_floodcontrol WHERE ip='$REMOTE_ADDR' LIMIT 1") or database_error(__FILE__, __LINE__);
 if (mysql_num_rows($request) == 0)
 {
 $request = mysql_query("INSERT INTO {$db_prefix}log_floodcontrol (ip,logTime) VALUES ('$REMOTE_ADDR',$time)") or database_error(__FILE__, __LINE__);
 return (false);
 }
 else
 {
 fatal_error("$txt[409] $timeout $txt[410]");
 return (true);
 }
 }
 
 function SetCookieExp()
 {
 global $Cookie_Length, $Cookie_Exp_Date;
 # set to default if missing
 if ($Cookie_Length == '') { $Cookie_Length = '120'; }
 $expires = $Cookie_Length * 60;
 $Cookie_Exp_Date = gmdate("D, d-M-Y H:i:s GMT", (time() + $expires));
 }
 
 /**
 * Preparses a message, puts [url] tags around urls etc.
 * @param $message the message to parse the code in
 * @return the preparsed code
 */
 
 function preparsecode($message, $realname, $username)
 {
 global $settings, $ext;
 
 if (strstr($realname, '[') || strstr($realname, ']') || strstr($realname, '\'') || strstr($realname, '"'))
 $realname = $username;
 
 $codes = array('/(\/me) (.*)([\r\n]?)/i');
 $codesto = array("[me=$realname]\\2[/me]\\3");
 
 $message = preg_replace($codes, $codesto, $message);
 $message = str_replace("\r", '', $message);
 
 // Check if all quotes are closed
 $parts = preg_split ("/(\[\/quote\])/is", $message, -1, PREG_SPLIT_DELIM_CAPTURE);
 
 $level = 0;
 for ($i = 0; $i < count($parts); $i++)
 {
 if (preg_match('/\[\/quote\]/i',$parts[$i]) !=0 )
 $level--;
 preg_match_all("/(\[quote author=(.+?) link=(.+?) date=(.+?)\])|(\[quote\])/is", $parts[$i], $regs);
 $level += count ($regs[0]);
 while ($level < 0)
 {
 $parts[$i] = '[quote]'.$parts[$i];
 $level++;
 }
 }
 $message = implode ('', $parts);
 while ($level > 0)
 {
 $message .= '[/quote]';
 $level--;
 }
 
 // Check if all code tags are closed
 preg_match_all("/(\[code\])/", $message, $regs);
 $codeopen = count($regs[0]);
 preg_match_all("/(\[\/code\])/", $message, $regs);
 $codeclose = count($regs[0]);
 
 if ($codeopen > $codeclose)
 {
 $toclose = $codeopen - $codeclose;
 for ($i = 0 ; $i < $toclose ; $i++)
 $message .= "[/code]";
 }
 elseif ($codeclose > $codeopen)
 {
 $toopen = $codeclose - $codeopen;
 for ($i = 0 ; $i < $toopen ; $i++)
 $message = "[code]$message";
 }
 
 // now that we've fixed all the code tags, let's fix the IMG and URL tags
 $parts = split('\[\/?code\]', " $message");
 
 for ($i = 0 ;$i < count($parts) ;$i++)
 {
 if ($i % 2 == 0)
 {
 $parts[$i] = fixTags($parts[$i]);
 if ($i > 0)
 $parts[$i] = '[/code]' . $parts[$i];
 }
 else
 $parts[$i] = '[code]' . $parts[$i];
 }
 $message = substr(implode('', $parts), 1);
 return $message;
 }
 
 function fixTags($message)
 {
 $fixArray = array
 (
 array('tag' => 'img', 'protocol' => 'http', 'embeddedUrl' => false, 'hasEqualSign' => false),
 array('tag' => 'url', 'protocol' => 'http', 'embeddedUrl' => true, 'hasEqualSign' => false),
 array('tag' => 'url', 'protocol' => 'http', 'embeddedUrl' => true, 'hasEqualSign' => true),
 array('tag' => 'iurl', 'protocol' => 'http', 'embeddedUrl' => true, 'hasEqualSign' => false),
 array('tag' => 'iurl', 'protocol' => 'http', 'embeddedUrl' => true, 'hasEqualSign' => true),
 array('tag' => 'ftp', 'protocol' => 'ftp', 'embeddedUrl' => true, 'hasEqualSign' => false),
 array('tag' => 'ftp', 'protocol' => 'ftp', 'embeddedUrl' => true, 'hasEqualSign' => true),
 array('tag' => 'flash', 'protocol' => 'http', 'embeddedUrl' => false, 'hasEqualSign' => true)
 );
 
 foreach ($fixArray as $param)
 $message = fixTag($message, $param['tag'], $param['protocol'], $param['embeddedUrl'], $param['hasEqualSign']);
 
 return $message;
 }
 
 function fixTag($message, $myTag, $protocol, $embeddedUrl = false, $hasEqualSign = false)
 {
 $isEqual = ($hasEqualSign ? '(=(.+?))' : '(())');
 while (preg_match("/\[($myTag)$isEqual\](.+?)\[\/($myTag)\]/si", $message, $matches))
 {
 $leftTag = $matches[1];
 $equalTo = $matches[3];
 $searchfor = $matches[4];
 $rightTag = $matches[5];
 //print_r($matches);
 //exit();
 $replace = ($hasEqualSign && $embeddedUrl ? $equalTo : $searchfor);
 $replace = trim($replace);	// remove all leading and trailing whitespaces
 if (!stristr($replace, "$protocol://"))
 {
 if ($protocol != 'http' || !stristr($replace,'https://'))
 $replace = "$protocol://$replace";
 else
 $replace = stristr($replace, 'https://');
 }
 else
 $replace = stristr($replace, "$protocol://");
 if ($hasEqualSign && $embeddedUrl)
 $message = str_replace(
 "[$leftTag=$equalTo]{$searchfor}[/$rightTag]",
 "\{$myTag=$replace]$searchfor\{/$myTag\}", $message);
 elseif ($hasEqualSign && !$embeddedUrl)
 $message = str_replace(
 "[$leftTag=$equalTo]{$searchfor}[/$rightTag]",
 "\{$myTag=$equalTo]$replace\{/$myTag\}", $message);
 elseif ($embeddedUrl)
 $message = str_replace(
 "[$leftTag]{$searchfor}[/$rightTag]",
 "\{$myTag=$replace]$searchfor\{/$myTag\}", $message);
 else
 $message = str_replace(
 "[$leftTag]{$searchfor}[/$rightTag]",
 "\{$myTag\}$replace\{/$myTag\}", $message);
 }
 if ($embeddedUrl || $hasEqualSign)
 $message = str_replace(
 array("\{$myTag=", "\{/$myTag\}"),
 array("[$myTag=", "[/$myTag]"), $message);
 else
 $message = str_replace(
 array("\{$myTag\}", "\{/$myTag\}"),
 array("[$myTag]", "[/$myTag]"), $message);
 return $message;
 }
 
 /**
 * Parses both smilies and kB code as required
 * @param $message the message to parse the code in
 * @param $boarddata the data array of the current board
 * @param $code whether or not to parse kB codes
 * @param $smilies same for smilies :-)
 */
 
 function doUBBC($message,$enableSmilies = 1)
 {
 //echo $message;
 global $settings, $text, $txt;
 
 $parts = split('\[\/?code\]', ' ' . $message);
 
 for ($i = 0; $i < count($parts); $i++)
 {
 if ($i % 2 == 0)
 {
 $parts[$i] = str_replace(array('$', '[[', ']]'), array('$', '{<{', '}>}'), $parts[$i]);
 if ($i > 0)
 $parts[$i] = '</font></td></tr></table></td></tr></table>' . $parts[$i];
 $parts[$i] = preg_replace("/([\n >\(])([\w\-_]+?):\/\/([\w\-_@:]+)((\.[\w\-_]+)+(:[\d]+)?((\/[\w\-_%]+(\.[\w\-_%]+)*)|(\/[~]?[\w\-_%]*))*(\/?(\?[&;=\w\+%]+)*)?(#[\w\-_]*)?)/", "\\1[url=\\2://\\3\\4]\\2://\\3\\4[/url]", $parts[$i]);
 $parts[$i] = preg_replace("/([\n >\(])www((\.[\w\-_]+)+(:[\d]+)?((\/[\w\-_%]+(\.[\w\-_%]+)*)|(\/[~]?[\w\-_%]*))*(\/?(\?[&;=\w\+%]+)*)?(#[\w\-_]*)?)/", "\\1[url=http://www\\2]www\\2[/url]", $parts[$i]);
 $parts[$i] = doparsecodesmilies($parts[$i], $enableSmilies);
 }
 elseif ($i <= count($parts) - 1)
 $parts[$i] = '<table border="0" cellpadding="0" cellspacing="0"><tr><td><font size="1"><b>' . $txt['yse238'] . ':</b></font></td></tr></table><table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#000000"><tr><td><table border="0" cellspacing="1" cellpadding="2" width="100%"><tr><td class="code"><font face="Courier new">' . $parts[$i];
 }
 $message = substr(implode('', $parts), 1);
 $message = str_replace(
 array('{<{', '}>}', '  ', "\t", "\n\r", "\r", "\n"),
 array('[', ']', '  ', '    ', '<br />', '<br />', '<br />'), $message);
 /*	$message = str_replace('{<{','[',$message);
 $message = str_replace('}>}',']',$message);
 // $message = stripslashes($message); // Maybe you'll have to uncomment this
 $message = str_replace("  ","  ",$message);
 $message = str_replace("\t","    ",$message);
 $message = str_replace("\n\r","<br>",$message);
 $message = str_replace("\r","<br>",$message);
 $message = str_replace("\n","<br>",$message);*/
 
 return $message;
 
 }
 
 /**
 * This function is being called by the above function (in a regexp) and will parse
 * smilies and tags as desired outside [code] and [php] tags.
 * @param $message the message to parse the code in
 * @param $boarddata the data array of the current board
 */
 
 function doparsecodesmilies($message,$enableSmilies = 1)
 {
 global $codefromcache, $codetocache, $smileyfromcache, $smileytocache, $text, $scripturl, $imagesdir, $txt, $modSettings;
 
 if (gettype($codefromcache) != 'array' || gettype($smileyfromcache) != 'array')
 {
 $codefromcache = array(
 '/\[url\](.+?)\[\/url\]/is',
 '/\[url=(.+?)\](.+?)\[\/url\]/is',
 '/\[iurl\](.+?)\[\/iurl\]/is',
 '/\[iurl=(.+?)\](.+?)\[\/iurl\]/is',
 '/\[b\](.+?)\[\/b\]/is',
 '/\[i\](.+?)\[\/i\]/is',
 '/\[u\](.+?)\[\/u\]/is',
 '/\[s\](.+?)\[\/s\]/is',
 '/\[move\](.+?)\[\/move\]/is',
 '/\n?\[quote author=(.+?) link=(.+?) date=(.+?)\](?:\n|\<br \/\>)*/ei',
 '/\[\/quote\]/i',
 '/\n?\[quote\](?:\n|\<br \/\>)*/i',
 '/\[me=([^\]]+)\](.+?)\[\/me\]/is',
 '/\[img\](.+?)\[\/img\]/i',
 '/\[img width=([0-9]+) height=([0-9]+)\s*\](.+?)\[\/img\]/i',
 '/\[img height=([0-9]+) width=([0-9]+)\s*\](.+?)\[\/img\]/i',
 '/\[color=([\w#]+)\](.*?)\[\/color\]/is',
 '/\[black\](.+?)\[\/black\]/is',
 '/\[white\](.+?)\[\/white\]/is',
 '/\[red\](.+?)\[\/red\]/is',
 '/\[green\](.+?)\[\/green\]/is',
 '/\[blue\](.+?)\[\/blue\]/is',
 '/\[font=(.+?)\](.+?)\[\/font\]/is',
 '/\[size=(.+?)\](.+?)\[\/size\]/is',
 '/\[pre\](.+?)\[\/pre\]/is',
 '/\[left\](.+?)\[\/left\]/is',
 '/\[right\](.+?)\[\/right\]/is',
 '/\[center\](.+?)\[\/center\]/is',
 '/\[sub\](.+?)\[\/sub\]/is',
 '/\[sup\](.+?)\[\/sup\]/is',
 '/\[tt\](.+?)\[\/tt\]/is',
 '/\[table\]\s*(.+?)\s*\[\/table\]\s?/is',
 '/\s*\[tr\]\s*(.*?)\s*\[\/tr\]\s*/is',
 '/\s*\[td\]\s*(.*?)\s*\[\/td\]\s*/is',
 '/\[ftp\](.+?)\[\/ftp\]/is',
 '/\[ftp=(.+?)\](.+?)\[\/ftp\]/is',
 '/\[glow=(.+?),(.+?),(.+?)\](.+?)\[\/glow\]/eis',
 '/\[shadow=(.+?),(.+?)\](.+?)\[\/shadow\]/eis',
 '/\[email\](.+?)\[\/email\]/is',
 '/\[hr\]/i',
 '/\[flash=(\S+?),(\S+?)\](\S+?)\[\/flash\]/is',
 '/\[list\]/',
 '/\[\/list\]/',
 '/(=)?([a-z0-9_-][a-z0-9\._-]*@[a-z0-9_-]+(\.[a-z0-9_-]+)+)(\/)?/eis',
 '/\[email=(.+?)\](.+?)\[\/email\]/is',
 '/(<\/?table>|<\/?tr>|<\/td>)<br \/>/');
 
 $codetocache = array(
 '<a href="\\1" target="_blank">\1</a>',
 '<a href="\\1" target="_blank">\2</a>',
 '<a href="\\1">\\1</a>',
 '<a href="\1">\\2</a>',
 '<b>\\1</b>',
 '<i>\\1</i>',
 '<u>\\1</u>',
 '<s>\\1</s>',
 '<marquee>\\1</marquee>',
 "'<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td><font size=\"1\"><b><a href=\"$scripturl?action=display;\\2\">$txt[yse239]: \\1 $txt[176] '.timeformat('\\3').'</a></b></font></td></tr></table><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#000000\"><tr><td><table border=\"0\" cellspacing=\"1\" cellpadding=\"2\" width=\"100%\"><tr><td class=\"quote\">'",
 "</td></tr></table></td></tr></table>",
 "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td><font size=\"1\"><b>$txt[yse240]:</b></font></td></tr></table><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#000000\"><tr><td><table border=\"0\" cellspacing=\"1\" cellpadding=\"2\" width=\"100%\"><tr><td class=\"quote\">",
 "<font class=\"meaction\">* \\1 \\2</font>",
 '<img src="\\1" alt="" border="0" />',
 '<img src="\\3" alt="" border="0" width="\\1" height="\\2" />',
 '<img src="\\3" alt="" border="0" width="\\2" height="\\1" />',
 '<font color="\\1">\\2</font>',
 '<font color="#000000">\\1</font>',
 '<font color="#FFFFFF">\\1</font>',
 '<font color="#FF0000">\\1</font>',
 '<font color="#00FF00">\\1</font>',
 '<font color="#0000FF">\\1</font>',
 '<font face="\\1">\\2</font>',
 '<font size="\\1">\\2</font>',
 '<pre>\\1</pre>',
 '<div align="left">\\1</div>',
 '<div align="right">\\1</div>',
 '<div align="center">\\1</div>',
 '<sub>\\1</sub>',
 '<sup>\\1</sup>',
 '<tt>\\1</tt>',
 '<table>\\1</table>',
 '<tr>\\1</tr>',
 '<td>\\1</td>',
 '<a href="\\1" target="_blank">\\1</a>',
 '<a href="\\1" target="_blank">\\2</a>',
 "'<table style=\"border 0px;\"><tr><td style=\"filter:Glow(color=\\1, strength=' . ('\\2' < 255 ? '\\2' : '255') . ');\">' . \"\\4\" . '</td></tr></table>'",
 "'<table style=\"border 0px;\"><tr><td style=\"filter:Shadow(color=\\1, direction=' . ('\\2' == 'left' ? '270' : ('\\2' == 'right' ? '90' : ('\\2' == 'top' ? '0' : ('\\2' == 'bottom' ? '180' : '\\2')))) . ');\">' . \"\\3\" . '</td></tr></table>'",
 '\\1',
 '<hr />',
 $modSettings['enableEmbeddedFlash'] == '1' ? '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="\\1" height="\\2"><param name="movie" value="\\3" /><param name="play" value="true" /><param name="loop" value="true" /><param name="quality" value="high" /><embed src="\\3" width="\\1" height="\\2" play="true" loop="true" quality="high"></embed></object>' : '<a href="\\3" target="_new">\\3</a>',
 '<ul>',
 '</ul>',
 "('\\4' != '/' && '\\1' != '=' ? '<a href=\"mailto:\\2\">\\2</a>' : '\\1\\2')",
 '<a href="mailto:\\1">\\2</a>',
 '\\1');
 //			"<table style=\"Filter: Glow(Color=\\1, Strength='.(('\\2'<400)?'\\2':400).')\" width='.(('\\3'<400)?'\\3':400).'\>\\4</table>",
 //			"<table style=\"Filter: Glow(Color=\\1, Strength=(?(\\2<400)\\2|400)\" width=\"(?(\\3<400)\\3|400)\"\>\\4</table>",
 
 // Instead we use:
 $smiliesfrom = array('::)', '>:(', '>:(', '>:D', '>:D', ':)', ';)', ':D', ';D', ':(', ':o', '8)', ':P', '???', ':-[', ':-X', ':-*', ":'(", ':'(', ':-\\', '^-^', 'O0');
 
 $smiliesto = array('rolleyes', 'angry', 'angry', 'evil', 'evil', 'smiley', 'wink', 'cheesy', 'grin', 'sad', 'shocked', 'cool', 'tongue', 'huh', 'embarassed', 'lipsrsealed', 'kiss', 'cry', 'cry', 'undecided', 'azn', 'afro'); // You'll get the idea
 
 // This smiley regex makes sure it doesn't parse smilies within code tags (so [url=mailto:[email protected]] doesn't parse the :D smiley)
 for ($i = 0; $i < count($smiliesfrom); $i++)
 {
 $smileyfromcache[] = '/([>\s\n\r]|(?:(?:(?:>[^<]*)|(?:^[^<]*))[\s\n\r]))(' . str_replace('|', '\|', quotemeta(str_replace('/', '\/', $smiliesfrom[$i]))) . ')/s';
 $smileytocache[] = "\\1<img src=\"$imagesdir/$smiliesto[$i].gif\" alt=\"\" border=\"0\" />";
 }
 }
 
 if ($enableSmilies)
 $message = parsesmilies($message);
 
 $message = parsecode($message);
 
 // List items
 $itemcode = array(
 '*' => '',
 '@' => ' type="disc"',
 '+' => ' type="square"',
 'x' => ' type="square"',
 '#' => ' type="square"',
 'o' => ' type="circle"',
 '0' => ' type="circle"');
 $message = preg_replace("!\\[([*@+x#o0])\\]!Uie", '\'<li\'.$itemcode[\'\\1\'].\'>\'', $message);
 
 return $message;
 
 }
 
 /**
 * Parses the special KeyBulletin code (also being used in UBB, YaBB, iB and other boards)
 * and returns it parsed (duh).
 * @param $message the message to parse the code in
 * @return the parsed code
 */
 
 function parsecode($message)
 {
 global $codefromcache, $codetocache, $modSettings;
 
 if (!strstr($message, '[') && !strstr($message, '://') && !strstr($message, '@') && !strstr($message, '/me'))
 return $message;
 
 if (gettype($codefromcache) != 'array')
 return $message;
 
 $message = preg_replace($codefromcache, $codetocache, $message);
 
 $maxwidth = $modSettings['maxwidth'];
 $maxheight = $modSettings['maxheight'];
 if (!($maxwidth == '0' && $maxheight == '0'))
 {
 preg_match_all('/<img src="(http:\/\/.+?)" alt="" border="0" \/>/is', $message, $imgmatches, PREG_PATTERN_ORDER);
 for ($i = 0; $i < count($imgmatches[1]); $i++)
 {
 $imagesize = @getimagesize($imgmatches[1][$i]);
 $width = $imagesize[0];
 $height = $imagesize[1];
 if ($width > $maxwidth || $height > $maxheight)
 {
 if ($width > $maxwidth && $maxwidth != '0')
 {
 $height = floor($maxwidth / $width * $height);
 $width = $maxwidth;
 if ($height > $maxheight && $maxheight != '0')
 {
 $width = floor($maxheight / $height * $width);
 $height = $maxheight;
 }
 }
 else
 {
 if ($height > $maxheight && $maxheight != '0')
 {
 $width = floor($maxheight / $height * $width);
 $height = $maxheight;
 }
 }
 }
 $imgnew[$i] = "<img src=\"{$imgmatches[1][$i]}\" width=\"$width\" height=\"$height\" alt=\"\" border=\"0\" />";
 }
 $message = str_replace($imgmatches[0], $imgnew, $message);
 }
 
 return $message;
 }
 
 /**
 * Parses smilies in the specified $message
 * @param $message the message to parse
 * @return the parsed code
 */
 
 function parsesmilies($message)
 {
 global $smileyfromcache, $smileytocache;
 
 $oldmessage = '';
 while ($oldmessage != $message)
 {
 $oldmessage = $message;
 $message = preg_replace($smileyfromcache, $smileytocache, $message);
 }
 return $message;
 }
 
 function KickGuest()
 {
 global $yytitle, $txt, $scripturl, $color, $cgi, $Cookie_Length;
 
 $yytitle = $txt[34];
 template_header();
 echo '
 <form action="' . $cgi . ';action=login2" method="post">
 <table border="0" cellspacing="1" bgcolor="' . $color['bordercolor'] . '" class="bordercolor" align="center">
 <tr>
 <td class="titlebg" bgcolor="' . $color['titlebg'] . '"><font size="2" class="text1" color="' . $color['titletext'] . '"><b>' . $txt[633] . '</b></font></td&
 
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            16 ก.พ. 2550  22:38:37 | By :
                            วุ่น |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  
 
        
          |  |  |  |  |  
          |  |  | 
            
              | <td class="windowbg" bgcolor="' . $color['windowbg'] . '"><font size="2"><br /> ' . $txt[634] . '<br />
 ' . $txt[635] . ' <a href="' . $cgi . ';action=register">' . $txt[636] . '</a> ' . $txt[637] . '
 <br /><br /></font></td>
 </tr><tr>
 <td class="titlebg" bgcolor="' . $color['titlebg'] . '"><font size="2" class="text1" color="' . $color['titletext'] . '"><b>' . $txt[34] . '</b></font></td>
 </tr><tr>
 <td class="windowbg" bgcolor="' . $color['windowbg'] . '"><font size="2">
 <table border="0" align="left">
 <tr>
 <td align="right"><font size="2"><b>' . $txt[35] . ':</b></font></td>
 <td><font size="2"><input type="text" name="user" size="20" /></font></td>
 </tr><tr>
 <td align="right"><font size="2"><b>' . $txt[36] . ':</b></font></td>
 <td><font size="2"><input type="password" name="passwrd" size="20" /></font></td>
 </tr><tr>
 <td align="right"><font size="2"><b>' . $txt[497] . ':</b></font></td>
 <td><font size="2"><input type="text" name="cookielength" size="4" maxlength="4" value="' . $Cookie_Length . '" /></font></td>
 </tr><tr>
 <td align="right"><font size="2"><b>' . $txt[508] . ':</b></font></td>
 <td><font size="2"><input type="checkbox" name="cookieneverexp" /></font></td>
 </tr><tr>
 <td align="center" colspan="2"><br /><input type="submit" value="' . $txt[34] . '" /></td>
 </tr><tr>
 <td align="center" colspan="2"><small><small><a href="' . $scripturl . '?action=reminder;what=input_user">' . $txt[315] . '</small></small></a><br /><br /></td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 </form>';
 footer();
 obExit();
 }
 
 /**
 * Highlights passed $code (only works in PHP4+)
 * @param $code code to be parsed
 * @return the php code parsed code
 */
 function phphighlight($code)
 {
 if (floor(phpversion()) < 4)
 $buffer=$code;
 else
 {
 $code = stripslashes($code);
 $code = stripslashes($code);
 $code = str_replace(array('>', '<', '$', '"'), array('>', '<', '$', '"'), $code);
 
 if (!strstr($code, '<?'))
 {
 $code="<?php\n".trim($code)."\n?" .'>';
 $addedtags = 1;
 }
 ob_start();
 $oldlevel = error_reporting(0);
 highlight_string($code);
 error_reporting($oldlevel);
 $buffer = ob_get_contents();
 ob_end_clean();
 $buffer = str_replace('"', '"', $buffer);
 }
 return '<table border="0" cellpadding="0" cellspacing="0"><tr><td><font size="1"><b>PHP:</b></font></td></tr><table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#000000"><tr><td><table border="0" cellspacing="1" cellpadding="2" width="100%"><tr><td class="quote">' . addslashes(addslashes($buffer)) . '</td></tr></table></td></tr></table>';
 }
 
 
 function WriteLog()
 {
 global $REMOTE_ADDR, $username, $db_prefix, $ID_MEMBER;
 
 $logTime = time();
 
 if ($ID_MEMBER == -1 && !empty($REMOTE_ADDR) && ip2long($REMOTE_ADDR) != -1)
 {
 $request = mysql_query ("
 DELETE FROM {$db_prefix}log_online
 WHERE logTime < " . ($logTime - 900) . "
 OR identity=IFNULL(INET_ATON('$REMOTE_ADDR'), -1)") or database_error(__FILE__, __LINE__);
 $request = mysql_query ("
 REPLACE INTO {$db_prefix}log_online
 (identity, logTime)
 VALUES (IFNULL(INET_ATON('$REMOTE_ADDR'), -1), $logTime)") or database_error(__FILE__, __LINE__);
 }
 else
 {
 if (!is_numeric($ID_MEMBER))
 $ID_MEMBER = -1;
 $request = mysql_query ("
 DELETE FROM {$db_prefix}log_online
 WHERE logTime < " . ($logTime - 900) . "
 OR identity=$ID_MEMBER") or database_error(__FILE__, __LINE__);
 $request = mysql_query ("
 REPLACE INTO {$db_prefix}log_online
 (identity, logTime)
 VALUES ($ID_MEMBER, $logTime)") or database_error(__FILE__, __LINE__);
 }
 }
 
 function ClickLog ()
 {
 global $HTTP_REFERER,$HTTP_USER_AGENT,$REMOTE_ADDR,$REQUEST_URI,$ClickLogTime,$db_prefix;
 $logTime = time();
 $threshold = time() - ($ClickLogTime*60);
 $request = mysql_query ("INSERT INTO {$db_prefix}log_clicks (ip,logTime,agent,fromUrl,toUrl) VALUES ('$REMOTE_ADDR',$logTime,'$HTTP_USER_AGENT','$HTTP_REFERER','$REQUEST_URI')") or database_error(__FILE__, __LINE__);
 $request = mysql_query ("DELETE FROM {$db_prefix}log_clicks WHERE logTime<$threshold") or database_error(__FILE__, __LINE__);
 }
 
 function redirectinternal()
 {
 global $currentboard, $sourcedir, $action, $threadid;
 
 if ($currentboard != '' && $action != 'logout')
 {
 if (isset($threadid) && $threadid > 0)
 {
 include_once("$sourcedir/Display.php");
 Display();
 }
 else
 {
 include_once("$sourcedir/MessageIndex.php");
 MessageIndex();
 }
 }
 else
 {
 include_once("$sourcedir/BoardIndex.php");
 BoardIndex();
 }
 obExit();
 }
 
 function redirectexit()
 {
 global $yySetLocation;
 header('Location: ' . str_replace(' ', '%20', $yySetLocation));
 obExit();
 }
 
 function Sticky()
 {
 global $threadid, $board, $moderators, $username, $settings, $txt, $cgi, $yySetLocation, $db_prefix, $doLimitOne;
 if (!in_array($username,$moderators) && $settings[7] != 'Administrator' && $settings[7] != 'Global Moderator')
 fatal_error($txt[67]);
 if ($threadid == '')
 fatal_error('No thread specified!');
 $request = mysql_query("
 UPDATE {$db_prefix}topics
 SET isSticky=IF(isSticky=1,0,1)
 WHERE ID_TOPIC=$threadid
 AND ID_BOARD=$board$doLimitOne") or database_error(__FILE__, __LINE__);
 $yySetLocation = "$cgi;action=display;threadid=$threadid";
 redirectexit();
 }
 
 function ReportToModerator()
 {
 global $txt, $color, $cgi, $thread, $board, $id, $subject, $poster, $username, $sc, $msgid, $yytitle, $modSettings;
 
 if ($modSettings['enableReportToMod'] != '1')
 fatal_error($txt[1]);
 
 $yytitle = $txt['rtm1'];
 template_header();
 
 $rname = LoadRealName($username);
 echo '
 <table border="0" width="80%" cellspacing="1" bgcolor="' . $color['bordercolor'] . '" class="bordercolor" align="center" cellpadding="4">
 <tr>
 <td  class="titlebg" bgcolor="' . $color['titlebg'] . '"><font size="2" class="text1" color="' . $color['titletext'] . '"><b>' . $txt['rtm1'] . '</b></font></td>
 </tr><tr>
 <td class="windowbg" bgcolor="' . $color['windowbg'] . '"><br />
 <form action="' . $cgi . ';action=reporttm2" method="post">
 <font size="2">' . $txt['yse315'] . '</font><br /></br />
 <div align="center">
 <font size="2">' . $txt['rtm2'] . '
 <input type="text" name="comment" value="" size="50" />
 <input type="hidden" name="reporter" value="' . $rname . ' (' . $username . ')" />
 <input type="hidden" name="thread" value="' . $thread . '" />
 <input type="hidden" name="board" value="' . $board . '" />
 <input type="hidden" name="id" value="' . $id . '" />
 <input type="hidden" name="subject" value="' . htmlspecialchars($subject) . '" />
 <input type="hidden" name="poster" value="' . $poster . '" />
 <input type="hidden" name="mid" value="' . $msgid . '" />
 <input type="hidden" name="sc" value="' . $sc . '" />
 <input type="submit" value="' . $txt['rtm10'] . '" />
 </font>
 </div>
 </form>
 </td>
 </tr>
 </table>';
 footer();
 exit;
 }
 
 function ReportToModerator2()
 {
 global $txt,$cgi,$db_prefix,$thread,$board,$id,$subject,$poster,$yySetLocation,$comment,$reporter, $mid, $modSettings;
 
 if ($modSettings['enableReportToMod'] != '1')
 fatal_error($txt[1]);
 
 checkSession();
 
 // first, we create the message...
 $subject = un_html_entities($subject);
 $mailtext = "$txt[rtm6]: $comment\n$txt[rtm5] $reporter\n$txt[rtm7]: $subject\n$txt[rtm4]: $poster\n$txt[rtm9]: $id\n $cgi;action=display;threadid=$thread;start=$id#msg$mid\n\n";
 $mailsub = "$txt[rtm3]:  $subject $txt[rtm4] $poster";
 
 // lets get some mods...
 $themoderators = array();
 
 $result = mysql_query("SELECT moderators FROM {$db_prefix}boards WHERE (ID_BOARD=$board)") or database_error(__FILE__, __LINE__);
 if (mysql_num_rows($result) > 0)
 {
 $mod_row = mysql_fetch_array($result);
 if (strlen($mod_row['moderators']) > 0)
 $themoderators = explode(',', $mod_row['moderators']);
 }
 
 // loop through admins
 $results = mysql_query("SELECT memberName FROM {$db_prefix}members WHERE (memberGroup='Administrator') OR (memberGroup='Global Moderator')") or database_error(__FILE__, __LINE__);
 
 while ($row = mysql_fetch_assoc($results))
 if (!in_array ($row['memberName'], $themoderators))
 $themoderators[] = $row['memberName'];
 
 // OK, send mails...
 if (sizeof($themoderators) > 0)
 {
 while (list($key, $val) = each($themoderators))
 {
 $result = mysql_query("SELECT emailAddress FROM {$db_prefix}members WHERE memberName='$val'") or database_error(__FILE__, __LINE__);
 if ($result)
 {
 $mod_row = mysql_fetch_array($result);
 sendmail($mod_row['emailAddress'], $mailsub, $mailtext);
 }
 }
 }
 else
 fatal_error($txt['rtm11']);
 }
 
 function obExit()
 {
 @ob_end_flush();
 exit;
 }
 
 function yytop()
 {
 
 }
 
 function yybottom()
 {
 
 }
 
 function checkSession($type = 'post')
 {
 global $HTTP_POST_VARS, $sesc, $HTTP_REFERER, $REQUEST_URI, $HTTP_HOST, $txt;
 
 if ($type == 'post')
 {
 if ($HTTP_POST_VARS['sc'] != session_id())
 fatal_error($txt['yse304']);
 }
 else
 {
 if ($sesc != session_id())
 fatal_error($txt['yse305']);
 }
 
 $referer = parse_url($HTTP_REFERER);
 
 if (strpos($HTTP_HOST,':'))
 $rhost = substr($HTTP_HOST,0,strpos($HTTP_HOST,':'));
 else
 $rhost = $HTTP_HOST;
 
 if (strlen($referer['host']) && strlen($rhost) && strtolower($referer['host']) != strtolower($rhost))
 fatal_error($txt['yse306']);
 
 }
 
 function OnlineStatus($user)
 {
 global $db_prefix;
 $onlinequery = @mysql_query("SELECT identity FROM {$db_prefix}log_online WHERE identity = '$user' LIMIT 1") or database_error(__FILE__, __LINE__);
 return (@mysql_num_rows($onlinequery)) ? 1 : 0;
 }
 
 function getMemberID($messageID)
 {
 global $db_prefix;
 $result = mysql_query("
 SELECT IFNULL(mem.ID_MEMBER,-1) AS ID_MEMBER
 FROM {$db_prefix}messages AS m
 LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER=m.ID_MEMBER)
 WHERE m.ID_MSG=$messageID") or database_error(__FILE__, __LINE__);
 if (mysql_num_rows($result) > 0)
 {
 $row = mysql_fetch_array($result);
 return $row['ID_MEMBER'];
 }
 else
 return -1;
 }
 
 function un_html_entities ($string)
 {
 $trans_tbl = get_html_translation_table (HTML_ENTITIES);
 $trans_tbl = array_flip ($trans_tbl);
 $trans_tbl['''] = "'";
 return strtr ($string, $trans_tbl);
 }
 
 ?>
 
 |  
              | 
                
                  |  |  |  |  
                  |  | 
                      
                        | Date :
                            16 ก.พ. 2550  22:42:05 | By :
                            วุ่น |  |  |  
                  |  |  |  |  |  |  |  
          |  |  |  |  |  |