<?php
include ("includes/class.php");

$botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz", "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot", "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler", "Yeti");
$max_lim = 51;

function detect_bot() {
global $botlist;

foreach($botlist as $bot) {
if(ereg($bot, $_SERVER['HTTP_USER_AGENT'])) {

if($bot == "Googlebot") {
if (substr(gethostbyaddr($_SERVER['REMOTE_ADDR']), 0, 11) == "216.239.46.") {
$thebot = 1;
return "Googlebot Deep Crawl";
} elseif (substr(gethostbyaddr($_SERVER['REMOTE_ADDR']), 0,7) == "64.68.8") {
$thebot = 1;
return "Google Freshbot";
}
}
if ($thebot == "") {
return $bot;
}

if ($_SERVER['QUERY_STRING'] != "") {
$url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] . "";
} else {
$url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . "";
}

}
}
}

function gallery($limit) {
global $pre;
global $mrw_1;
global $siteurl;

$temp = mysql_fetch_row(mysql_query("SELECT template FROM ".$pre."templates WHERE name = 'gallery_image'"));

$sql = mysql_query("SELECT * FROM ".$pre."files ORDER BY `id` DESC LIMIT ".$limit);
for($i = 0; $row = mysql_fetch_assoc($sql); $i++) {
$title = "";
$title = mysql_fetch_row(mysql_query("SELECT name FROM ".$pre."gallery WHERE id = '".$row[gallery]."'"));

if (preg_match("/http/", $row[filedir])) {
$images .= "<a href='".$mrw_1["gallery"].fthrough($title[0], "", $row[gallery])."'><img src='".$row[filedir].$row[filename]."' width='159' height='109' alt='Gallery' class='galleryimage' /></a><br />";
} else {
$images .= "<a href='".$mrw_1["gallery"].fthrough($title[0], "", $row[gallery])."'><img src='".$siteurl.$row[filedir]."thumbs/".$row[filename]."' width='159' height='109' alt='Gallery' class='galleryimage' /></a><br />";
}
}
return $images;
}
function soc_bookmark($link, $title, $topic, $des, $icon = 'Y') {
	global $siteurl;
    $link = rawurlencode($link);
    $title = rawurlencode($title);
    $icon_folder = $siteurl."includes/icons/";
    $bookmark = array(
        #'BlinkBits'=>'http://www.blinkbits.com/bookmarklets/save.php?v=1&amp;source_url='.$link.'&amp;title='.$title,
        ##'Del.icio.us'=>'http://del.icio.us/post?v=2&amp;url='.$link.'&amp;title='.$title,
        'Digg'=>'http://digg.com/submit?phase=2&amp;url='.$link.'&amp;title='.$title.'&amp;topic='.htmlentities($topic).'&amp;bodytext='.htmlentities($des),
		'Facebook'=>'http://www.facebook.com/sharer.php?u='.$link.'&amp;t='.$title,
        ##'Fark'=>'http://cgi.fark.com/cgi/fark/submit.pl?new_url='.$link.'&amp;title='.$title,
        'Furl'=>'http://www.furl.net/savedialog.jsp?p=1&t='.$title.'&amp;v=1&amp;u='.$link,
        ##'Google'=>'http://www.google.com/bookmarks/mark?op=add&amp;bkmk='.$link.'&amp;title='.$title,
        ##'Ma.gnolia'=>'http://ma.gnolia.com/bookmarklet/add?url='.$link.'&amp;title='.$title,
        #'MyWeb'=>'http://myweb2.search.yahoo.com/myresults/bookmarklet?t='.$title.'&amp;u='.$link,
        'Netscape'=>'http://www.netscape.com/submit/?U='.$link.'&amp;T='.$title,
        ##'NetVouz'=>'http://netvouz.com/action/submitBookmark?url='.$link.'&amp;title='.$title.'&amp;description='.htmlentities($des).'&amp;popup=no',
        'Newsvine'=>'http://www.newsvine.com/_tools/seed&save?u='.$link.'&amp;h='.$title,
        'Reddit'=>'http://reddit.com/submit?url='.$link.'&amp;title='.$title,
        #'Shadows'=>'http://www.shadows.com/features/tcr.htm?url='.$link.'&amp;title='.$title,
        'Simpy'=>'http://simpy.com/simpy/LinkAdd.do?title='.$title.'&amp;href='.$link,
        ##'Slashdot'=>'http://slashdot.org/bookmark.pl?url='.$link.'&amp;title='.$title,
        'Spurl'=>'http://www.spurl.net/spurl.php?v=3&amp;url='.$link.'&amp;title='.$title,
		'StumbleUpon'=>'http://www.stumbleupon.com/submit?url='.$link.'&amp;title='.$title,
        #'Technorati'=>'http://technorati.com/faves?add='.$link.'&amp;title='.$title,
    );
    foreach($bookmark as $key=>$value) {
        $link_text = $icon == 'Y' ? '<img src="'.$icon_folder.str_replace(".", '', strtolower($key)).'.jpg" alt="Post to '.$key.'" />' : $key;
        $a .= '<a href="'.$value.'" title="Post to '.$key.'">'.$link_text.'</a> ';
    }
	return $a;
}

function watermark($SourceFile, $WatermarkFile, $SaveToFile = NULL) {
// copyright bokehman.com
    $watermark = @imagecreatefrompng($WatermarkFile) or exit('Cannot open the watermark file.');

    imageAlphaBlending($watermark, false);
    imageSaveAlpha($watermark, true);

    $image_string = @file_get_contents($SourceFile) or exit('Cannot open image file.');
    $image = @imagecreatefromstring($image_string) or exit('Not a valid image format.');

    $imageWidth=imageSX($image);
    $imageHeight=imageSY($image);

    $watermarkWidth=imageSX($watermark);
    $watermarkHeight=imageSY($watermark);

    $coordinate_X = ( $imageWidth - 5) - ( $watermarkWidth);
    $coordinate_Y = ( $imageHeight - 5) - ( $watermarkHeight);

    imagecopy($image, $watermark, $coordinate_X, $coordinate_Y, 0, 0, $watermarkWidth, $watermarkHeight);

    if(!($SaveToFile)) header('Content-Type: image/jpeg');

    imagejpeg ($image, $SaveToFile, 100);
    imagedestroy($image);
    imagedestroy($watermark);

    if(!($SaveToFile)) exit;
}

function createThumbs($pathToImages, $pathToThumbs, $fname) {
global $setting;

    $info = pathinfo($pathToImages.$fname);
    // continue only if this is a JPEG image
    if (strtolower($info['extension']) == 'jpg')
    {

      // load image and get image size
      $img = imagecreatefromjpeg("{$pathToImages}{$fname}");
      $width = imagesx($img);
      $height = imagesy($img);

      // calculate thumbnail size
      $new_width = $setting["gallery_width"];
      //$new_height = floor( $height * ( $thumbWidth / $width ) );
	  $new_height = $setting["gallery_height"];

      // create a new temporary image
      $tmp_img = imagecreatetruecolor($new_width, $new_height);

      // copy and resize old image into new image
      imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

      // save thumbnail into a file
      imagejpeg($tmp_img, "{$pathToThumbs}{$fname}", 100);
    }

	if (strtolower($info['extension']) == 'png')
    {

      // load image and get image size
      $img = imagecreatefrompng("{$pathToImages}{$fname}");
      $width = imagesx($img);
      $height = imagesy($img);

      // calculate thumbnail size
      $new_width = $setting["gallery_width"];
      //$new_height = floor( $height * ( $thumbWidth / $width ) );
	  $new_height = $setting["gallery_height"];

      // create a new temporary image
      $tmp_img = imagecreatetruecolor($new_width, $new_height);

      // copy and resize old image into new image
      imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

      // save thumbnail into a file
      imagepng($tmp_img, "{$pathToThumbs}{$fname}", 9);
    }

	if (strtolower($info['extension']) == 'gif')
    {

      // load image and get image size
      $img = imagecreatefromgif("{$pathToImages}{$fname}");
      $width = imagesx($img);
      $height = imagesy($img);

      // calculate thumbnail size
      $new_width = $setting["gallery_width"];
      //$new_height = floor( $height * ( $thumbWidth / $width ) );
	  $new_height = $setting["gallery_height"];

      // create a new temporary image
      $tmp_img = imagecreatetruecolor($new_width, $new_height);

      // copy and resize old image into new image
      imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

      // save thumbnail into a file
      imagegif($tmp_img, "{$pathToThumbs}{$fname}");
    }
}

