<?php

function dbquery($sql) {
  //own db debugger
  global $fdb, $conf_admin_mail, $f_auth_uid;
  //$time = time() . " " . date("g:i:s.u");
  //mail($conf_admin_mail, "[$time] SQL START",$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\n\n$sql");
  $res = mysql_query($sql,$fdb);
  //$time = time() . " " . date("g:i:s.u");
  //mail($conf_admin_mail, "[$time] SQL END",$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\n\n$sql");
  if (mysql_errno($fdb) && basename($_SERVER['PHP_SELF']) != "setup.php") {
    mail($conf_admin_mail, 'Simple-BB DB-Error',$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\n\nMySQL error ".mysql_errno().": ".mysql_error()."\nWhen executing:\n$sql\nHTTP_USER_AGENT: ".$_SERVER['HTTP_USER_AGENT']."\nREMOTE_ADDR: ".$_SERVER['REMOTE_ADDR']."\nHTTP_HOST: ".$_SERVER['HTTP_HOST'] . "\n\nUID: $f_auth_uid");
  }
  return $res;
}

function dbquote($str) {
  //to get the correct quotes and prevent from musthave of magic quotes
  if (get_magic_quotes_gpc()) { //if slashes added and magic quotes are enabled
      $str = stripslashes($str);
  }
  // quotieren, falls kein integer
  if (!is_numeric($str)) {
      $str = "'" . mysql_real_escape_string($str) . "'";
  }
  return $str;
}

  
function forum_user($uid) {
  global $ftable_prefix, $is_admin;
  $uid = intval($uid);
  if (!$uid) return false;
  else {
    if ($uid) $sql = "select * from `" . $ftable_prefix . "users` where id = '$uid' " . (!$is_admin ? "and status = '1'" : "") . ";";
    $res = dbquery($sql,$fdb);
    if (mysql_num_rows($res)) {
      $row = mysql_fetch_object($res);
      if ($row->birthday != "0000-00-00" && $row->birthday) {
        list ($y,$m,$d) = explode("-",$row->birthday);
        if ($y > "1900") $row->age = (date('Y')-$y) - intval(date('md') < sprintf('%02d%02d' , $m, $d));
        //strtotime bugfix
        if ($y == 1900) $row->birthday = ($y+50) . "-$m-$d";
      } else $row->birthday = false;
      return $row;
    } else return false;
  }
}

function voted($tid) {
  global $ftable_prefix, $f_auth_uid;
  if (!$tid || !$f_auth_uid) return false;
  $sql = "select poll_option_id from `" . $ftable_prefix . "polls` where uid = '$f_auth_uid' and poll_option_id in (select id from `" . $ftable_prefix . "poll_options` where tid = '$tid');";
  $res = dbquery($sql);
  if (mysql_num_rows($res)) {
    while ($row = mysql_fetch_object($res)) {
      $arr[] = $row->poll_option_id;
    }
    return $arr;
  }
  else return false;
}


function translate($arr,$lang) {
  if ($arr[$lang]) { //if existing
    return($arr[$lang]);
  } else {
    //found engl.
    if ($arr["en"]) return $arr["en"];
    else { //if not, use next avail
      $arr_keys = array_keys($arr);
      return $arr[$arr_keys[0]];
    }
  }
}

  function lang($key) {
    global $lang, $deblang;
    if (array_key_exists($key, $lang)) return $lang[$key];// . " [$key]";
    else {
      $deblang[] = $key;
      return "__" . $key . "__";
    }
  }
  function deblang() {
    //mail notfound language keys to debug mailaddr
    global $f_lang, $conf_admin_mail, $deblang;
    if (!$deblang) return false;
    mail($conf_admin_mail, 'Simple-BB Language-Error',$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']."\n\nLanguage: $f_lang\nLanguagefile: $f_lang/common.lang.php\nKeys:\n\t" . implode("\n\t",$deblang) . "\n");  
  }


function getUtopic($tid) {
  global $ftable_prefix;
  if (!$tid) return false;
  else {
    $sql = "select unix_timestamp(datetime) as ut, 'q' as type, topic, detail as message, uid, id as tid, fid from " . $ftable_prefix . "question where id = '$tid'";
    $res = dbquery($sql);
    return mysql_fetch_object($res);
  }
}
function getUreply($a_id,$tid) {
  global $ftable_prefix;
  if (!$tid || !$a_id) return false;
  else {
    $sql = "select unix_timestamp(" . $ftable_prefix . "answer.a_datetime) as ut, 'a' as type, topic, a_topic, a_answer as message, " . $ftable_prefix . "answer.a_uid as uid, a_id, question_id as tid, fid from " . $ftable_prefix . "answer, " . $ftable_prefix . "question where " . $ftable_prefix . "answer.a_id = '$a_id' and " . $ftable_prefix . "answer.question_id = " . $ftable_prefix . "question.id and " . $ftable_prefix . "answer.question_id = '$tid'";
    $res = dbquery($sql);
    return mysql_fetch_object($res);
  }
}

function forum_user_posts($uid) {
  global $ftable_prefix;
  $uid = intval($uid);
  if (!$uid) return false;
  else {
    $sql = "select unix_timestamp(datetime) as ut, 'q' as type, topic, detail as message, uid, id as tid, fid from " . $ftable_prefix . "question where uid = '$uid' order by datetime;";
    $res = dbquery($sql);
    $x = 1000;
    if (mysql_num_rows($res)) {
      while ($row = mysql_fetch_object($res)) {
        $x++;
        //$output[$row->ut . "_$x"]["content"] = $row;
        $output[$row->ut . "_$x"]["tid"] = $row->tid;
        $keys[] = $row->ut . "_$x";
      }
    }
    $sql = "select unix_timestamp(" . $ftable_prefix . "answer.a_datetime) as ut, 'a' as type, topic, a_topic, a_answer as message, " . $ftable_prefix . "answer.a_uid as uid, a_id, question_id as tid, fid from " . $ftable_prefix . "answer, " . $ftable_prefix . "question where " . $ftable_prefix . "answer.a_uid = '$uid' and " . $ftable_prefix . "answer.question_id = " . $ftable_prefix . "question.id;";
    $res = dbquery($sql);
    if (mysql_num_rows($res)) {
      while ($row = mysql_fetch_object($res)) {
        $x++;
        //$output[$row->ut . "_$x"]["content"] = $row;
        $output[$row->ut . "_$x"]["a_id"] = $row->a_id;
        $output[$row->ut . "_$x"]["tid"] = $row->tid;
        $keys[] = $row->ut . "_$x";
      }
    }
    if ($output) return array("content" => $output, "keys" => $keys);
    else return false;
  }
}

function forum_user_post_count($uid) {
  global $ftable_prefix;
  $uid = intval($uid);
  $sum = 0;
  if (!$uid) return false;
  else {
    //topics
    $sql = "select count(id) as cnt from `" . $ftable_prefix . "question` where uid = '$uid'";
    $res = dbquery($sql);
    $row = mysql_fetch_object($res);
    $sum = $row->cnt;
    //replies
    $sql = "select count(a_id) as cnt from `" . $ftable_prefix . "answer`, `" . $ftable_prefix . "question` where `" . $ftable_prefix . "answer`.a_uid = '$uid' and `" . $ftable_prefix . "answer`.question_id = `" . $ftable_prefix . "question`.id";
    $res = dbquery($sql);
    $row = mysql_fetch_object($res);
    $sum += $row->cnt;
    return $sum;
  }
}

function nick_class($is_admin, $is_mod) {
  if ($is_admin) return "coltext3";
  elseif ($is_mod) return "coltext2";
  else return false;     
}

function strip_bbcodes($str) {
  $find = array("[ b]","[ /b]","[b]","[/b]",
    "[ i]","[ /i]","[i]","[/i]",
    "[ u]","[ /u]","[u]","[/u]",
    "[ quote]","[ /quote]","[quote]","[/quote]", 
    "[ code]","[ /code]","[code]","[/code]",
    "[ list]","[ /list]","[list]","[/list]",
    "[ *]","[*]",
    "[img]","[/img]",
    "[youtube]","[/youtube]",
    "[video]","[/video]");
  return str_replace($find,"",$str);
}

function bbencode($text,$encodeurls=true,$hl=false) {
  global $rel_path;
  //simple replacements
  $text = strip_tags(stripslashes(trim($text)));
 
  $find = array("[ b]","[ /b]","[b]","[/b]",
    "[ i]","[ /i]","[i]","[/i]",
    "[ u]","[ /u]","[u]","[/u]",
    "[ quote]","[ /quote]","[quote]","[/quote]", 
    "[ code]","[ /code]","[code]","[/code]",
    "[ list]","[ /list]","[list]","[/list]",
    "[ *]","[*]",
    "[img]","[/img]",
    ": )=):",": 8):",": )):",": (:",": ((:");
  $replace = array("<b>","</b>","<b>","</b>",
    "<i>","</i>","<i>","</i>", 
    "<span class='u'>","</span>","<span class='u'>","</span>",
    "<div class='bbquote'><div class='bbquotehl'>Quote:</div><div style='padding:5px;'>","</div></div>","<div class='bbquote'><div class='bbquotehl'>Quote:</div><div style='padding:5px;'>","</div></div>",
    "<div class='bbcode'><div class='bbcodehl'>Code:</div><pre style='padding:5px;margin:0px;'>","</pre></div>","<div class='bbcode'><div class='bbcodehl'>Code:</div><pre style='padding:5px;margin:0px;'>","</pre></div>",
    "<ul>","</ul>","<ul>","</ul>",
    "<li>","<li>",
    "<img src='","' alt='' />",
    "<img src='$rel_path/images/icons/smiley_biggrin.gif' alt='' /> ","<img src='$rel_path/images/icons/smiley_cool.gif' alt='' /> ","<img src='$rel_path/images/icons/smiley_lol.gif' alt='' /> ","<img src='$rel_path/images/icons/smiley_sad.gif' alt='' /> ","<img src='$rel_path/images/icons/smiley_wah.gif' alt='' /> ");
  
  //external smilies
  $smilies = smilies();
  if ($smilies["count"]) {
    for ($i=0;$i<$smilies["count"];$i++) {
      $find[] = $smilies["files"][$i]["SMILEY_CODE"];
      $replace[] = "<img src='$rel_path/images/smilies/" . $smilies["files"][$i]["SMILEY"] . "' alt='' /> ";
    }
  }
  
  $encoded = str_replace($find, $replace, $text);
  
  

  //url replacements
  if ($encodeurls) {
    $encoded = preg_replace("/\[url\](.*?)\[\/url\]/e", ("'<a href=\"$1\" onclick=\"javascript:window.open(this.href); return false;\">$1</a>'"), $encoded);
    $encoded = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/e", ("'<a href=\"$1\" onclick=\"javascript:window.open(this.href); return false;\">$2</a>'"), $encoded);
  }
  //embedded youtube and vimeo videos
  $encoded = preg_replace("/\[(?:youtube|video)\](.*?)\[\/(?:youtube|video)\]/e", 'createVideoIframe("\1")', $encoded);
  
  //highlight search_results
  if ($hl) $encoded = hl($encoded,$hl);
  return nl2br($encoded);
}

if (!function_exists("checkdnsrr")) {
  function checkdnsrr() {
    return true;
  }
}

function is_email($email) {
  $email = trim($email);
  if (!$email) return false;
  if (!preg_match("!^[\w|\.|\-|_]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,6}$!",$email)) return false;
  else {
    list($user, $host) = explode("@", $email);
    if (checkdnsrr($host, "MX") or checkdnsrr($host, "A")) return true;
    else return false;
  }
}

function relPath($path1, $path2) {
    //replacing Backslashes with Slashes on Windows Machnines
    $path1 = str_replace("\\","/",$path1);
    $path2 = str_replace("\\","/",$path2);

    //Remove starting, ending, and double / in paths
    $path1 = trim($path1,'/');
    $path2 = trim($path2,'/');
    while (substr_count($path1, '//')) $path1 = str_replace('//', '/', $path1);
    while (substr_count($path2, '//')) $path2 = str_replace('//', '/', $path2);

    //create arrays
    $arr1 = explode('/', $path1);
    if ($arr1 == array('')) $arr1 = array();
    $arr2 = explode('/', $path2);
    if ($arr2 == array('')) $arr2 = array();
    $size1 = count($arr1);
    $size2 = count($arr2);
    //now the hard part :-p
    $path='';
    for($i=0; $i<min($size1,$size2); $i++) {
        if ($arr1[$i] == $arr2[$i]) continue;
        else $path = '../'.$path.$arr2[$i].'/';
    }
    if ($size1 > $size2) {
      for ($i = $size2; $i < $size1; $i++) {
        $path = '../'.$path;
      }
    } elseif ($size2 > $size1) {
      for ($i = $size1; $i < $size2; $i++) {
        $path .= $arr2[$i].'/';
      }
    }
    //crop trailing slash
    $path = preg_replace('/\/$/','',$path);
    return $path;
}

function statmess($mess_kind, $mess_key) {
  //to make it easier to change and find error/success messages they are stored in includes/stat_messages.php
  //and here is the place to print them out
  
  global $ERR, $SUC, $this_user, $fuser, $stat, $img_ext_arr;
  
  $find = array("{USER_NAME}","{NICK}","{STAT}");
  $replace = array($this_user->user,$fuser,($stat ? "de" : ""));
  
  if (${$mess_kind}[$mess_key]) return str_replace($find,$replace,${$mess_kind}[$mess_key]);
  else return false;
}

//to remove/replace some chars for file uploads
function tidyup($str) {
  $str = strtolower(trim($str));
  $find = array(" ","ä","ö","ü","ß",",");
  $replace = array("_","ae","oe","ue","sz","_");
  
  $str = str_replace($find,$replace,$str);
  $str = preg_replace('([^a-z0-9\.\-_])', '', $str);
  return $str;
}

//delete directories recursive and the files within
function xrmdir($location){
   $rc=0;
   if (is_dir($location)){
      $dp=opendir("$location");
      while(false !== ($file = readdir($dp))){
         if ($file=="."||$file=="..") continue;
         xrmdir("$location/$file");
      }
      closedir($dp);
      unset($dp);
      $rc=rmdir($location);
      unset($location);
   }
   else{
      if (file_exists($location)) $rc=unlink($location);

      unset($location);
   }
   return $rc;
}

//currently only used for the signature
function make_clickable($text) {
	$ret = ' ' . $text;
	$ret = preg_replace("#(^|[\n ])([\w]+?://[^ \"\n\r\t<]*)#is", "\\1<a href=\"\\2\" onclick=\"javascript:window.open(this.href); return false;\">\\2</a>", $ret);
	$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#is", "\\1<a href=\"http://\\2\" onclick=\"javascript:window.open(this.href); return false;\">\\2</a>", $ret);
	$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
  $ret = preg_replace("#(^|[\n ])(([a-z0-9_-]+)\.([a-z0-9_-]+)\.([a-z0-9_-]+)[^ \"\t\n\r\)<]*)#is", "\\1<a href=\"http://\\2\" onclick=\"javascript:window.open(this.href); return false;\">\\2</a>", $ret);
	$ret = substr($ret, 1);
	return($ret);
}

function he($str) {
  //short htmlentities checker - converts all quotes
  $str = htmlentities($str, ENT_QUOTES);
  return $str;
}

function adddescr2link($str) {
  $str = trim(strtolower($str));
  $find = array("ä","ö","ü","ß","&");
  $replace = array("ae","oe","ue","ss","+");
  $str = str_replace($find,$replace,$str);
  $find = array("Ä","Ö","Ü");
  $str = str_replace($find,$replace,$str);
  $str = preg_replace('([^a-z0-9,+])',"-",$str);
  $str = preg_replace("([-]+)",'-',$str);
  //$str = preg_replace('([^a-z0-9\.\-_])', '', $str);
  return "-".preg_replace('/-$/',"",$str);
}

function short($str,$len) {
  if ((strlen($str)+4) > $len) return trim(substr($str,0,$len)) . "...";
  else return $str;
}

function add0($int) {
  if ($int < 10) return "0$int";
  else return $int;
}

//generate passwords (needed for resets)
function genPWD($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) $consonants .= 'BDGHJLMNPQRSTVWXZ';
    if ($strength & 2) $vowels .= "AEUY";
    if ($strength & 4) $consonants .= '23456789';
    if ($strength & 8) $consonants .= '@#$%';
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

function pagination($pages,$p) {
  if ($pages < 2) return false;   //nothing to page
  if ($pages > 8) {
    //interpage calc
    $pstart = $p - 2;
    if ($pstart <= 1) $pstart = 2;
		$pend = $p + 2;
		if ($pend > $pages) $pend = $pages;
		$pages_after_last_interpage = ($pend+1 >= $pages ? true : false);
		$pages_before_first_interpage = ($pstart-2 >= 1 ? true : false);
  
    $NAV_PAGES[] = array("P" => 1,
                         "ADD2PCLASS" => ($p == 1 ? "sel" : ""),
                         "SEP" => ($pages_before_first_interpage ? " ... " : ""));
                         
    for ($i=$pstart;$i<=$pend;$i++) {
      $NAV_PAGES[] = array("P" => $i,
                           "ADD2PCLASS" => ($p == $i ? "sel" : ""),
                           "SEP" => ($i == $pend && !$pages_after_last_interpage ? " ... " : "" ));
    }
    if ($pend < $pages) {
    $NAV_PAGES[] = array("P" => $pages,
                         "ADD2PCLASS" => "",
                         "SEP" => "");
    }
  } else {
    //into template array
    for ($i=1;$i<=$pages;$i++) {
      $NAV_PAGES[] = array("P" => $i,
                           "ADD2PCLASS" => ($p == $i ? "sel" : ""),
                           "SEP" => "");
    }
  }
  return $NAV_PAGES;
}

function createVideoIframe($url) {
  $url = trim($url);
  if (!$url) return false;
  if (preg_match('/www\.youtube\.com/',$url)) {
    //http://www.youtube.com/watch?v=gch6edum9Tg 
    $t = parse_url($url);
    $q = $t["query"];
    if (!$q) return false;
    parse_str($q,$op);
    if (!$op["v"]) return false;
    else $vurl = "http://www.youtube.com/v/" . $op["v"] . "?fs=1&amp;autoplay=0";
  } elseif (preg_match('/youtu\.be/',$url)) {
    //http://youtu.be/gch6edum9Tg
    $t = parse_url($url);
    $q = basename($t["path"]);
    if (!$q) return false;
    else $vurl = "http://www.youtube.com/v/$q?fs=1&amp;autoplay=0";
  } elseif (preg_match('/vimeo\.com/',$url)) {
    //http://vimeo.com/21864555
    $t = parse_url($url);
    $q = basename($t["path"]);
    if (!$q) return false;
    else $vurl = "http://player.vimeo.com/video/$q?autoplay=0";
  } else return false;
  if ($vurl) {
    return "<iframe width='560' height='315' src='$vurl' frameborder='0' allowfullscreen webkitallowfullscreen mozallowfullscreen>$vurl</iframe>";
  }
}


function fsize($int) {
  $int = intval($int);
  if ($int/1024 < 1024) return round($int/1024,2) . " KB";
  elseif ($int/1024/1024 < 1024) return round($int/1024/1024,2) . " MB";
  else return round($int/1024/1024,2) . " GB";
}

function has_edit_permission($tid,$pid=0) {
  global $board_config, $is_admin, $is_mod, $f_auth_uid;
  if (!$f_auth_uid) return false;
  if ($is_admin || $is_mod) return true;
  if ($board_config->mod_minutes == -1) return false;
  
  if ($tid && !$pid && !$attid) $checktid = true;
  if ($tid && $pid && !$attid) $checkpid = true;
  
  //the topic only - including it's attachments
  if ($checktid) {
    $sql = "select *, TIMESTAMPDIFF(MINUTE,`datetime`,now()) as age from `" . $board_config->prefix . "question` where id = '$tid';";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) return false;
    else {
      $row = mysql_fetch_object($res);
      if ($row->uid == $f_auth_uid) {
        if ($board_config->mod_minutes == 0) return true;
        if ($board_config->mod_minutes >= $row->age) return true;
        else return false;
      }
    }
  }
  //onepost - including it's attachments
  if ($checkpid) {
    $sql = "select *, TIMESTAMPDIFF(MINUTE,`a_datetime`,now()) as age from `" . $board_config->prefix . "answer` where question_id = '$tid' and a_id = '$pid';";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) return false;
    else {
      $row = mysql_fetch_object($res);
      if ($row->a_uid == $f_auth_uid) {
        if ($board_config->mod_minutes == 0) return true;
        if ($board_config->mod_minutes >= $row->age) return true;
        else return false;
      }
    }
  }
}