function stats_check() {
global $pre;

if (date("m") == "01") {
$lmonth = "12";
$lyear = date("Y") -1;
} else {
$lmonth = date("m") - 1;
$lyear = date("Y");
}

if (date("W") == "01") {
$lweek = "52";
} else {
$lweek = date("W") - 1;
}

if (date("z") == "0") {
if (date("L") == "1") {
$lday = "366";
} else {
$lday = "365";
}
$lyear = date("Y") -1;
} else {
$lday = date("z") - 1;
$lyear = date("Y");
}

if ($lweek < "10") {
$lweek = "0".$lweek;
} else {
$lweek = $lweek;
}

if ($lmonth < "10") {
$lmonth = "0".$lmonth;
} else {
$lmonth = $lmonth;
}

$stat_last_week = mysql_fetch_row(mysql_query("SELECT month,year,week FROM ".$pre."stats WHERE year = '".$lyear."' AND week = '".$lweek."'"));
$stats_arch_check1 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats_archive WHERE year = '".$stat_last_week[1]."' AND week = '".$stat_last_week[2]."' AND name = 'last_week'"));

if ($stats_arch_check1 == 0 && $stat_last_week[0]) {
$views1 = 0;
$uniques1 = 0;
$ref = "";$os = "";$bro = "";
$sql = mysql_query("SELECT * FROM ".$pre."stats WHERE year = '".$lyear."' AND week = '".$lweek."'");
while($r = mysql_fetch_array($sql)) {
$week1 = $r[week];
$month1 = $r[month];
$year1 = $r[year];
$ex = explode("|", $r[info]);
if ($r[type] == "view") {
$views1 = $views1 + 1;
}
if ($r[type] == "unique") {
$uniques1 = $uniques1 + 1;
}
}

mysql_query("DELETE FROM ".$pre."stats WHERE year = '".$lyear."' AND week = '".$lweek."'");
mysql_query("INSERT INTO ".$pre."stats_archive VALUES (null, 'last_week', '', '".$week1."', '".$month1."', '".$year1."', '".$views1."', '".$uniques1."', '".time()."')");
if ($views1) {
mysql_query("TRUNCATE `".$pre."stats`");
mysql_query("OPTIMIZE TABLE ".$pre."stats");
}
}

if (mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats WHERE year = '".$lyear."' AND month = '".$lmonth."'")) == 0) {
$lyears = $lyear - 1;
$stat_last_month = mysql_fetch_row(mysql_query("SELECT month,year,week FROM ".$pre."stats WHERE year = '".$lyears."' AND month = '".$lmonth."'"));
} else {
$stat_last_month = mysql_fetch_row(mysql_query("SELECT month,year,week FROM ".$pre."stats WHERE year = '".$lyear."' AND month = '".$lmonth."'"));
}
$stats_arch_check2 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats_archive WHERE month = '".$stat_last_month[0]."' AND year = '".$stat_last_month[1]."' AND name = 'last_month'"));

if (($stats_arch_check2 == 0) && ($stat_last_month[1])) {
$views2 = 0;
$uniques2 = 0;
$ref = "";$os = "";$bro = "";
$sql2 = mysql_query("SELECT * FROM ".$pre."stats WHERE year = '".$lyear."' AND month = '".$lmonth."'");
while($r = mysql_fetch_array($sql2)) {
$week2 = $r[week];
$month2 = $r[month];
$year2 = $r[year];
$ex = explode("|", $r[info]);
if ($r[type] == "view") {
$views2 = $views2 + 1;
}
if ($r[type] == "unique") {
$uniques2 = $uniques2 + 1;
}
}

$sql = mysql_query("SELECT * FROM ".$pre."stats_archive WHERE month = '".$lmonth."' AND year = '".$lyear."' AND name = 'last_week'");
while($r = mysql_fetch_array($sql)) {
$uniques2 = $uniques2 + $r[uniques];
$views2 = $views2 + $r[views];
}

mysql_query("DELETE FROM ".$pre."stats_archive WHERE date = 0");
mysql_query("DELETE FROM ".$pre."stats WHERE year = '".$lyear."' AND month = '".$lmonth."'");
mysql_query("INSERT INTO ".$pre."stats_archive VALUES (null, 'last_month', '', '".$week2."', '".$month2."', '".$year2."', '".$views2."', '".$uniques2."', '".time()."')");
if ($views2) {
mysql_query("TRUNCATE `".$pre."stats`");
mysql_query("OPTIMIZE TABLE ".$pre."stats");
mysql_query("OPTIMIZE TABLE ".$pre."stats_archive");
}
}

$lyear = $lyear - 1;
$stat_last_year = mysql_fetch_row(mysql_query("SELECT month,year,week FROM ".$pre."stats WHERE year = '".$lyear."'"));
$stats_arch_check3 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats_archive WHERE year = '".$stat_last_year[1]."' AND name = 'last_year'"));

if (($stats_arch_check3 == 0) && ($stat_last_year[0])) {
$views3 = 0;
$uniques3 = 0;
$ref = "";$os = "";$bro = "";
$sql3 = mysql_query("SELECT * FROM ".$pre."stats WHERE year = '".$lyear."'");
while($r = mysql_fetch_array($sql3)) {
$week3 = $r[week];
$month3 = $r[month];
$year3 = $r[year];
$ex = explode("|", $r[info]);
if ($r[type] == "view") {
$views3 = $views3 + 1;
}
if ($r[type] == "unique") {
$uniques3 = $uniques3 + 1;
}
}

$sql = mysql_query("SELECT * FROM ".$pre."stats_archive WHERE year = '".$lyear."' AND name = 'last_month'");
while($r = mysql_fetch_array($sql)) {
$uniques3 = $uniques3 + $r[uniques];
$views3 = $views3 + $r[views];
}

mysql_query("DELETE FROM ".$pre."stats_archive WHERE data = 0");
mysql_query("DELETE FROM ".$pre."stats WHERE year = '".$lyear."'");
mysql_query("INSERT INTO ".$pre."stats_archive VALUES (null, 'last_year', '', '".$week3."', '".$month3."', '".$year3."', '".$views3."', '".$uniques3."', '".time()."')");
}
if ($views3) {
mysql_query("TRUNCATE `".$pre."stats`");
mysql_query("OPTIMIZE TABLE ".$pre."stats");
mysql_query("OPTIMIZE TABLE ".$pre."stats_archive");
}
}

function translate() {
return "<form action='http://www.google.com/translate'>
<script language='JavaScript'>
document.write ('<input name=u value='+location.href+' type=hidden>')
</script>

<input name='hl' value='en' type='hidden'>
<input name='ie' value='UTF8' type='hidden'>
<input name='langpair' value='' type='hidden'>

<input name='langpair' value='en|fr' title='French' src= 'http://photos1.blogger.com/img/43/1633/320/13539949_e76af75976.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|de' title='German' src= 'http://photos1.blogger.com/img/43/1633/320/13539933_041ca1eda2.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|it' title='Italian' src= 'http://photos1.blogger.com/img/43/1633/320/13539953_0384ccecf9.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|pt' title='Portuguese' src= 'http://photos1.blogger.com/img/43/1633/320/13539966_0d09b410b5.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|es' title='Spanish' src= 'http://photos1.blogger.com/img/43/1633/320/13539946_2fabed0dbf.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|ja' title='Japanese' src= 'http://photos1.blogger.com/img/43/1633/320/13539955_925e6683c8.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|ko' title='Korean' src= 'http://photos1.blogger.com/img/43/1633/320/13539958_3c3b482c95.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
<input name='langpair' value='en|zh-CN' title='Chinese Simplified' src= 'http://photos1.blogger.com/img/43/1633/320/14324441_5ca5ce3423.jpg' onclick='this.form.langpair.value=this.value' height='20' type='image' width='30'>
</form>";
}

function check($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
   
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
   
      // &#x0040 @ search for the hex values
      $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // &#00064 @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   
   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base', 'img');
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
               $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
               $pattern .= ')?';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return strip_tags($val, "<p><a><font><b><i><u><span><em><div><li><ul><ol><center><blockquote>");
}

function check_domain($url) {	
	$info = parse_url($url);
	if ($info['host'] == "")
	$domain = $info['path'];
	else
	$domain = $info['host'];
	
	if (substr_count($domain, ".") == 1) {
 	$output = $domain;
	} else {
  	
	if (preg_match("#([^\.\/]*\.(co|biz|com|edu|gov|info|mil|net|org)\.(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|bb|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))#is", $domain, $output)) {
    $output = $output[1];
   	} else {
    $domain = explode(".", $domain);
    $output = $domain[count($domain)-2].".".$domain[count($domain)-1];
  	}
	}
	return $output;
}

function text_quote ($str) {
    $open = '<blockquote>';
    $close = '</blockquote>';

    // How often is the open tag?
    preg_match_all('/\[quote\]/i', $str, $matches);
    $opentags = count($matches['0']);

    // How often is the close tag?
    preg_match_all ('/\[\/quote\]/i', $str, $matches);
    $closetags = count($matches['0']);

    // Check how many tags have been unclosed
    // And add the unclosing tag at the end of the message
    $unclosed = $opentags - $closetags;
    for ($i = 0; $i < $unclosed; $i++) {
        $str .= '</blockquote>';
    }

    // Do replacement
    $str = str_replace('[' . 'quote]', $open, $str);
    $str = str_replace('[/' . 'quote]', $close, $str);

    return $str;
}

function parse_text($str) {
    $str = htmlentities($str);

    $simple_search = array(
                '/\[b\](.*?)\[\/b\]/is',                                
                '/\[i\](.*?)\[\/i\]/is',                                
                '/\[u\](.*?)\[\/u\]/is',                                
                '/\[url\=(.*?)\](.*?)\[\/url\]/is',                         
                '/\[url\](.*?)\[\/url\]/is',                             
                '/\[align\=(left|center|right)\](.*?)\[\/align\]/is',    
                '/\[img\](.*?)\[\/img\]/is',                            
                '/\[mail\=(.*?)\](.*?)\[\/mail\]/is',                    
                '/\[mail\](.*?)\[\/mail\]/is',                            
                '/\[font\=(.*?)\](.*?)\[\/font\]/is',                    
                '/\[size\=(.*?)\](.*?)\[\/size\]/is',                    
                '/\[color\=(.*?)\](.*?)\[\/color\]/is',        
                );

    $simple_replace = array(
                '<strong>$1</strong>',
                '<em>$1</em>',
                '<u>$1</u>',
                '<a href="$1">$2</a>',
                '<a href="$1">$1</a>',
                '<div style="text-align: $1;">$2</div>',
                '<img src="$1" />',
                '<a href="mailto:$1">$2</a>',
                '<a href="mailto:$1">$1</a>',
                '<span style="font-family: $1;">$2</span>',
                '<span style="font-size: $1;">$2</span>',
                '<span style="color: $1;">$2</span>',
                );

    // Do simple BBCode's
    $str = preg_replace ($simple_search, $simple_replace, $str);
    // Do <blockquote> BBCode
    $str = text_quote($str);
 
    return stripslashes(stripslashes(html_entity_decode($str)));
}

function search_box() {
global $pre;
global $siteurl;

$a .= "<form action='".$siteurl."index.php' method='get'><input type='hidden' name='view' value='search'><input type='text' name='search'><br /><br /><select name='section'><option value=''>-------</option>";
$cat = mysql_query("SELECT * FROM ".$pre."sections ORDER BY `name` ASC");
for($i = 0; $r = mysql_fetch_assoc($cat); $i++) {
$a .= "<option value='".$r[name]."'>".ucwords($r[name])."</option>";
}
$a .= "</select>&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='Search'></form>";
return $a;
}

function table($tablename) {
global $dbname;

   $result = @mysql_list_tables($dbname);
   $rcount = @mysql_num_rows($result);

   for ($i=0;$i<$rcount;$i++) {
       if (@mysql_tablename($result, $i)==$tablename) return true;
   }
   return false;
}

function header_functions() {
global $pre;
if (($_COOKIE['adaptcms_skin']) or ($_POST['skin'])) {
if ($_COOKIE['adaptcms_skin']) {
$skin = $_COOKIE['adaptcms_skin'];
}
if ($_POST['skin']) {
$skin = $_POST['skin'];
}
} else {
$skin = "skin1";
}
if ($skin == "skin1") {
$color = "#feb011";
$color2 = "#4A4A4A";
}
if ($skin == "skin2") {
$color = "#db1c1c";
$color2 = "white";
}
if ($skin == "skin3") {
$color = "#5400ff";
$color2 = "white";
}
if ($skin == "skin4") {
$color = "#176b12";
$color2 = "white";
}
if ($skin == "skin5") {
$color = "#64126b";
$color2 = "white";
}

$num1 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."articles WHERE ver = ''"));
$time1 = time() - 9001;
$time2 = time() + 1;
$time = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."users WHERE logged < ".$time2." AND logged > ".$time1));
$user = $_COOKIE[adaptcms_username];
$num1 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."articles WHERE ver = ''"));
}

function hilite($var) {
return "<font style='background-color: #FFFF00'>".$var."</font>";
}

function abclist($url, $cat) {
global $setting;
global $mrw;
global $mrw_1;

$url = str_replace(" ", "-", $url);
if (strtolower($setting["mod_rewrite"]) == "yes") {
if ($cat) {
$url .= "/letter/";
$arch = $mrw_1["section"].str_replace(" ","-",$cat)."/";
} else {
$url .= "letter/";
$arch = $mrw["archive"];
}
return "<center><a href='".$arch."'><b><u>All</u></b></a>&nbsp;&nbsp;<a href='".$url."0-9/'>#</a>&nbsp;&nbsp;<a href='".$url."A/'>A</a>&nbsp;&nbsp;<a href='".$url."B/'>B</a>&nbsp;&nbsp;<a href='".$url."C/'>C</a>&nbsp;&nbsp;<a href='".$url."D/'>D</a>&nbsp;&nbsp;<a href='".$url."E/'>E</a>&nbsp;&nbsp;<a href='".$url."F/'>F</a>&nbsp;&nbsp;<a href='".$url."G/'>G</a>&nbsp;&nbsp;<a href='".$url."H/'>H</a>&nbsp;&nbsp;<a href='".$url."I/'>I</a>&nbsp;&nbsp;<a href='".$url."J/'>J</a>&nbsp;&nbsp;<a href='".$url."K/'>K</a>&nbsp;&nbsp;<a href='".$url."L/'>L</a>&nbsp;&nbsp;<a href='".$url."M/'>M</a>&nbsp;&nbsp;<a href='".$url."N/'>N</a>&nbsp;&nbsp;<a href='".$url."O/'>O</a>&nbsp;&nbsp;<a href='".$url."P/'>P</a>&nbsp;&nbsp;<a href='".$url."Q/'>Q</a>&nbsp;&nbsp;<a href='".$url."R/'>R</a>&nbsp;&nbsp;<a href='".$url."S/'>S</a>&nbsp;&nbsp;<a href='".$url."T/'>T</a>&nbsp;&nbsp;<a href='".$url."U/'>U</a>&nbsp;&nbsp;<a href='".$url."V/'>V</a>&nbsp;&nbsp;<a href='".$url."W/'>W</a>&nbsp;&nbsp;<a href='".$url."X/'>X</a>&nbsp;&nbsp;<a href='".$url."Y/'>Y</a>&nbsp;&nbsp;<a href='".$url."Z/'>Z</a></center><br />";
} else {
$url2 = "";
return "<center><a href='".$mrw["archive"]."'><b><u>All</u></b></a>&nbsp;&nbsp;<a href='$type".$url2."abc=0-9'>#</a>&nbsp;&nbsp;<a href='$type".$url2."abc=A'>A</a>&nbsp;&nbsp;<a href='$type".$url2."abc=B'>B</a>&nbsp;&nbsp;<a href='$type".$url2."abc=C'>C</a>&nbsp;&nbsp;<a href='$type".$url2."abc=D'>D</a>&nbsp;&nbsp;<a href='$type".$url2."abc=E'>E</a>&nbsp;&nbsp;<a href='$type".$url2."abc=F'>F</a>&nbsp;&nbsp;<a href='$type".$url2."abc=G'>G</a>&nbsp;&nbsp;<a href='$type".$url2."abc=H'>H</a>&nbsp;&nbsp;<a href='$type".$url2."abc=I'>I</a>&nbsp;&nbsp;<a href='$type".$url2."abc=J'>J</a>&nbsp;&nbsp;<a href='$type".$url2."abc=K'>K</a>&nbsp;&nbsp;<a href='$type".$url2."abc=L'>L</a>&nbsp;&nbsp;<a href='$type".$url2."abc=M'>M</a>&nbsp;&nbsp;<a href='$type".$url2."abc=N'>N</a>&nbsp;&nbsp;<a href='$type".$url2."abc=O'>O</a>&nbsp;&nbsp;<a href='$type".$url2."abc=P'>P</a>&nbsp;&nbsp;<a href='$type".$url2."abc=Q'>Q</a>&nbsp;&nbsp;<a href='$type".$url2."abc=R'>R</a>&nbsp;&nbsp;<a href='$type".$url2."abc=S'>S</a>&nbsp;&nbsp;<a href='$type".$url2."abc=T'>T</a>&nbsp;&nbsp;<a href='$type".$url2."abc=U'>U</a>&nbsp;&nbsp;<a href='$type".$url2."abc=V'>V</a>&nbsp;&nbsp;<a href='$type".$url2."abc=W'>W</a>&nbsp;&nbsp;<a href='$type".$url2."abc=X'>X</a>&nbsp;&nbsp;<a href='$type".$url2."abc=Y'>Y</a>&nbsp;&nbsp;<a href='$type".$url2."abc=Z'>Z</a></center><br />";
}
}

function fthrough($var, $cat, $id) {
$var = rtrim(trim(stripslashes($var)));
$namepart = str_replace(" ", "-", $var);
$namepart = str_replace("--", "", $namepart);
$namepart = str_replace("_", "-", $namepart);
$namepart = str_replace("?", "", $namepart);
$namepart = str_replace("!", "", $namepart);
$namepart = str_replace(":", "", $namepart);
$namepart = str_replace("'", "", $namepart);
$namepart = str_replace("`", "", $namepart);
$namepart = str_replace("’", "", $namepart);
$namepart = str_replace("(", "", $namepart);
$namepart = str_replace(")", "", $namepart);
$namepart = str_replace("[", "", $namepart);
$namepart = str_replace("]", "", $namepart);
$namepart = str_replace("/", "-", $namepart);
$namepart = str_replace(",", "", $namepart);
$namepart = str_replace(".", "", $namepart);
$namepart = str_replace('"', "", $namepart);
$namepart = str_replace("'", "", $namepart);
$namepart = str_replace("—", "", $namepart);
$namepart = str_replace("@", "at", $namepart);
$namepart = str_replace("®", "", $namepart);
$namepart = str_replace("©", "", $namepart);
$namepart = str_replace("+", "plus", $namepart);
$namepart = str_replace("%", "", $namepart);
$namepart = str_replace("*", "", $namepart);
$namepart = str_replace("$", "", $namepart);
$namepart = str_replace("&", "and", $namepart);
$namepart = str_replace("#", "", $namepart);

$section = str_replace(" ", "-", ucwords(stripslashes($cat)));
$section = str_replace("--", "", $section);
$section = str_replace("_", "-", $section);
$section = str_replace(":", "", $section);
$section = str_replace("'", "", $section);
$section = str_replace("/", "-", $section);
$section = str_replace('"', "", $section);
$section = str_replace("'", "", $section);

if ($id) {
if ($cat) {
return $id."/".$section."/".$namepart."/";
} else {
return $id."/".$namepart."/";
}
} else {
return $namepart;
}
}

function show_poll($pid, $pname) {
global $pre;
global $setting;
global $siteurl;

if ($pid && $pname == "") {
$pname2 = mysql_fetch_row(@mysql_query("SELECT pname,votes,options FROM ".$pre."polls WHERE id = '".$pid."' AND type = 'poll'"));
$pname = $pname2[0];
$total = $pname2[1];
$num = $total;

$ex = explode(",", $pname2[2]);
$multi = $ex[0];
$custom = $ex[1];
} else {
$pname2 = mysql_fetch_row(@mysql_query("SELECT votes,options FROM ".$pre."polls WHERE id = '".$pid."' AND type = 'poll'"));
$total = $pname2[0];
$num = $total;

$ex = explode(",", $pname2[1]);
$multi = $ex[0];
$custom = $ex[1];
}

if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
if ($multi) {
$other_stuff .= "<input type='hidden' name='multi' value='yes'>";
}
if ($custom) {
$other_stuff .= "<input type='hidden' name='custom' value='yes'>";
}
$poll_header = "<form action='".$_SERVER['REQUEST_URI']."' method='post'><input type='hidden' name='question' value='".stripslashes(urlencode(stripslashes($pname)))."'><input type='hidden' name='pid' value='".$pid."'>".$other_stuff;
}

if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
$temp2 = array("<tr><td>{name}</td><td>{data}</td></tr>");
} else {
$temp2 = @mysql_fetch_row(@mysql_query("SELECT template FROM ".$pre."templates WHERE name = 'poll_options'"));
}
$sql = @mysql_query("SELECT * FROM ".$pre."polls WHERE pname = '".$pname."' AND type = 'option' OR pname = '".$pname."' AND type = 'custom_option' ORDER BY `id` ASC");
while($r = @mysql_fetch_array($sql)) {
$pab = "";$rab = "";

if ($num == "0") {
$num = "1";
}
@$nu = @$r[votes]/$num;

if (($num == $r[votes]) && ($r[votes] > "0")) {
$nua = "100";
} else {
if ($r[votes] == "0") {
$nua = "0";
} else {
$nua = round($nu);
}
}

if (($nu < "10") && ($nu > "0")) {
$nua = $nu * 100;
}

if (($num == $r[votes]) && ($r[votes] == "0")) {
$nua = "0";
}

if ($setting["poll_type"] == "graphic") {
if ($nua > "0") {
$img = "<img src='".$siteurl."includes/poll.jpg' width='".substr($nua,0,4)."%' height='10'>";
} else {
$img = "<img src='".$siteurl."includes/poll.jpg' width='1%' height='10'>";
}
} else {
$img = substr($nua,0,4)."%";
}

$pab[] = "{name}";
$pab[] = "{data}";
$rab[] = stripslashes($r[name]);
if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
if ($multi) {
$rab[] = "<input type='checkbox' name='answer[]' value='".stripslashes(urlencode(stripslashes($r[name])))."'>";
} else {
$rab[] = "<input type='radio' name='answer' value='".stripslashes(urlencode(stripslashes($r[name])))."'>";
}
} else {
$rab[] = substr($nua,0,4)."%<br>".$img;
}

$poll_options .= str_replace($pab, $rab, stripslashes($temp2[0]));
}

if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
if ($custom) {
if ($_COOKIE[adaptcms_username] or strtolower($setting["custom_poll_guest"]) == "yes") {
$cunum = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."polls WHERE pname = '".$pname."' AND type = 'custom_option'"));
@$diff = $setting["custom_poll_limit"] - $cunum;
if ($diff > 0) {
$ab[] = "{data}";
$ab[] = "{name}";
$oab[] = "&nbsp;";
$oab[] = "<input type='text' name='custom_answer' size='14' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'>";
$poll_options .= str_replace($ab, $oab, stripslashes($temp2[0]));
}
}
}