/** returns 
  0 ... for allowance to rate
  1 ... information about already liked
 -1 ... information about already disliked
 false ... no permission to rate
 **/ 
function rating_permission($uid,$tid,$pid) {
  global $board_config, $f_auth_uid;
  if (!$f_auth_uid) return false;
  
  $uid = intval($uid);
  $tid = intval($tid);
  $pid = intval($pid);

  //users don't have the right to rate their own posts
  if ($uid == $f_auth_uid) return false;
  if ($pid) {
    $sql = "select rating from `" . $board_config->prefix . "ratings` where tid = '$tid' and pid = '$pid' and uid = '$f_auth_uid'";
  } else {
    $sql = "select rating from `" . $board_config->prefix . "ratings` where tid = '$tid' and pid = '0' and uid = '$f_auth_uid'";
  }
  $res = dbquery($sql);
  if (!mysql_num_rows($res)) return 0;
  $row = mysql_fetch_object($res);
  return $row->rating;
}

function smilies($repl = false) {
  global $rel_path;
  $smilies_dir = "$rel_path/images/smilies";
  if (!is_dir($smilies_dir)) return false;
  $handle = opendir($smilies_dir);
  $i = 0;
  while(false !== ($file = readdir($handle))) {
    if ($file=="."||$file=="..") continue;
    elseif (preg_match('/gif$/i',$file)) {
      $this_code = ":" . preg_replace('/\.gif$/i','',$file) . ":";
      $SMILIES[] = array("SMILEY" => $file,
                         "SMILEY_CODE" => $this_code);
      $i++;
    }
  }
  closedir($handle);
  return array("files" => $SMILIES, "count" => $i);
}