$temp1 = @mysql_fetch_row(@mysql_query("SELECT template FROM ".$pre."templates WHERE name = 'poll_vote'"));
} else {
$temp1 = @mysql_fetch_row(@mysql_query("SELECT template FROM ".$pre."templates WHERE name = 'poll_results'"));
}
$sab[] = "{question}";
$sab[] = "{options}";
$sab[] = "{submit}";
$sab[] = "{vote_total}";

$tab[] = stripslashes($pname);
$tab[] = $poll_options;
if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
$tab[] = "<input type='submit' value='Vote'>";
} else {
$tab[] = "";
}
$tab[] = $total;

if ($_SESSION["poll_".$pid] == "" && $_GET['results'] == "") {
return $poll_header.str_replace($sab, $tab, stripslashes($temp1[0]))."</form>";
} else {
return $poll_header.str_replace($sab, $tab, stripslashes($temp1[0]));
}
}

function content($temp, $cat, $limit, $sort, $sortby, $field = NULL, $dataf = NULL) {
global $pre;
global $mrw_1;
global $mrw;
global $lev;
global $setting;
global $siteurl;


if ($field or $dataf) {
$field = str_replace("_", " ", str_replace("-"," ", stripslashes(htmlspecialchars(check($field)))));
$dataf = str_replace("_", " ", str_replace("-"," ", stripslashes(htmlspecialchars(check($dataf)))));
$ex = explode(",", $dataf);

if (mysql_num_rows(mysql_query("SELECT * FROM ".$pre."sections WHERE name = '".$field."'")) == 0) {
while (list($k,$i) = each($ex)) {
if ($k == 0) {
} else {
$fddata .= " OR";
}
$fddata .= " fname = '".$field."' AND data LIKE '%". $i ."%'";
}
} else {
while (list($k,$i) = each($ex)) {
$gid = mysql_fetch_row(mysql_query("SELECT id FROM ".$pre."articles WHERE section = '".$field."' AND name LIKE '%" . addslashes($i) . "%' AND ver = ''"));
if ($k == 0) {
} else {
$fddata .= " OR";
}
$fddata .= " fname = '".$field."' AND data LIKE '%". $gid[0] ."%'";
}
unset($gid);
}
}

if ($limit == "") {
$limit = "5";
}
if ($sort == "") {
$sort = "`id`";
} else {
if ($sort == "RAND()") {
$sort = "RAND()";
} else {
$sort = "`".$sort."`";
}
}
if ($sortby == "") {
$sortby = "DESC";
}

if ($field or $dataf) {
$sql = mysql_query("SELECT * FROM ".$pre."fielddata WHERE".$fddata." ORDER BY `id` DESC LIMIT ".$limit);
} else {
if ($cat) {
$catss = explode(",", $cat);
while (list($i, $mb) = each ($catss)) {
if ($i == 0) {
} else {
$cats .= " OR";
}
$cats .= " section = '".$mb."' AND ver = ''";
}
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE".$cats." AND ver = '' ORDER BY ".$sort." ".$sortby." LIMIT ".$limit);
} else {
$sql = mysql_query("SELECT * FROM ".$pre."articles WHERE ver = '' ORDER BY ".$sort." ".$sortby." LIMIT ".$limit);
}
}
while($r = mysql_fetch_array($sql)) {
unset($data, $datas, $pab, $rab, $name1, $link1, $n, $m, $y, $x, $i, $id, $name, $relations_id, $relations_sec, $s, $fetch, $get, $dats, $fname, $lid, $lids, $b, $sqlst, $k, $data23, $check);

if ($field or $dataf) {
$get = mysql_fetch_row(mysql_query("SELECT section,id,username,name,views,date FROM ".$pre."articles WHERE id = '".$r[aid]."'"));
$r[section] = $get[0];
$r[id] = $get[1];
$r[username] = $get[2];
$r[name] = $get[3];
$r[views] = $get[4];
$r[date] = $get[5];
}

if (!$cat && $r[name] or $cat && $fddata && $cat == $r[section] && $r[name] or $cat && !$fddata && $r[name]) {
$s = @mysql_query("SELECT * FROM ".$pre."fields WHERE type = 'textarea' AND cat = '".$r[section]."' ORDER BY `id` ASC LIMIT 1");
while($x = @mysql_fetch_array($s)) {
$fetch = @mysql_fetch_row(@mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$x[name]."' AND aid = '".$r[id]."'"));
if ($fetch[0]) {
$datas[] = stripslashes($fetch[0]);
}
}
if ($datas) {
@asort($datas);
while (list($k,$i) = @each($datas)) {
if ($i) {
$data = $i;
}
}
} else {
$data = "No Description";
}

$cnum2 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."comments WHERE aid = '".$r[id]."'"));

$pab[0] = "{link}";
$pab[1] = "{date}";
$pab[2] = "{story}";
$pab[3] = "{comments}";
$pab[4] = "{cnum}";
$pab[5] = "{pcomment}";
$pab[6] = "{author}";
$pab[7] = "{section}";
$pab[8] = "{cat}";
$pab[9] = "{url}";
$pab[10] = "{title}";
$pab[11] = "{subject}";
$pab[12] = "{name}";
$pab[13] = "{username}";
$pab[14] = "{id}";
$pab[15] = "{views}";
$pab[16] = "{votes}";
$pab[17] = "{social_icons}";

$pab[18] = "{".$r[section]."_link}";
$pab[19] = "{".$r[section]."_date}";
$pab[20] = "{".$r[section]."_story}";
$pab[21] = "{".$r[section]."_comments}";
$pab[22] = "{".$r[section]."_cnum}";
$pab[23] = "{".$r[section]."_pcomment}";
$pab[24] = "{".$r[section]."_author}";
$pab[25] = "{".$r[section]."_section}";
$pab[26] = "{".$r[section]."_cat}";
$pab[27] = "{".$r[section]."_url}";
$pab[28] = "{".$r[section]."_title}";
$pab[29] = "{".$r[section]."_subject}";
$pab[30] = "{".$r[section]."_name}";
$pab[31] = "{".$r[section]."_username}";
$pab[32] = "{".$r[section]."_id}";
$pab[33] = "{".$r[section]."_views}";
$pab[34] = "{".$r[section]."_votes}";
$pab[35] = "{".$r[section]."_social_icons}";

$rab[0] .= "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."'>".stripslashes($r[name])."</a>";
if ($lev == 1 or $lev == 2 && $r[username] == $_COOKIE[adaptcms_username] && 1 == 2) {
$rab[0] .= "&nbsp;&nbsp;<a href='".$siteurl."admin.php?view=edit_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/edit.gif' border='0'></a>&nbsp;<a href='".$siteurl."admin.php?view=delete_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/delete.gif' border='0'></a>";
}
$rab[1] = date($setting["date_format"], $r[date]);
$rab[2] = stripslashes(html_entity_decode(stripslashes($data)));
$rab[3] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Comments</a>";
$rab[4] = $cnum2;
$rab[5] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Post a Comment</a>";
$rab[6] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[7] = $r[section];
$rab[8] = $r[section];
$rab[9] = $mrw_1["content"].fthrough($r[name], $r[section], $r[id]);
$rab[10] = stripslashes($r[name]);
$rab[11] = stripslashes($r[name]);
$rab[12] = stripslashes($r[name]);
$rab[13] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[14] = $r[id];
$rab[15] = stripslashes($r[views]);
$rab[16] = $r[rate];
$rab[17] = soc_bookmark($mrw_1["content"].fthrough($r[name], $r[cat], $r[id]), $r[name], "", $data, 'Y');

$rab[18] .= "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."'>".stripslashes($r[name])."</a>";
if ($lev == 1 or $lev == 2 && $r[username] == $_COOKIE[adaptcms_username] && 1 == 2) {
$rab[18] .= "&nbsp;&nbsp;<a href='".$siteurl."admin.php?view=edit_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/edit.gif' border='0'></a>&nbsp;<a href='".$siteurl."admin.php?view=delete_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/delete.gif' border='0'></a>";
}
$rab[19] = date($setting["date_format"], $r[date]);
$rab[20] = stripslashes(html_entity_decode(stripslashes($data)));
$rab[21] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Comments</a>";
$rab[22] = $cnum2;
$rab[23] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Post a Comment</a>";
$rab[24] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[25] = $r[section];
$rab[26] = $r[section];
$rab[27] = $mrw_1["content"].fthrough($r[name], $r[section], $r[id]);
$rab[28] = stripslashes($r[name]);
$rab[29] = stripslashes($r[name]);
$rab[30] = stripslashes($r[name]);
$rab[31] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[32] = $r[id];
$rab[33] = stripslashes($r[views]);
$rab[34] = $r[rate];
$rab[35] = soc_bookmark($mrw_1["content"].fthrough($r[name], $r[cat], $r[id]), $r[name], "", $data, 'Y');

$m = 35;
$n = 35;

// start - custom fields
$name = "";$data = "";$row = "";
$sql_cf = mysql_query("SELECT * FROM ".$pre."fields WHERE cat = '".$r[section]."' OR cat = 'user-profile'");
while ($row = mysql_fetch_array($sql_cf)) {
$name = "$row[name]";

$data = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$r[id]."'"));
$fdata[$name] = $data[0];

if ($data[0]) {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data[0]);
$m = $m + 1;
$rab[$m] = parse_text($data[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data[0]));
$m = $m + 1;
$rab[$m] = stripslashes(html_entity_decode($data[0]));
}
} else {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
}
}
// end - custom fields

// start - go through related sections...find similar item, if so then puts section and appropiate ID number in array
$name = "";
$sec_type = mysql_fetch_row(mysql_query("SELECT type FROM ".$pre."sections WHERE name = '".$r[section]."'"));
$type = $sec_type[0];
if ($type) {
$sql_rel = mysql_query("SELECT * FROM ".$pre."relations WHERE ".$type." = '".addslashes($r[section])."'");
while ($rel = mysql_fetch_array($sql_rel)) {
if ($type == "section") {
$name = $rel[sub];
} else {
$name = $rel[section];
}
$relations_sec[] = $name;

$check = mysql_fetch_row(mysql_query("SELECT id FROM ".$pre."articles WHERE section = '".$name."' AND name LIKE '%" . addslashes($r[name]) . "%' AND ver = ''"));

$sqlst = mysql_query("SELECT * FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$r[id]."' ORDER BY `id` DESC");
while ($sr = mysql_fetch_array($sqlst)) {
if (preg_match("/".$sr[data]."/", $data23) == 0) {
$relations_id[$name][] = $sr[data];
$data23 .= $sr[data].",";
}
}

if ($check[0] && preg_match("/".$check[0]."/", $data23) == 0) {
$relations_id[$name][] = $check[0];
}
}
}
// end - go through related sections

$cn = "0";
if (count($relations_id) == 1) {
$dats = "yes";
while (list($idy,$x) = @each($relations_id)) {
$cn = $cn + 1;
if ($cn == 1) {
$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
if ($idy == $q[name]) {
} else {
$relations_sec[] = $q[name];
$rel_sec[] = $sr[fname];
$lid = $x[0];
$lids = $idy;

$fname .= " aid = '".$x[0]."' AND fname = '".$q[name]."' OR";
}
}
}
//echo $fname;
}
if ($fname) {
$sqlst = mysql_query("SELECT * FROM ".$pre."fielddata WHERE ".substr($fname,0,-3));
while ($sr = mysql_fetch_array($sqlst)) {
$ids = $sr[fname];
if ($sr[fname] == $idy) {
} else {
if (preg_match("/".$sr[fname].$sr[data]."/", $lst)) {
} else {
$relations_id[$ids][] = $sr[data];
$lst .= $sr[fname].$sr[data];
}
}
}
}
}
}