function avatars($d=false) {
  global $rel_path;
  $avatars_dir = "$rel_path/images/avatars";
  if (!is_dir($avatars_dir)) return false;
  $hdl1 = opendir($avatars_dir);
  $i=0;
  while(false !== ($file = readdir($hdl1))) {
    if ($file=="."||$file=="..") continue;
    else {
      //categories
      if (is_dir("$avatars_dir/$file")) {
        $AVATARS[$i]["cat"] = $file;
        $cat_cnt++;
        $hdl2 = opendir("$avatars_dir/$file");
        while(false !== ($file2 = readdir($hdl2))) {
          if ($file2=="."||$file2=="..") continue;
          elseif (preg_match('/(gif|png|jpg|jpeg)$/i',$file2)) {
            if ($d && $d == $file) $AVATARS[$i]["files"][] = $file2;
            $file_cnt++;
          }      
        }
        closedir($hdl2);
        $AVATARS[$i]["cnt"] = $file_cnt;
        if ($file_cnt) $found_avatars = true;
        else unset ($AVATARS[$i]);
        $file_cnt = 0;
        $i++;
      }
    }
  }
  closedir($hdl1);
  return ($found_avatars ? $AVATARS : false);
}

function gravatar($email) {
  global $board_config;
  $url = "http://www.gravatar.com/avatar/" . md5(strtolower($email)) ."?s=" . $board_config->avatar_width;
  return $url;
}


//create avatarthumb if bigger then allowed
function create_av_thumb($src) {
  global $board_config;
  $fname = basename($src);
  $dir = dirname($src);
  
  $width = $board_config->avatar_width;
  $height = $board_config->avatar_height;
  
  $_tn_filename = "$dir/tn_" . $fname;
  
  if (!file_exists($_tn_filename)) {
    list($width_orig, $height_orig) = getimagesize($src);

    if ($width_orig <= $width) $width = $width_orig;
    if ($height_orig <= $height) $height = $height_orig;
  
    if ($width && ($width_orig < $height_orig)) {
    	$width = ceil(($height / $height_orig) * $width_orig);
    } else {
      if ($height_orig > $width_orig) { //portrait
        $width = ceil(($height / $height_orig) * $width_orig);
      } else { //landscape
        $height = ceil(($width / $width_orig) * $height_orig);
      }
  //  	$height = ceil(($width / $width_orig) * $height_orig);
    }
    $image_p = imagecreatetruecolor($width, $height);
    $weiss = imagecolorallocate($image_p, 255, 255, 255);
    imagefilledrectangle($image_p, 0, 0, $width, $height, $weiss);
  
    $ext = explode(".",$fname);
  	$ext = array_pop($ext);
  
    if ($ext == "gif") $image = imagecreatefromgif($src);
  	elseif ($ext == "png") $image = imagecreatefrompng($src);
    else $image = imagecreatefromjpeg($src);
    
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
  	imagejpeg($image_p, $_tn_filename, 70);
    imagedestroy($image_p);    
  }
  if (file_exists($_tn_filename)) return true;
  else return false;
}




function hl($text, $needle) {
  if (!$needle) return $text;
  else {
    // Default highlighting
    if ($highlight === null) {
        $highlight = '<span class="hl">\1</span>';
    }
    $pattern = '#(?!<.*?)(%s)(?![^<>]*?>)#';
    $sl_pattern = '#<a\s(?:.*?)>(%s)</a>#';
    $pattern .= 'i';
    $sl_pattern .= 'i';
    $needle = (array) $needle;
	  foreach ($needle as $needle_s) {
	    //$needle_s = preg_quote(htmlentities($needle_s), '/');
      $needle_s = preg_quote($needle_s);
      $regex = sprintf($pattern, $needle_s);
      $text = preg_replace($regex, $highlight, $text);
	  }
    return $text;
  }
}

?>