$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
$cat = $q[name];
$k = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$q[name]."' AND aid = '".$r[id]."'"));
if ($dats == "yes") {
if ($lids == $q[name]) {
$sqlst = array("a");
} else {
$sqlst = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$q[name]."' AND aid = '".$lid."'"));
}
}
if ($sqlst[0] == "" && $dats == "yes" or $k[0] == "" && $dats == "") {
$b[] = $cat;
$n = $n + 1;
$pab[$n] = "{".$q[name]."_name}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_subject}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_title}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_link}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_url}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_date}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_username}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_cat}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_category}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_section}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_views}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_form}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_text}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_img}";
$n = $n + 1;
$pab[$n] = "{".$q[name].";";
$n = $n + 1;
$pab[$n] = ";".$q[name]."}";

$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
}
}
}

// start - custom fields for related section(s)
while (list($k,$i) = @each($relations_sec)) {
$name = "";$data = "";$row = "";$sql_cf = "";$cn = "0";$fname = "";
if ($dats == "yes" && $relations_id[$i][0]) {
$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
if ($i == $q[name]) {
} else {
$cn = $cn + 1;
if (!$blacks) {
$fname .= " aid = '".$relations_id[$i][0]."' AND fname = '".$q[name]."'";
} else {
$fname .= " OR aid = '".$relations_id[$i][0]."' AND fname = '".$q[name]."'";
}
$blacks = 1;
}
}
}

}

$sql_cf = mysql_query("SELECT * FROM ".$pre."fields WHERE cat = '".$i."'");
while ($row = mysql_fetch_array($sql_cf)) {
$name = "$row[name]";

$data = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$relations_id[$i][0]."' ORDER BY `id` ASC"));
if ($dats == "yes") {
$data2 = @mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE ".substr($fname,0,-3)));
//echo substr($fname,0,-3)."|||".$data[0];
}

if ($data[0]) {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data[0]));
}
} else {
if (($data2[0]) && ($dats == "yes")) {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data2[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data2[0]));
}
} else {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
$rab[$m] = "";
}
}
}

$name1 = "";$link1 = "";
if (count($relations_id[$i]) > 0) {
while (list($idy,$x) = each($relations_id[$i])) {
$y = mysql_fetch_row(mysql_query("SELECT name,date,username,views,rate FROM ".$pre."articles WHERE id = '".$x."' AND ver = ''"));
$y[0] = stripslashes($y[0]);

if (count($relations_id[$i]) > 1) {
if ($idy == 0) {
$name1 .= template("related_articlelist_start", "");
$link1 .= template("related_articlelist_start", "");
}
$name1 .= template("related_articlelist_entry", $y[0]);
$link1 .= template("related_articlelist_entry", "<a href='".$mrw_1["content"].fthrough($y[0], $i, $x)."'>".stripslashes($y[0])."</a>");

$idt = $idy + 1;
if (count($relations_id[$i]) == $idt) {
$name1 .= template("related_articlelist_end", "");
$link1 .= template("related_articlelist_end", "");
}
} else {
$name1 = stripslashes($y[0]);
$link1 = "<a href='".$mrw_1["content"].fthrough($y[0], $i, $x)."'>".stripslashes($y[0])."</a>";
}
$id = $x;
}

$rating_img = "";$rate = "";$user_rate_form = "";
if ($y[4] == "0|0") {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'>";
$rate = 0;
} else {
$rx = explode("|", $y[4]);
@$rate = $rx[1] / $rx[0];
$rate = round(substr($rate, 0, 3));
for ($kl = 1; $kl <= $rate; $kl++) {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/star.png'>";
}
$val = 5 - $rate;
if ($val > "0") {
for ($kl = 1; $kl <= $val; $kl++) {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/starno.png'>";
}
}
}
$user_rate_form = "<form action='".$_SERVER['REQUEST_URI']."' method='post'><b>Vote for Article:</b> <select name='rating' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select> <input type='submit' value='Go' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444'><input type='hidden' name='cur_rating' value='".$y[4]."'><input type='hidden' name='aid' value='".$relations_id[$i]."'></form>";
if ($id) {
$n = $n + 1;
$pab[$n] = "{".$i."_name}";
$n = $n + 1;
$pab[$n] = "{".$i."_subject}";
$n = $n + 1;
$pab[$n] = "{".$i."_title}";
$n = $n + 1;
$pab[$n] = "{".$i."_link}";
$n = $n + 1;
$pab[$n] = "{".$i."_url}";
$n = $n + 1;
$pab[$n] = "{".$i."_date}";
$n = $n + 1;
$pab[$n] = "{".$i."_username}";
$n = $n + 1;
$pab[$n] = "{".$i."_cat}";
$n = $n + 1;
$pab[$n] = "{".$i."_category}";
$n = $n + 1;
$pab[$n] = "{".$i."_section}";
$n = $n + 1;
$pab[$n] = "{".$i."_views}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_form}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_text}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_img}";
$n = $n + 1;
$pab[$n] = "{".$i.";";
$n = $n + 1;
$pab[$n] = ";".$i."}";

$m = $m + 1;
$rab[$m] = $name1;
$m = $m + 1;
$rab[$m] = $name1;
$m = $m + 1;
$rab[$m] = $y[0];
$m = $m + 1;
$rab[$m] = $link1;
$m = $m + 1;
$rab[$m] = $mrw_1["content"].fthrough($y[0], $i, $id);
$m = $m + 1;
$rab[$m] = date($setting["date_format"], $y[1]);
$m = $m + 1;
$rab[$m] = $y[2];
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $y[3];
$m = $m + 1;
$rab[$m] = $user_rate_form;
$m = $m + 1;
$rab[$m] = $rate;
$m = $m + 1;
$rab[$m] = $rating_img;
$m = $m + 1;
$rab[$m] = "<a href='".$mrw_1["content"].fthrough($y[0], $i, $id)."'>";
$m = $m + 1;
$rab[$m] = "</a>";
}
}
}

// end - custom fields for related section(s)

$content .= str_replace($pab, $rab, stripslashes($temp));
$data = "";$datas = "";
}
}
return $content;
}

function user_content($temp, $cat, $limit, $sort, $sortby, $user) {
global $pre;
global $mrw_1;
global $mrw;
global $lev;
global $setting;
global $siteurl;

if ($limit == "") {
$limit = "5";
}
if ($sort == "") {
$sort = "`id`";
} else {
if ($sort == "RAND()") {
$sort = "RAND()";
} else {
$sort = "`".$sort."`";
}
}
if ($sortby == "") {
$sortby = "DESC";
}

if ($cat) {
$catss = explode(",", $cat);
while (list($i, $mb) = each ($catss)) {
if ($i == 0) {
} else {
$cats .= " OR";
}
$cats .= " section = '".$mb."' AND ver = ''";
}
$sql = @mysql_query("SELECT * FROM ".$pre."articles WHERE".$cats." AND ver = '' AND username = '".$user."' ORDER BY ".$sort." ".$sortby." LIMIT ".$limit);
} else {
$sql = @mysql_query("SELECT * FROM ".$pre."articles WHERE username = '".$user."' AND ver = '' ORDER BY ".$sort." ".$sortby." LIMIT ".$limit);
}
while($r = @mysql_fetch_array($sql)) {
unset($data, $datas, $pab, $rab, $name1, $link1, $n, $m, $y, $x, $i, $id, $name, $relations_id, $relations_sec, $s, $fetch, $get, $dats, $fname, $lid, $lids, $b, $sqlst, $k, $data23, $check);


$s = @mysql_query("SELECT * FROM ".$pre."fields WHERE type = 'textarea' AND cat = '".$r[section]."' ORDER BY `id` ASC LIMIT 1");
while($x = @mysql_fetch_array($s)) {
$fetch = @mysql_fetch_row(@mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$x[name]."' AND aid = '".$r[id]."'"));
if ($fetch[0]) {
$datas[] = stripslashes($fetch[0]);
}
}
if ($datas) {
@asort($datas);
while (list($k,$i) = @each($datas)) {
if ($i) {
$data = $i;
}
}
} else {
$data = "No Description";
}

$cnum2 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."comments WHERE aid = '".$r[id]."'"));

$pab[0] = "{link}";
$pab[1] = "{date}";
$pab[2] = "{story}";
$pab[3] = "{comments}";
$pab[4] = "{cnum}";
$pab[5] = "{pcomment}";
$pab[6] = "{author}";
$pab[7] = "{section}";
$pab[8] = "{cat}";
$pab[9] = "{url}";
$pab[10] = "{title}";
$pab[11] = "{subject}";
$pab[12] = "{name}";
$pab[13] = "{username}";
$pab[14] = "{id}";
$pab[15] = "{views}";
$pab[16] = "{votes}";
$pab[17] = "{social_icons}";

$pab[18] = "{".$r[section]."_link}";
$pab[19] = "{".$r[section]."_date}";
$pab[20] = "{".$r[section]."_story}";
$pab[21] = "{".$r[section]."_comments}";
$pab[22] = "{".$r[section]."_cnum}";
$pab[23] = "{".$r[section]."_pcomment}";
$pab[24] = "{".$r[section]."_author}";
$pab[25] = "{".$r[section]."_section}";
$pab[26] = "{".$r[section]."_cat}";
$pab[27] = "{".$r[section]."_url}";
$pab[28] = "{".$r[section]."_title}";
$pab[29] = "{".$r[section]."_subject}";
$pab[30] = "{".$r[section]."_name}";
$pab[31] = "{".$r[section]."_username}";
$pab[32] = "{".$r[section]."_id}";
$pab[33] = "{".$r[section]."_views}";
$pab[34] = "{".$r[section]."_votes}";
$pab[35] = "{".$r[section]."_social_icons}";

$rab[0] .= "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."'>".stripslashes($r[name])."</a>";
if ($lev == 1 or $lev == 2 && $r[username] == $_COOKIE[adaptcms_username] && 1 == 2) {
$rab[0] .= "&nbsp;&nbsp;<a href='".$siteurl."admin.php?view=edit_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/edit.gif' border='0'></a>&nbsp;<a href='".$siteurl."admin.php?view=delete_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/delete.gif' border='0'></a>";
}
$rab[1] = date($setting["date_format"], $r[date]);
$rab[2] = stripslashes(html_entity_decode(stripslashes($data)));
$rab[3] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Comments</a>";
$rab[4] = $cnum2;
$rab[5] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Post a Comment</a>";
$rab[6] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[7] = $r[section];
$rab[8] = $r[section];
$rab[9] = $mrw_1["content"].fthrough($r[name], $r[section], $r[id]);
$rab[10] = stripslashes($r[name]);
$rab[11] = stripslashes($r[name]);
$rab[12] = stripslashes($r[name]);
$rab[13] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[14] = $r[id];
$rab[15] = stripslashes($r[views]);
$rab[16] = $r[rate];
$rab[17] = soc_bookmark($mrw_1["content"].fthrough($r[name], $r[cat], $r[id]), $r[name], "", $data, 'Y');

$rab[18] .= "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."'>".stripslashes($r[name])."</a>";
if ($lev == 1 or $lev == 2 && $r[username] == $_COOKIE[adaptcms_username] && 1 == 2) {
$rab[18] .= "&nbsp;&nbsp;<a href='".$siteurl."admin.php?view=edit_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/edit.gif' border='0'></a>&nbsp;<a href='".$siteurl."admin.php?view=delete_article&id=".$r[id]."&cat=".$r[section]."'><img src='".$siteurl."includes/delete.gif' border='0'></a>";
}
$rab[19] = date($setting["date_format"], $r[date]);
$rab[20] = stripslashes(html_entity_decode(stripslashes($data)));
$rab[21] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Comments</a>";
$rab[22] = $cnum2;
$rab[23] = "<a href='".$mrw_1["content"].fthrough($r[name], $r[section], $r[id])."#comments'>Post a Comment</a>";
$rab[24] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[25] = $r[section];
$rab[26] = $r[section];
$rab[27] = $mrw_1["content"].fthrough($r[name], $r[section], $r[id]);
$rab[28] = stripslashes($r[name]);
$rab[29] = stripslashes($r[name]);
$rab[30] = stripslashes($r[name]);
$rab[31] = "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'>".$r[username]."</a>";
$rab[32] = $r[id];
$rab[33] = stripslashes($r[views]);
$rab[34] = $r[rate];
$rab[35] = soc_bookmark($mrw_1["content"].fthrough($r[name], $r[cat], $r[id]), $r[name], "", $data, 'Y');

$m = 35;
$n = 35;

// start - custom fields
$name = "";$data = "";$row = "";
$sql_cf = mysql_query("SELECT * FROM ".$pre."fields WHERE cat = '".$r[section]."' OR cat = 'user-profile'");
while ($row = mysql_fetch_array($sql_cf)) {
$name = "$row[name]";

$data = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$r[id]."'"));
$fdata[$name] = $data[0];

if ($data[0]) {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data[0]);
$m = $m + 1;
$rab[$m] = parse_text($data[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data[0]));
$m = $m + 1;
$rab[$m] = stripslashes(html_entity_decode($data[0]));
}
} else {
$n = $n + 1;
$pab[$n] = "{".$name."}";
$n = $n + 1;
$pab[$n] = "{".$r[section]."_".$name."}";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
}
}
// end - custom fields

// start - go through related sections...find similar item, if so then puts section and appropiate ID number in array
$name = "";
$sec_type = mysql_fetch_row(mysql_query("SELECT type FROM ".$pre."sections WHERE name = '".$r[section]."'"));
$type = $sec_type[0];
if ($type) {
$sql_rel = mysql_query("SELECT * FROM ".$pre."relations WHERE ".$type." = '".addslashes($r[section])."'");
while ($rel = mysql_fetch_array($sql_rel)) {
if ($type == "section") {
$name = $rel[sub];
} else {
$name = $rel[section];
}
$relations_sec[] = $name;

$check = mysql_fetch_row(mysql_query("SELECT id FROM ".$pre."articles WHERE section = '".$name."' AND name LIKE '%" . addslashes($r[name]) . "%' AND ver = ''"));

$sqlst = mysql_query("SELECT * FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$r[id]."' ORDER BY `id` DESC");
while ($sr = mysql_fetch_array($sqlst)) {
if (preg_match("/".$sr[data]."/", $data23) == 0) {
$relations_id[$name][] = $sr[data];
$data23 .= $sr[data].",";
}
}

if ($check[0] && preg_match("/".$check[0]."/", $data23) == 0) {
$relations_id[$name][] = $check[0];
}
}
}
// end - go through related sections

$cn = "0";
if (count($relations_id) == 1) {
$dats = "yes";
while (list($idy,$x) = @each($relations_id)) {
$cn = $cn + 1;
if ($cn == 1) {
$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
if ($idy == $q[name]) {
} else {
$relations_sec[] = $q[name];
$rel_sec[] = $sr[fname];
$lid = $x[0];
$lids = $idy;

$fname .= " aid = '".$x[0]."' AND fname = '".$q[name]."' OR";
}
}
}
//echo $fname;
}
if ($fname) {
$sqlst = mysql_query("SELECT * FROM ".$pre."fielddata WHERE ".substr($fname,0,-3));
while ($sr = mysql_fetch_array($sqlst)) {
$ids = $sr[fname];
if ($sr[fname] == $idy) {
} else {
if (preg_match("/".$sr[fname].$sr[data]."/", $lst)) {
} else {
$relations_id[$ids][] = $sr[data];
$lst .= $sr[fname].$sr[data];
}
}
}
}
}
}

$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
$cat = $q[name];
$k = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$q[name]."' AND aid = '".$r[id]."'"));
if ($dats == "yes") {
if ($lids == $q[name]) {
$sqlst = array("a");
} else {
$sqlst = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$q[name]."' AND aid = '".$lid."'"));
}
}
if ($sqlst[0] == "" && $dats == "yes" or $k[0] == "" && $dats == "") {
$b[] = $cat;
$n = $n + 1;
$pab[$n] = "{".$q[name]."_name}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_subject}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_title}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_link}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_url}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_date}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_username}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_cat}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_category}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_section}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_views}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_form}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_text}";
$n = $n + 1;
$pab[$n] = "{".$q[name]."_user_rate_img}";
$n = $n + 1;
$pab[$n] = "{".$q[name].";";
$n = $n + 1;
$pab[$n] = ";".$q[name]."}";

$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
$m = $m + 1;
$rab[$m] = "";
}
}
}

// start - custom fields for related section(s)
while (list($k,$i) = @each($relations_sec)) {
$name = "";$data = "";$row = "";$sql_cf = "";$cn = "0";$fname = "";
if ($dats == "yes" && $relations_id[$i][0]) {
$sql_rels = mysql_query("SELECT * FROM ".$pre."sections");
while ($q = mysql_fetch_array($sql_rels)) {
if ($r[section] == $q[name]) {
} else {
if ($i == $q[name]) {
} else {
$cn = $cn + 1;
if (!$blacks) {
$fname .= " aid = '".$relations_id[$i][0]."' AND fname = '".$q[name]."'";
} else {
$fname .= " OR aid = '".$relations_id[$i][0]."' AND fname = '".$q[name]."'";
}
$blacks = 1;
}
}
}

}

$sql_cf = mysql_query("SELECT * FROM ".$pre."fields WHERE cat = '".$i."'");
while ($row = mysql_fetch_array($sql_cf)) {
$name = "$row[name]";

$data = mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE fname = '".$name."' AND aid = '".$relations_id[$i][0]."' ORDER BY `id` ASC"));
if ($dats == "yes") {
$data2 = @mysql_fetch_row(mysql_query("SELECT data FROM ".$pre."fielddata WHERE ".substr($fname,0,-3)));
//echo substr($fname,0,-3)."|||".$data[0];
}

if ($data[0]) {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data[0]));
}
} else {
if (($data2[0]) && ($dats == "yes")) {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
if ($row[type] == "textarea") {
$rab[$m] = parse_text($data2[0]);
} else {
$rab[$m] = stripslashes(html_entity_decode($data2[0]));
}
} else {
$n = $n + 1;
$pab[$n] = "{".$i."_".$name."}";
$m = $m + 1;
$rab[$m] = "";
}
}
}

$name1 = "";$link1 = "";
if (count($relations_id[$i]) > 0) {
while (list($idy,$x) = each($relations_id[$i])) {
$y = mysql_fetch_row(mysql_query("SELECT name,date,username,views,rate FROM ".$pre."articles WHERE id = '".$x."' AND ver = ''"));
$y[0] = stripslashes($y[0]);

if (count($relations_id[$i]) > 1) {
if ($idy == 0) {
$name1 .= template("related_articlelist_start", "");
$link1 .= template("related_articlelist_start", "");
}
$name1 .= template("related_articlelist_entry", $y[0]);
$link1 .= template("related_articlelist_entry", "<a href='".$mrw_1["content"].fthrough($y[0], $i, $x)."'>".stripslashes($y[0])."</a>");

$idt = $idy + 1;
if (count($relations_id[$i]) == $idt) {
$name1 .= template("related_articlelist_end", "");
$link1 .= template("related_articlelist_end", "");
}
} else {
$name1 = stripslashes($y[0]);
$link1 = "<a href='".$mrw_1["content"].fthrough($y[0], $i, $x)."'>".stripslashes($y[0])."</a>";
}
$id = $x;
}

$rating_img = "";$rate = "";$user_rate_form = "";
if ($y[4] == "0|0") {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'><img src='".$siteurl."skins/".$skin."/starno.png'>";
$rate = 0;
} else {
$rx = explode("|", $y[4]);
@$rate = $rx[1] / $rx[0];
$rate = round(substr($rate, 0, 3));
for ($kl = 1; $kl <= $rate; $kl++) {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/star.png'>";
}
$val = 5 - $rate;
if ($val > "0") {
for ($kl = 1; $kl <= $val; $kl++) {
$rating_img .= "<img src='".$siteurl."skins/".$skin."/starno.png'>";
}
}
}
$user_rate_form = "<form action='".$_SERVER['REQUEST_URI']."' method='post'><b>Vote for Article:</b> <select name='rating' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select> <input type='submit' value='Go' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444'><input type='hidden' name='cur_rating' value='".$y[4]."'><input type='hidden' name='aid' value='".$relations_id[$i]."'></form>";
if ($id) {
$n = $n + 1;
$pab[$n] = "{".$i."_name}";
$n = $n + 1;
$pab[$n] = "{".$i."_subject}";
$n = $n + 1;
$pab[$n] = "{".$i."_title}";
$n = $n + 1;
$pab[$n] = "{".$i."_link}";
$n = $n + 1;
$pab[$n] = "{".$i."_url}";
$n = $n + 1;
$pab[$n] = "{".$i."_date}";
$n = $n + 1;
$pab[$n] = "{".$i."_username}";
$n = $n + 1;
$pab[$n] = "{".$i."_cat}";
$n = $n + 1;
$pab[$n] = "{".$i."_category}";
$n = $n + 1;
$pab[$n] = "{".$i."_section}";
$n = $n + 1;
$pab[$n] = "{".$i."_views}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_form}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_text}";
$n = $n + 1;
$pab[$n] = "{".$i."_user_rate_img}";
$n = $n + 1;
$pab[$n] = "{".$i.";";
$n = $n + 1;
$pab[$n] = ";".$i."}";

$m = $m + 1;
$rab[$m] = $name1;
$m = $m + 1;
$rab[$m] = $name1;
$m = $m + 1;
$rab[$m] = $y[0];
$m = $m + 1;
$rab[$m] = $link1;
$m = $m + 1;
$rab[$m] = $mrw_1["content"].fthrough($y[0], $i, $id);
$m = $m + 1;
$rab[$m] = date($setting["date_format"], $y[1]);
$m = $m + 1;
$rab[$m] = $y[2];
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $i;
$m = $m + 1;
$rab[$m] = $y[3];
$m = $m + 1;
$rab[$m] = $user_rate_form;
$m = $m + 1;
$rab[$m] = $rate;
$m = $m + 1;
$rab[$m] = $rating_img;
$m = $m + 1;
$rab[$m] = "<a href='".$mrw_1["content"].fthrough($y[0], $i, $id)."'>";
$m = $m + 1;
$rab[$m] = "</a>";
}
}
}

// end - custom fields for related section(s)

$content .= str_replace($pab, $rab, stripslashes($temp));
$data = "";$datas = "";
}
return $content;
}

function template($name, $data) {
global $pre;

$r = mysql_fetch_row(mysql_query("SELECT template FROM ".$pre."templates WHERE name = '".$name."'"));
return str_replace("{name}", $data, $r[0]);
}

function layout($layout) {
global $pre;
global $setting;
global $lev;
global $mrw_1;
global $mrw;

$r = mysql_fetch_row(mysql_query("SELECT template FROM ".$pre."templates WHERE name = 'layout'"));
$ex = explode("{content}", stripslashes($r[0]));

$prep[0] = "{pages}";
$prep[1] = "{categories}";
$prep[2] = "{sections}";

$sql2 = mysql_query("SELECT * FROM ".$pre."pages ORDER BY `name` ASC");
while($c = @mysql_fetch_array($sql2)) {
$rep[0] .= "<br /><a href='".$mrw_1["page"].stripslashes($c[url])."'>".stripslashes($c[name])."</a>";
}
$sql1 = mysql_query("SELECT * FROM ".$pre."sections ORDER BY `name` ASC");
while($a = @mysql_fetch_array($sql1)) {
$rep[1] .= "<br /><a href='".$mrw_1["section"].fthrough($a[name], "", "")."'>".$a[name]."</a>";
$rep[2] .= "<br /><a href='".$mrw_1["section"].fthrough($a[name], "", "")."'>".$a[name]."</a>";
}

$var1 = str_replace($prep, $rep, $ex[0]);
$var2 = str_replace($prep, $rep, $ex[1]);

if ($layout == "header") {
return '<?php if (($_COOKIE[\'adaptcms_skin\']) or ($_POST[\'skin\'])) {
if ($_COOKIE[\'adaptcms_skin\']) {
$skin = $_COOKIE[\'adaptcms_skin\'];
}
if ($_POST[\'skin\']) {
$skin = $_POST[\'skin\'];
}
} else {
$skin = "skin1";
}
if ($skin == "skin1") {
$color = "#feb011";
$color2 = "#4A4A4A";
}
if ($skin == "skin2") {
$color = "#db1c1c";
$color2 = "white";
}
if ($skin == "skin3") {
$color = "#5400ff";
$color2 = "white";
}
if ($skin == "skin4") {
$color = "#176b12";
$color2 = "white";
}
if ($skin == "skin5") {
$color = "#64126b";
$color2 = "white";
}

$num1 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."articles AND ver = \'\'"));
$time1 = time() - 9001;
$time2 = time() + 1;
$time = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."users WHERE logged < ".$time2." AND logged > ".$time1));
$user = $_COOKIE[adaptcms_username];
$num1 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."articles WHERE ver = \'\'"));?>'.$var1;
} else {
return $var2;
}
}

function RemoveXSS($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
   
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
   
      // &#x0040 @ search for the hex values
      $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // &#00064 @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   
   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
               $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
               $pattern .= ')?';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
}

function reporterror($page, $error, $domain) {
global $email;
global $setting;

$sub = "[AdaptCMS] Error Reported";
$msg = "The error has been repoted from the ".$domain." website, below is the information on the error\n\nPage: ".$page."\nError: ".$error."\n\nThe error has also been reported to the error database. Thank you.";
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$setting["sitename"]." <".$email.">"."\r\n";
$headers .= "Reply-To: ".$email."\r\n";

@mail("errors@adaptcms.com", $sub, $msg, $headers);
return "<iframe src='http://www.adaptcms.com/error.php?domain=".$domain."&error=".urlencode($error)."&page=".$page."' width='0' height='0' frameborder='0'></iframe>";
}

function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        return "mail send ... OK"; // or use booleans here
    } else {
        return "mail send ... ERROR!";
    }
} 

function pointcount($user) {
global $pre;
global $regdate;

$math1 = time() - $regdate;
$math2 = $math1 / 86400;

if ($user == "") {
$username = $_COOKIE[adaptcms_username];
} else {
$username = $user;
}

$num1 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."articles WHERE username = '".$username."' AND ver = ''"));
$count2 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."comments WHERE author = '".$username."'"));
$num3 = mysql_num_rows(mysql_query("SELECT * FROM ".$pre."stats WHERE username = '".$username."'"));

$count1 = $num1 * 3;
$count3 = $num3 * .1;
if ($math2 < 8) {
$count4 = $math2 * 5;
} else {
$count4 = $math2 * .5;
}

$final = $count1 + $count2 + $count3 + $count4;

$final = round($final,0);
return substr($final,0,3);
}

function myquery ($query) {
$result = mysql_query($query);
if (mysql_errno())
echo "<b>MySQL error</b> ".mysql_errno().": ".mysql_error()."\n<br /><b>When executing:</b><br />\n$query\n<br /><br />";
return $result;
}

function valid_email($email) {
  $result = TRUE;
  if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)) {
    $result = FALSE;
  }
  return $result;
}


function wysiwyg() {
global $siteurl;
return "<script language='javascript' type='text/javascript' src='".$siteurl."includes/jscripts/tiny_mce/tiny_mce.js'></script>
<script language='javascript' type='text/javascript'>
	tinyMCE.init({
		theme : 'advanced',
		mode : 'textareas',
		elements : 'abshosturls',
		plugins : 'spellchecker,preview,searchreplace,emotions,media,tinyautosave,contextmenu,codeprotect',

		theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontsizeselect,formatselect',
		theme_advanced_buttons2 : 'bullist,numlist,|,undo,redo,|,link,unlink,image,cleanup,code,preview,replace,spellchecker,emotions,media,tinyautosave',
		theme_advanced_buttons3 : '',
		theme_advanced_toolbar_location : 'top',
		theme_advanced_toolbar_align : 'left',
		theme_advanced_statusbar_location : 'bottom',
		theme_advanced_resizing : true,

		remove_linebreaks : false,
        force_p_newlines : false,
		debug : false,
		relative_urls : false,
		remove_script_host : false
	});</script>";
}

function re_direct($time, $url) {
return "<SCRIPT LANGUAGE='JavaScript'>
redirTime = '".$time."';
redirURL = '".$url."';
function redirTimer() { self.setTimeout('self.location.href = redirURL;',redirTime); }
</script><BODY onLoad='redirTimer()'>";
}

function badwords($str) { // http://www.programmingtalk.com/showthread.php?t=34225
global $setting;

	$badwords = explode(",", $setting['word_filter']);
    $replacements = "*";
    
    foreach ($badwords AS $badword)
    {
          $str = eregi_replace($badword, str_repeat('*', strlen($badword)), $str);
    }  
    
    return $str;
}  

function admin_header() {
global $setting;
global $domain;
global $pre;
global $level;
global $mrw_1;
global $mrw;
global $key;

$user = $_COOKIE[adaptcms_username];

if (($_COOKIE['adaptcms_skin']) or ($_POST['skin'])) {
if ($_COOKIE['adaptcms_skin']) {
$skin = $_COOKIE['adaptcms_skin'];
}
if ($_POST['skin']) {
$skin = $_POST['skin'];
}
} else {
$skin = "skin1";
}
if ($skin == "skin1") {
$color = "#feb011";
$color2 = "#4A4A4A";
}
if ($skin == "skin2") {
$color = "#db1c1c";
$color2 = "white";
}
if ($skin == "skin3") {
$color = "#5400ff";
$color2 = "white";
}
if ($skin == "skin4") {
$color = "#176b12";
$color2 = "white";
}
if ($skin == "skin5") {
$color = "#64126b";
$color2 = "white";
}
$temp .= '
<html>
<head>
<script language="javascript">function jump(targ,selObj,restore){
eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
if (restore) selObj.selectedIndex=0;
}
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}

function clickrecall(thisfield, defaulttext) {
if (thisfield.value == "") {
thisfield.value = defaulttext;
}
}
function confirmDelete()
{
    return confirm("Are you sure you wish to delete this entry?");
}
function confirmVerify()
{
    return confirm("Are you sure you wish to verify this entry?");
}
</script>';
$temp .= "<script language='javascript'>function awindow(towhere, newwinname, properties) {window.open(towhere,newwinname,properties);}</script><STYLE type='text/css'>body { font-family: tahoma;font-size: 11px;color: #4a4a4a; }td { font-family: tahoma;font-size: 11px;color: #4a4a4a;}a:link {color: #4a4a4a; text-decoration: none;font-weight: bold}a:visited {color: #4a4a4a; text-decoration: none;font-weight: bold} a:active {color: #4a4a4a; text-decoration: none;font-weight: bold} a:hover {text-decoration: none; color: #4a4a4a;font-weight: bold}a:visited:hover {text-decoration: none; color: #4a4a4a;font-weight: bold</style>

<table cellpadding='0' cellspacing='0' width='757' border='0' align='center'><tr><td>

<table cellpadding='0' cellspacing='0' width='757' border='0' align='center'><tr><td><img src='skins/".$skin."/top.png'></td></tr></table><br />

<table cellpadding='0' cellspacing='0' border='0'><tr><td align='left' valign='top'>

<form name='form1'><table cellpadding='0' cellspacing='0' border='0'><tr><td background='includes/leftbg.png' height='281' width='168' align='left' valign='top'><img src='skins/".$skin."/menu1.png'>

<table cellpadding='10' cellspacing='0' border='0' width='center'><tr><td valign='top'>";
if ($_GET['view'] == "denied") {
$temp .= "<a href='index.php'>Main Site</a><br />";
} else {
$temp .= "<a href='index.php'>Main Site</a><br />
<a href='admin.php'>Admin Panel</a><br />
<a href='admin.php?view=support'>Support</a><br />
<a href='admin.php?view=tools'>Tools</a><br /><br />
<a href='admin.php?view=articles'>Articles</a><br />
<a href='admin.php?view=comments'>Comments</a><br />
<a href='admin.php?view=files'>Files</a><br />
<a href='admin.php?view=gallery'>Gallery</a><br />
<a href='admin.php?view=pages'>Pages</a><br />
<a href='admin.php?view=plugins'>Plugins</a><br />";
$temp .= "<a href='admin.php?view=polls'>Polls</a><br />
<a href='admin.php?view=sections'>Sections</a><br />
<a href='admin.php?view=stats'>Statistics</a><br />
<a href='javascript:awindow(\"http://www.adaptcms.com/s2smessages.php?domain=".$domain."&license_number=".$license_number."\", \"\", \"width=600,height=400,scroll=yes,toolbar=no,directories=no,status=no,menubar=no,resizable=yes\")'>S2S messages</a><br /><br />

<select name='quickadd' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px' onChange=\"jump('parent',this,0)\"><option value=''>-- Quick Add --</option>";
$sql = @mysql_query("SELECT * FROM ".$pre."sections ORDER BY `type` ASC, `name` ASC");
while($r = @mysql_fetch_array($sql)) {
$p = "";
$p = @mysql_fetch_row(@mysql_query("SELECT padd FROM ".$pre."permissions WHERE level = '".$level."' AND name = '".$r[name]."'"));
if ($p[0]) {
$temp .= "<option value='admin.php?view=quick_add_articles&cat=".$r[name]."'>".ucwords($r[name])."</option>";
}
}
$temp .= "</select></center>";
}
$temp .= "</td></tr></table></form>
</td></tr></table><br />

<table cellpadding='0' cellspacing='0' border='0'><tr><td background='includes/leftbg.png' height='281' width='168' align='left' valign='top'><img src='skins/".$skin."/menu2.png'>

<table cellpadding='10' cellspacing='0' border='0' width='center'><tr><td>";
if ($_GET['view'] == "denied") {
} else {
$temp .= "
<form action='admin.php?view=search' method='get'><input type='hidden' name='view' value='search'><input type='text' size='21' name='search' onclick=\"clickclear(this, 'Admin Panel Search...')\" onblur=\"clickrecall(this,'Admin Panel Search...')\" value='Admin Panel Search...' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'><br /><select name='cat' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'>";
$array = array("articles","comments","fields","files","gallery","pages","settings","templates","users");
while (list(, $i) = each ($array)) {
$temp .= "<option value='".$i."'>".ucwords($i)."</option>";
}
$temp .= "</select> <input type='submit' value='Go' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'></form>

<form action='admin.php?view=support_search' method='post'><input type='text' size='13' name='search' onclick=\"clickclear(this, 'Support Search...')\" onblur=\"clickrecall(this,'Support Search...')\" value='Support Search...' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'> <input type='submit' value='Search' style='font-family: tahoma; font-size: 11px; border: 1px solid #444444;padding-left:1px'></form>
<a href='admin.php?view=fields'>Custom Fields</a><br />
<a href='admin.php?view=permissions'>Permissions</a><br />
<a href='admin.php?view=ranks'>Ranks</a><br />
<a href='admin.php?view=settings'>Settings</a><br />
<a href='admin.php?view=templates'>Templates</a><br />
<a href='admin.php?view=levels'>User Levels</a><br />
<a href='admin.php?view=users'>Users</a><br /><br /><br />".translate();
}
$temp .= "</td></tr></table>
</td></tr></table>

</td><td valign='top' width='591' align='center'><table cellpadding='1' cellspacing='0' border='0' width='100%'><tr><td align='center'>";
$num1 = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."articles WHERE ver = ''"));
if ($_COOKIE[adaptcms_username]) {
$temp .= "Welcome back <a href='".$mrw["profile"]."'>".stripslashes($_COOKIE[adaptcms_username])."</a>! There are <a href='admin.php?view=articles'>".$num1."</a> articles, <a href='admin.php?view=users'>".online("", 60)."</a> user(s) and <b>".online("guests", 15)."</b> guest(s) online @ <a href='http://www.".$domain."'>".$domain."</a>";
} else {
$temp .= "Welcome <b>Guest</b>. Please <a href='".$mrw_1["login"]."'>Login</a> or <a href='".$mrw_1["register"]."'>Sign-Up</a> to use some features of ".ucwords($domain);
}

$temp .= "</td><td align='right'><form action='".$_SERVER['REQUEST_URI']."' method='post'><select name='skin' style='background-color: ".$color.";color: ".$color2.";font-size: 11px;font-face: tahoma;font-weight: bold' onchange='this.form.submit()'><option value='skin1' style='background-color: ".$color.";color: ".$color2.";font-size: 11px;font-face: tahoma;font-weight: bold' selected> - Choose Skin -</option><option value='skin1' style='background-color: #feb011;color: #4a4a4a;font-size: 11px;font-face: tahoma;font-weight: bold'>Orange Skin</option><option value='skin2' style='background-color: #db1c1c;color: white;font-size: 11px;font-face: tahoma;font-weight: bold'>Red Skin</option><option value='skin3' style='background-color: #5400ff;color: white;font-size: 11px;font-face: tahoma;font-weight: bold'>Blue Skin</option><option value='skin4' style='background-color: #176b12;color: white;font-size: 11px;font-face: tahoma;font-weight: bold'>Green Skin</option><option value='skin5' style='background-color: #64126b;color: white;font-size: 11px;font-face: tahoma;font-weight: bold'>Dark Skin</option></select></form></td></tr></table><br /><table cellpadding='0' cellspacing='0' border='0' width='center'><tr><td background='includes/contentbg.png' height='100%' width='518' valign='top' align='left'><img src='skins/".$skin."/content.png'><table cellpadding='10' cellspacing='0' border='0' width='center'><tr><td>";
return $temp;
}

$timev = 0;
$sqlv = mysql_query("SELECT * FROM ".$pre."stats WHERE date < ".$time2." AND date > ".$time1." AND username = ''");
while($r = @mysql_fetch_array($sqlv)) {
if (preg_match("/".$r[ip]."/", $datav) == 0) {
$timev = $timev + 1;
}
$datav .= $r[ip];
}

function users_online($mins) {
global $pre;
global $mrw_1;
global $botlist;

if ($mins == "" or $mins == 0) {
$mins = 15;
}
$min = $mins * 60 + 1;
$time1 = time() - $min;
$time2 = time() + 1;
$timev = 0;
$datav = "";
//$sqlv = mysql_query("SELECT * FROM ".$pre."users WHERE logged < ".$time2." AND logged > ".$time1);
$sqlv = mysql_query("SELECT * FROM ".$pre."stats WHERE date < ".$time2." AND date > ".$time1." AND username != ''");
while($r = mysql_fetch_array($sqlv)) {
$bot_count = "";
if (preg_match("/".$r[ip]."/", $datav) == 0) {
$timev = $timev + 1;


foreach($botlist as $bot) {
if (preg_match("/".$r[username]."/", $bot)) {
$bot_count = "1";
}
}
//$data .= $bot_count."<br>";

if (!$bot_count) {
$rank = mysql_fetch_row(mysql_query("SELECT rank FROM ".$pre."users WHERE username = '".$r[username]."'"));
$color = mysql_fetch_row(mysql_query("SELECT color FROM ".$pre."ranks WHERE name = '".$rank[0]."'"));
if ($timev == 1) {
$data .= "<a href='".$mrw_1["user"].fthrough($r[username],"","")."'><font color='".$color[0]."'>".stripslashes($r[username])."</font></a>";
} else {
$data .= ", <a href='".$mrw_1["user"].fthrough($r[username],"","")."'><font color='".$color[0]."'>".stripslashes($r[username])."</font></a>";
}
} else {
if ($timev == 1) {
$data .= "<b>".stripslashes($r[username])."</b>";
} else {
$data .= ", <b>".stripslashes($r[username])."</b>";
}
}

}
$datav .= $r[ip];
}
return $data;
}

function online($type, $mins) {
global $pre;
global $botlist;
if ($mins == "" or $mins == 0) {
$mins = 15;
}
if ($type == "all" or $type == "guests") {
$min = $mins * 60 + 1;
$time1 = time() - $min;
$time2 = time() + 1;
$timev = 0;
$datav = "";
foreach($botlist as $bot) {
$quer .= " OR date < ".$time2." AND date > ".$time1." AND username = '".$bot."'";
}
$sqlv = mysql_query("SELECT * FROM ".$pre."stats WHERE date < ".$time2." AND date > ".$time1." AND username = '' OR date < ".$time2." AND date > ".$time1." AND username = 'guest'".$quer);
while($r = @mysql_fetch_array($sqlv)) {
if (preg_match("/".$r[ip]."/", $datav) == 0) {
$timev = $timev + 1;
}
$datav .= $r[ip];
}
return $timev;
} else {
$min = $mins * 60 + 1;
$time1 = time() - $min;
$time2 = time() + 1;
//$time = @mysql_num_rows(@mysql_query("SELECT * FROM ".$pre."users WHERE logged < ".$time2." AND logged > ".$time1));
$timev = 0;
foreach($botlist as $bot) {
$que .= " AND username != '".$bot."'";
}
$sqlv = mysql_query("SELECT * FROM ".$pre."stats WHERE date < ".$time2." AND date > ".$time1." AND username != '' AND username != 'guest'".$que);
while($r = @mysql_fetch_array($sqlv)) {
if (preg_match("/".$r[ip]."/", $datav) == 0) {
$timev = $timev + 1;
}
$datav .= $r[ip];
}
return $timev;
}
}

function admin_footer() {
return "</td></tr></table>

</td></tr></table>

<a href='http://www.adaptcms.com'><img src='includes/footer1.png' border='0'></a>

</td></tr></table>
</td></tr></table>

</body></html>";
}
?>