<?php
error_reporting(0);
function trigger_db_error($obj)
{
    global $CFG;
    $error_arr = debug_backtrace();
    $subject   = "Report bug - Sql error - VAR_SITE_URL";
    $content   = "<u><b>Url :</b></u>\r\n\t\tVAR_CURRENT_URL\r\n\r\n\t\t<u><b>IP :</b></u>\r\n\t\tVAR_SITE_IP\r\n\r\n\t\t<u><b>Error File :</b></u>\r\n\t\tVAR_FILE\r\n\r\n\t\t<u><b>Error Line No :</b></u>\r\n\t\tVAR_LINE\r\n\r\n\t\t<u><b>Error Description:</b></u>\r\n\t\tVAR_ERROR";
    $frmobj    = new FormHandler();
    $frmobj->setEmailTemplateValue("VAR_CURRENT_URL", $CFG['site']['current_url']);
    $frmobj->setEmailTemplateValue("VAR_SITE_IP", $CFG['remote_client']['ip']);
    $frmobj->setEmailTemplateValue("VAR_FILE", $error_arr[0]['file']);
    $frmobj->setEmailTemplateValue("VAR_LINE", $error_arr[0]['line']);
    $frmobj->setEmailTemplateValue("VAR_ERROR", $error_arr[0]['args'][0]->debug_output);
    $frmobj->buildEmailTemplate($subject, $content, false, true);
    trigger_error("Error at " . $error_arr[0]['file'] . " on line " . $error_arr[0]['line'] . "<br>" . $obj->ErrorNo() . " " . $obj->ErrorMsg(), E_USER_ERROR);
}

function chkIsSiteUnderMaintenance()
{
    global $CFG;
    if ($CFG['admin']['module']['site_maintenance']) {
        $murl = getUrl($CFG['redirect']['maintenance_module_url']['file_name'], "", "", "root");
        if ($CFG['site']['current_url'] != $murl) {
            Redirect2Url($murl);
        }
    }
}

function word_limiter($str, $limit = 100, $end_char = "&#8230;")
{
    if (trim($str) == "") {
        return $str;
    }
    preg_match("/^\\s*+(?:\\S++\\s*+){1," . ( integer ) $limit . "}/", $str, $matches);
    if (strlen($str) == strlen($matches[0])) {
        $end_char = "";
    }
    return rtrim($matches[0]) . $end_char;
}

function character_limiter($str, $n = 500, $end_char = "&#8230;")
{
    if (strlen($str) < $n) {
        return $str;
    }
    $str = preg_replace("/\\s+/", " ", preg_replace("/(\r\n|\r|\n)/", " ", $str));
    if (strlen($str) <= $n) {
        return $str;
    }
    $out = "";
    foreach (explode(" ", trim($str)) as $val) {
        $out .= $val . " ";
        if (!($n <= strlen($out))) {
            continue;
        }
        return trim($out) . $end_char;
    }
}

function highlight_code($str)
{
    $str = str_replace(array(
        "&lt;",
        "&gt;"
    ), array(
        "<",
        ">"
    ), $str);
    $str = str_replace(array(
        "<?",
        "?>",
        "<%",
        "%>",
        "\\",
        "</script>"
    ), array(
        "phptagopen",
        "phptagclose",
        "asptagopen",
        "asptagclose",
        "backslashtmp",
        "scriptclose"
    ), $str);
    $str = "<?php tempstart" . "\n" . $str . "tempend ?>";
    $str = highlight_string($str, TRUE);
    if (abs(phpversion()) < 5) {
        $str = str_replace(array(
            "<font ",
            ",",
            ",",
            ",",
            ",",
            "</font>"
        ), array(
            "<span ",
            ",",
            ",",
            ",",
            ",",
            "</span>"
        ), $str);
        $str = preg_replace("#color=\"(.*?)\"#", "style=\"color: \\1\"", $str);
    }
    $str = preg_replace("#\\<code\\>.+?tempstart\\<br />(?:\\</span\\>)?#is", "<code>\n", $str);
    $str = preg_replace("#tempend.+#is", "</span>\n</code>", $str);
    $str = str_replace(array(
        "phptagopen",
        "phptagclose",
        "asptagopen",
        "asptagclose",
        "backslashtmp",
        "scriptclose"
    ), array(
        "&lt;?",
        "?&gt;",
        "&lt;%",
        "%&gt;",
        "\\",
        "&lt;/script&gt;"
    ), $str);
    return $str;
}

function highlight_phrase($str, $phrase, $tag_open = "<strong>", $tag_close = "</strong>")
{
    if ($str == "") {
        return "";
    }
    if ($phrase != "") {
        return preg_replace("/(" . preg_quote($phrase, "/") . ")/i", $tag_open . "\\1" . $tag_close, $str);
    }
    return $str;
}

function word_wrap($str, $charlim = "76")
{
    if (!is_numeric($charlim)) {
        $charlim = 76;
    }
    $str    = preg_replace("| +|", " ", $str);
    $str    = preg_replace("/\r\n|\r/", "\n", $str);
    $unwrap = array();
    if (preg_match_all("|(\\{unwrap\\}.+?\\{/unwrap\\})|s", $str, $matches)) {
        $i = 0;
        while ($i < count($matches['0'])) {
            $unwrap[] = $matches['1'][$i];
            $str      = str_replace($matches['1'][$i], "{{unwrapped" . $i . "}}", $str);
            ++$i;
        }
    }
    $str    = wordwrap($str, $charlim, "\n", FALSE);
    $output = "";
    foreach (explode("\n", $str) as $line) {
        if (strlen($line) <= $charlim) {
            $output .= $line . "\n";
            continue;
        }
        $temp = "";
        while ($charlim < strlen($line)) {
            if (preg_match("!\\[url.+\\]|://|wwww.!", $line)) {
                break;
            }
            $temp .= substr($line, 0, $charlim - 1);
            $line = substr($line, $charlim - 1);
        }
        if ($temp != "") {
            $output .= $temp . "\n" . $line;
        } else {
            $output .= $line;
        }
        $output .= "\n";
    }
    if (0 < count($unwrap)) {
        foreach ($unwrap as $key => $val) {
            $output = str_replace("{{unwrapped" . $key . "}}", $val, $output);
        }
    }
    $output = str_replace(array(
        "{unwrap}",
        "{/unwrap}"
    ), "", $output);
    return $output;
}

function utf8_strlen($str)
{
    return preg_match_all("/[\\x01-\\x7F]|[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF][\\x80-\\xBF]/", $str, $arr);
}

function utf8_substr($str, $start)
{
    preg_match_all("/./su", $str, $ar);
    if (3 <= func_num_args()) {
        $end = func_get_arg(2);
        return join("", array_slice($ar[0], $start, $end));
    }
    return join("", array_slice($ar[0], $start));
}

function htmlwrap($str, $width = 60, $break = "\n", $nobreak = "")
{
  $content = preg_split("/([<>])/", $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  $nobreak = explode(" ", strtolower($nobreak));
  $intag = false;
  $innbk = array();
  $drain = "";
  $lbrks = "/?!%)-}]\\\"':;&";
  $utf8 = (preg_match("/^([\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/", $str)) ? "u" : "";
  while (list(, $value) = each($content)) {
    switch ($value) {
      case "<": $intag = true; break;
      case ">": $intag = false; break;
      default:
        if ($intag) {
          $lvalue = strtolower($value);
          if ($lvalue{0} != "/") {
            preg_match("/^(\w*?)(\s|$)/", $lvalue, $t);
            if (in_array($t[1], $nobreak)) array_unshift($innbk, $t[1]);
          } else {
            if (in_array(substr($lvalue, 1), $nobreak)) {
              reset($innbk);
              while (list($key, $tag) = each($innbk)) {
                if (substr($lvalue, 1) == $tag) {
                  unset($innbk[$key]);
                  break;
               }
              }
              $innbk = array_values($innbk);
            }
          }
        } else if ($value) {
          if (!count($innbk)) {
            $value = str_replace("\x06", "", $value);
            preg_match_all("/&([a-z\d]{2,7}|#\d{2,5});/i", $value, $ents);
            $value = preg_replace("/&([a-z\d]{2,7}|#\d{2,5});/i", "\x06", $value);
            do {
              $store = $value;
              if (preg_match("/^(.*?\s)?([^\s]{".$width."})(?!(".preg_quote($break, "/")."|\s))(.*)$/s{$utf8}", $value, $match)) {
                if (strlen($match[2])) {
                  for ($x = 0, $ledge = 0; $x < strlen($lbrks); $x++) $ledge = max($ledge, strrpos($match[2], $lbrks{$x}));
                  if (!$ledge) $ledge = strlen($match[2]) - 1;
                  $value = $match[1].substr($match[2], 0, $ledge + 1).$break.substr($match[2], $ledge + 1).$match[4];
                }
              }
            } while ($store != $value);
            foreach ($ents[0] as $ent) $value = preg_replace("/\x06/", $ent, $value, 1);
          }
        }
    }
    $drain .= $value;
  }
  return $drain;
}

function wordWrapManual($text, $length, $total_length = 0)
{
    global $CFG;
    if (!$CFG['feature']['wrap_content']) {
        return $text;
    }
    if ($total_length) {
        $text = strip_tags($text);
        if ($total_length < utf8_strlen($text)) {
            $text = utf8_substr($text, 0, $total_length - 3) . "...";
        }
        return htmlwrap($text, $length, " ", true);
    }
    return htmlwrap($text, $length, " ", true);
    while ($i <= $str_length) {
        $skip = 0;
        $char = substr($text, $i, 1);
        if ($char == "<" || $char == "&") {
            $skip = 1;
        } else if ($char == ">" || $char == ";") {
            $skip = 0;
        } else if ($char == " ") {
            $wrap = 0;
        } else if ($skip == 0) {
            $wrap = $wrap + 1;
        }
        $returnvar = $returnvar . $char;
        if ($length < $wrap) {
            $returnvar = $returnvar . " ";
            $wrap      = 0;
        }
        $i = $i + 1;
    }
    return $returnvar;
}

function directory_map($source_dir, $top_level_only = FALSE)
{
    if ($fp = @opendir($source_dir)) {
        $filedata = array();
        while (FALSE !== ($file = readdir($fp))) {
            if (@is_dir($source_dir . $file) && substr($file, 0, 1) != "." && $top_level_only == FALSE) {
                $temp_array      = array();
                $temp_array      = directory_map($source_dir . $file . "/");
                $filedata[$file] = $temp_array;
            } else if (substr($file, 0, 1) != ".") {
                $filedata[] = $file;
            }
        }
        return $filedata;
    }
}

function read_file($file)
{
    if (!file_exists($file)) {
        return FALSE;
    }
    if (function_exists("file_get_contents")) {
        return file_get_contents($file);
    }
    if (!($fp = @fopen($file, "rb"))) {
        return FALSE;
    }
    flock($fp, LOCK_SH);
    $data = "";
    if (0 < filesize($file)) {
        $data =& fread($fp, filesize($file));
    }
    flock($fp, LOCK_UN);
    fclose($fp);
    return $data;
}

function write_file($path, $data, $mode = "w+")
{
    if (!($fp = @fopen($path, $mode))) {
        return FALSE;
    }
    flock($fp, LOCK_EX);
    fwrite($fp, $data);
    @chmod($path, 511);
    flock($fp, LOCK_UN);
    fclose($fp);
    return TRUE;
}

function readDirectory($dir_path, $return = "both")
{
    $return_arr = array();
    if ($handle = opendir($dir_path)) {
        while (false !== ($file = readdir($handle))) {
            if (!($file != "." && $file != ".." && $file != ".svn") && !(is_file($dir_path . $file) && $return == "file" || is_dir($dir_path . $file) && $return == "dir" || $return == "both")) {
                $return_arr[] = $file;
            }
        }
        closedir($handle);
    }
    return $return_arr;
}

function force_download($filename = "", $data = "")
{
    global $CFG;
    if ($filename == "" || $data == "") {
        return FALSE;
    }
    if (FALSE === strpos($filename, ".")) {
        return FALSE;
    }
    $x         = explode(".", $filename);
    $extension = end($x);
    @include($CFG['site']['project_path'] . "common/configs/config_mimes.inc..php");
    if (!isset($mimes[$extension])) {
        $mime = "application/octet-stream";
    } else {
        $mime = is_array($mimes[$extension]) ? $mimes[$extension][0] : $mimes[$extension];
    }
    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
        header("Content-Type: \"" . $mime . "\"");
        header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Transfer-Encoding: binary");
        header("Pragma: public");
        header("Content-Length: " . strlen($data));
    } else {
        header("Content-Type: \"" . $mime . "\"");
        header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
        header("Content-Transfer-Encoding: binary");
        header("Expires: 0");
        header("Pragma: no-cache");
        header("Content-Length: " . strlen($data));
    }
    echo $data;
}

function strip_slashes($str)
{
    if (is_array($str)) {
        foreach ($str as $key => $val) {
            $str[$key] = strip_slashes($val);
        }
    } else {
        $str = stripslashes($str);
    }
    return $str;
}

function isCronRunning($script_name = "")
{
    $max_cron_allowed = 1;
    $cronRunning      = false;
    if ($script_name) {
        $command          = " ps -eaf | grep " . $script_name;
        $result           = @shell_exec($command);
        $scriptCount      = intval(@substr_count($result, $script_name));
        $max_cron_allowed = $max_cron_allowed + 3;
        $cronRunning      = $max_cron_allowed <= $scriptCount;
    }
    return $cronRunning;
}

function callMultipleCronCheck()
{
    global $CFG;
    $cronUrl = $CFG['site']['current_url'];
    $time    = date("d-m-y H:i:s");
    print "\n CRON:\t{$cronUrl}:\nTIME:{$time}\n";
    if (iscronrunning($cronUrl)) {
        print "CRON : {$cronUrl}\nTIME:{$cronUrl}\nConcurrent Process Detected\nSo Skipping " . $cronUrl . " CRON at " . date("d-M-y H:i:s") . "\n\n";
        exit();
    }
}

function getMD5Text($text, $count = 15)
{
    $text = md5($text);
    return substr($text, 0, $count - 1);
}

function doEncode($text, $size = 0)
{
    $text = str_pad($text, $size, "0", STR_PAD_LEFT);
    $text = base64_encode($text);
    $text = urlencode($text);
    return $text;
}

function doDecode($text)
{
    $text = urldecode($text);
    $text = base64_decode($text);
    return $text;
}

function getTimeDiffInSeconds($date)
{
    global $CFG;
    global $db;
    $sql  = "SELECT TIMEDIFF(NOW(), '" . $date . "') AS date_added";
    $stmt = $db->Prepare($sql);
    $rs   = $db->Execute($stmt);
    if (!$rs) {
        trigger_db_error($db);
    }
    $row = $rs->FetchRow();
    return $row['date_added'];
}

function getTimeDiffernce($timeStamp = "")
{
    global $LANG;
    $time_arr = getTimeLeftArray($timeStamp);
    $day      = $time_arr[0];
    $hour     = $time_arr[1];
    $minute   = $time_arr[2];
    $seconds  = $time_arr[3];
    if ($day) {
        if (365 <= $day) {
            $year = floor($day / 365);
            if (1 < $year) {
                $time = $year . " " . $LANG['years_ago'];
            } else {
                $time = $year . " " . $LANG['year_ago'];
            }
        } else if (30 < $day) {
            $month = floor($day / 30);
            if (1 < $month) {
                $time = $month . " " . $LANG['months_ago'];
            } else {
                $time = $month . " " . $LANG['month_ago'];
            }
        } else if (1 < $day) {
            $time = $day . " " . $LANG['days_ago'];
        } else {
            $time = $day . " " . $LANG['day_ago'];
        }
    } else if ($hour) {
        if (1 < $hour) {
            $time = $hour . " " . $LANG['hours_ago'];
        } else {
            $time = $hour . " " . $LANG['hour_ago'];
        }
    } else if ($minute) {
        if (1 < $minute) {
            $time = $minute . " " . $LANG['minutes_ago'];
        } else {
            $time = $minute . " " . $LANG['minute_ago'];
        }
    } else if (1 < $seconds) {
        $time = $seconds . " " . $LANG['seconds_ago'];
    } else {
        $time = $seconds . " " . $LANG['second_ago'];
    }
    return $time;
}

function getTimeLeftArray($endtime = null)
{
    $time_left = 0;
    if ($endtime != null) {
        $time_left = time() - $endtime;
    }
    if (0 < $time_left) {
        $days      = floor($time_left / 86400);
        $time_left = $time_left - $days * 86400;
        $hours     = floor($time_left / 3600);
        $time_left = $time_left - $hours * 3600;
        $minutes   = floor($time_left / 60);
        $seconds   = $time_left - $minutes * 60;
    } else {
        return array(
            0,
            0,
            0,
            0
        );
    }
    return array(
        $days,
        $hours,
        $minutes,
        $seconds
    );
}

function str_replace_once($needle, $replace, $haystack)
{
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}

function getFullTextSearchString($tags)
{
    $tags = rawurlencode($tags);
    return $tags = "[[:<:]]" . preg_replace("/\\s+/", "|", addslashes($tags)) . "[[:>:]]";
    while (strpos($tags, "  ")) {
        $tags = str_replace("  ", " ", $tags);
    }
    $tags     = addslashes($tags);
    $tags_arr = explode(" ", $tags);
    $tags     = "[[:<:]]" . implode("[[:>:]]|[[:<:]]", $tags_arr) . "[[:>:]]";
    return $tags;
}

function formatSearchString($tags)
{
    $tags           = trim($tags);
    $tags_count_arr = explode(" ", $tags);
    $tags_count     = 0;
    foreach ($tags_count_arr as $tagvalue) {
        if (trim($tagvalue)) {
            ++$tags_count;
        }
    }
    if (1 < $tags_count) {
        return $tags = "[[:<:]]" . preg_replace("/\\s+/", "|", $tags) . "[[:>:]]";
    }
    return $tags = "[[:<:]]" . $tags . "|" . $tags . "[[:>:]]";
}

function replaceCharacter($search_value, $replace, $text)
{
    if (is_array($search_value)) {
        foreach ($search_value as $key => $value) {
            $text = str_replace($value, $replace, $text);
        }
        return $text;
    }
    return str_replace($char, $replace, $text);
}

function getSearchRegularExpressionQuery($tags, $field_name, $extra = "")
{
    global $CFG;
    $not_allowed_search_array = $CFG['admin']['not_allowed_chars'];
    $tags                     = replacecharacter($not_allowed_search_array, "-", $tags);
    $tags                     = addslashes($tags);
    $additional_query         = " (" . $field_name . " REGEXP '" . formatsearchstring($tags) . "') " . $extra . " ";
    return $additional_query;
}

function createMultiLevelFolder($folderName)
{
    $folder_arr = explode("/", $folderName);
    $folderName = "";
    foreach ($folder_arr as $key => $value) {
        $folderName .= $value . "/";
        if ($value == ".." || $value == ".") {
            continue;
        }
        if (!is_dir($folderName)) {
            mkdir($folderName);
            @chmod($folderName, 511);
        }
    }
}

function removeDirectory($dirname)
{
    if (is_dir($dirname)) {
        $result = array();
        if (substr($dirname, 0 - 1) != "/") {
            $dirname .= "/";
        }
        $handle = opendir($dirname);
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $path = $dirname . $file;
                if (is_dir($path)) {
                    $result = array_merge($result, removeDirectory($path));
                } else {
                    unlink($path);
                }
            }
        }
        closedir($handle);
        rmdir($dirname);
        return $result;
    }
    return false;
}

function setHeaderStart()
{
    global $CFG;
    ob_start();
    header("Pragma: no-cache");
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: 0");
    header("Content-type: text/css; charset=\"" . $CFG['site']['charset'] . "\"");
}

function setHeaderEnd()
{
    ob_end_flush();
}

function chkIsValidUrlUsingCurl($url)
{
    if (!strstr($url, "://")) {
        $url = "http://" . $url;
    }
    if (function_exists("curl_init")) {
        $ch = @curl_init();
        if ($ch) {
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_NOBODY, 1);
            curl_setopt($ch, CURLOPT_RANGE, "0-1");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $result = curl_exec($ch);
            $errno  = curl_errno($ch);
            curl_close($ch);
            if ($errno != 0) {
                return false;
            }
        }
    }
    return true;
}

function setFontSizeForTagCloud($tag_array = array())
{
    $formattedArray = $tag_array;
    $max_qty        = max(array_values($formattedArray));
    $min_qty        = min(array_values($formattedArray));
    $max_font_size  = 28;
    $min_font_size  = 12;
    $spread         = $max_qty - $min_qty;
    if (0 == $spread) {
        $spread = 1;
    }
    $step = ($max_font_size - $min_font_size) / $spread;
    foreach ($tag_array as $catname => $count) {
        $size                     = $min_font_size + ($count - $min_qty) * $step;
        $formattedArray[$catname] = ceil($size);
    }
    return $formattedArray;
}

function setTemplateFolder($template_for = "", $module = "")
{
    global $smartyObj;
    global $CFG;
    if ($module) {
        if ($template_for == "admin/") {
            $smartyObj->template_dir = $CFG['site']['project_path'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for . $module . "/";
            $smartyObj->compile_dir  = $CFG['site']['project_path'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . getTplFolder() . $module . "/templates_c/";
            $smartyObj->css_path     = $CFG['site']['url'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for . "/css/" . $CFG['html']['stylesheet']['screen']['default'] . "/";
        } else {
            if (isAdmin()) {
                $smartyObj->template_dir = $CFG['site']['project_path'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for;
                $smartyObj->compile_dir  = $CFG['site']['project_path'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/members/templates_c/";
                $smartyObj->css_path     = $CFG['site']['url'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for . "css/" . $CFG['html']['stylesheet']['screen']['default'] . "/";
            } else {
                $smartyObj->template_dir = $CFG['site']['project_path'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for;
                $smartyObj->compile_dir  = $CFG['site']['project_path'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/" . getTplFolder() . "templates_c/";
                $smartyObj->css_path     = $CFG['site']['url'] . $module . "/design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for . "css/" . $CFG['html']['stylesheet']['screen']['default'] . "/";
            }
            if (!is_dir($smartyObj->template_dir)) {
                foreach ($CFG['html']['template']['allowed'] as $available_template) {
                    $available_template_dir = $CFG['site']['project_path'] . $module . "/design/templates/" . $available_template . "/" . $template_for;
                    if (is_dir($available_template_dir)) {
                        foreach ($CFG['html']['stylesheet'][$available_template]['allowed'] as $available_css) {
                            $available_css_path = $CFG['site']['project_path'] . $module . "/design/templates/" . $available_template . "/root/css/" . $available_css . "/";
                            if (!is_dir($available_css_path)) {
                                continue;
                            }
                            $smartyObj->template_dir = $available_template_dir;
                            $smartyObj->compile_dir  = $CFG['site']['project_path'] . $module . "/design/templates/" . $available_template . "/" . getTplFolder() . "templates_c/";
                            $smartyObj->css_path     = $CFG['site']['url'] . $module . "/design/templates/" . $available_template . "/" . $template_for . "css/" . $available_css . "/";
                            break;
                            break;
                        }
                    }
                }
            }
        }
    } else {
        $smartyObj->template_dir = $CFG['site']['project_path'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for;
        $smartyObj->compile_dir  = $CFG['site']['project_path'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . getTplFolder() . "templates_c/";
        $smartyObj->css_path     = $CFG['site']['url'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for . "css/" . $CFG['html']['stylesheet']['screen']['default'] . "/";
        if (isset($CFG['site']['is_module_page']) && !empty($CFG['site']['is_module_page'])) {
            $template_dir_module = $CFG['site']['project_path'] . $CFG['site']['is_module_page'] . "/design/templates/" . $CFG['html']['template']['default'] . "/" . $template_for;
            if (!is_dir($template_dir_module)) {
                foreach ($CFG['html']['template']['allowed'] as $available_template) {
                    $available_template_dir = $CFG['site']['project_path'] . $CFG['site']['is_module_page'] . "/design/templates/" . $available_template . "/" . $template_for;
                    if (is_dir($available_template_dir)) {
                        $CFG['html']['template']['default'] = $available_template;
                        foreach ($CFG['html']['stylesheet'][$available_template]['allowed'] as $available_css) {
                            $available_css_path = $CFG['site']['project_path'] . $CFG['site']['is_module_page'] . "/design/templates/" . $available_template . "/root/css/" . $available_css . "/";
                            if (!is_dir($available_css_path)) {
                                continue;
                            }
                            $CFG['html']['stylesheet']['screen']['default'] = $available_css;
                            $smartyObj->template_dir                        = $CFG['site']['project_path'] . "design/templates/" . $available_template . "/" . $template_for;
                            $smartyObj->compile_dir                         = $CFG['site']['project_path'] . "design/templates/" . $available_template . "/" . getTplFolder() . "templates_c/";
                            $smartyObj->css_path                            = $CFG['site']['url'] . "design/templates/" . $available_template . "/" . $template_for . "css/" . $available_css . "/";
                            break;
                            break;
                        }
                    }
                }
            }
        }
    }
    $smartyObj->cache_dir = $CFG['site']['project_path'] . "design/templates/" . $CFG['html']['template']['default'] . "/" . getTplFolder() . "cache/";
    $image_path           = $CFG['site']['url'] . "design/templates/" . $CFG['html']['template']['default'] . "/root/images/" . $CFG['html']['stylesheet']['screen']['default'] . "/";
    $smartyObj->assign("html_stylesheet", $smartyObj->css_path . $CFG['html']['stylesheet']['screen']['default_file'] . ".css");
    $smartyObj->css_defalut_path = $smartyObj->css_path . $CFG['html']['stylesheet']['screen']['default_file'] . ".css";
    $smartyObj->assign("images_path", $image_path);
    $smartyObj->assign("html_stylesheet_path", $smartyObj->css_path);
}

function URL($url)
{
    return $url;
}

function isAjaxPage()
{
    return isset($_REQUEST['ajax_page']) && $_REQUEST['ajax_page'] == true || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest";
}

function isAjax()
{
    return isset($_REQUEST['ajax_page']) && $_REQUEST['ajax_page'] == true || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest";
}

function ShowHelpTip($tip_key, $tipfor = "")
{
    global $LANG;
    global $CFG;
    $tipfor = $tipfor ? $tipfor : $tip_key;
    $tip    = str_replace("\n", "&#13;", $LANG['help'][$tip_key]);
    echo "<div class=\"clsHelpText\" id=\"";
    echo $tipfor;
    echo "_Help\" style=\"visibility:hidden\">";
    echo $tip;
    echo "</div>\r\n";
}

function FMT_DATE($date)
{
    return $date;
}

function ExposeQuery($msg, $newline = "")
{
    global $SQL_QUERIES;
    $SQL_QUERIES .= "\n" . $msg . "\n";
}

function DEBUG($var_name, $var_desc = "")
{
    global $CFG;
    global $DEBUG_TRACE;
    if ($CFG['debug']['is_debug_mode']) {
        $DEBUG_TRACE .= "\n" . $var_desc . ":";
        if (!is_array($var_name)) {
            $var_name = htmlspecialchars($var_name);
        }
        $DEBUG_TRACE .= print_r($var_name, true);
        if (is_array($var_name)) {
            reset($var_name);
        }
        $DEBUG_TRACE .= "\n";
    }
}

function Redirect2URL($url)
{
    if (!headers_sent()) {
        header("Location: " . url($url));
        if (stristr($_SERVER['SERVER_SIGNATURE'], "IIS")) {
            header("Refresh: 0;url=" . $url);
        }
    } else {
        trigger_error("Headers already sent", E_USER_NOTICE);
        echo "<meta http-equiv=\"refresh\" content=\"0; URL=" . url($url) . "\" />" . "\n";
        echo "<p>Please click this <a href=\"" . url($url) . "\">link</a> to continue...</p>" . "\n";
    }
    exit(0);
}

function RedirectAjaxPage()
{
    global $CFG;
    if ($CFG['is']['ajax_page']) {
        $url = $CFG['auth']['ajax_url'];
    } else {
        $url = getUrl($CFG['auth']['login_url']['file_name'], "", "", "root");
    }
    return $url;
}

function htmlentitydecode($text)
{
    global $CFG;
    $default_charset   = strtolower($CFG['site']['charset']);
    $allwable_charsets = array(
        "iso-8859-1",
        "iso-8859-15",
        "utf-8",
        "cp866",
        "cp1251",
        "cp1252",
        "koi8-r",
        "big5",
        "gb2312",
        "big5-hkscs",
        "shift_jis",
        "euc-jp",
        "iso8859-1",
        "iso8859-15",
        "ibm866",
        "866",
        "windows-1251",
        "win-1251",
        "1251",
        "windows-1252",
        "1252",
        "koi8-ru",
        "koi8r",
        "950",
        "936",
        "sjis",
        "932",
        "eucjp"
    );
    if (in_array($default_charset, $allwable_charsets)) {
        $charset = $CFG['site']['charset'];
    } else {
        $charset = "ISO-8859-1";
    }
    return html_entity_decode($text, ENT_QUOTES, $charset);
}

function isNoPlansAvailable()
{
    global $CFG;
    global $db;
    $sql  = "SELECT plan_id FROM " . $CFG['db']['tbl']['payment_plan_settings'] . " WHERE plan_status = 'Yes'";
    $stmt = $db->Prepare($sql);
    $rs   = $db->Execute($stmt);
    if (!$rs) {
        trigger_db_error($db);
    }
    if ($rs->PO_RecordCount()) {
        return false;
    }
    return true;
}

function getCleanUrl($url)
{
    global $CFG;
    if ($CFG['feature']['rewrite_mode'] == "clean") {
        $url = str_replace("&amp;", "/", $url);
        $url = str_replace("?", "/", $url);
        $url = str_replace("&", "/", $url);
        $url = str_replace("=", "/", $url);
    }
    return $url;
}

function populateGETValue()
{
    global $CFG;
    if ($CFG['feature']['rewrite_mode'] == "clean" && $CFG['site']['query_string']) {
        $query_string = getcleanurl($CFG['site']['query_string']);
        if (strpos($query_string, "/") === 0) {
            $query_string = substr($query_string, 1);
        }
        if (strrpos($query_string, "/") == strlen($query_string) - 1) {
            $query_string = substr($query_string, 0, strlen($query_string) - 1);
        }
        $query_string_arr = explode("/", $query_string);
        $i                = 0;
        while ($i < sizeof($query_string_arr)) {
            $_REQUEST[$query_string_arr[$i]] = $_GET[$query_string_arr[$i]] = isset($query_string_arr[$i + 1]) ? $query_string_arr[$i + 1] : "";
            $i                               = $i + 2;
        }
    }
}

function getUrl($file_name, $normal = "", $htaccess = "", $change = "", $module = "")
{
    global $CFG;
    global $folder_names_arr;
    if ($module == $CFG['admin']['index']['anova_module'] && $CFG['feature']['rewrite_mode'] != "normal") {
        $module = "";
    }
    $relativeUrl = "";
    if (!$change) {
        $change = "current";
    }
    if (!proceeedSite()) {
        return $CFG['site']['url'] . "install.php";
    }
    $normal   = $CFG['page_url'][$file_name]['normal'] . $normal;
    $htaccess = $CFG['page_url'][$file_name]['htaccess'] . $htaccess;
    if ($CFG['feature']['rewrite_mode'] == "clean") {
        $normal = getcleanurl($normal);
    }
    if ($CFG['feature']['rewrite_mode'] == "htaccess") {
        if (strrpos($htaccess, "/") == strlen($htaccess) - 1 && $htaccess != $CFG['site']['url'] && $htaccess != $CFG['site']['url'] . "/members/" && $htaccess != $CFG['site']['url'] . "/admin/") {
            $htaccess = substr($htaccess, 0, strrpos($htaccess, "/")) . $CFG['feature']['rewrite_mode_endwith'];
        }
        $htaccess = str_replace("/?", ".html?", $htaccess);
        $htaccess = str_replace("/&", ".html&", $htaccess);
    }
    if ($module) {
        if ($CFG['site']['relative_url'] == $CFG['site']['url']) {
            $relativeUrl = $CFG['site']['url'] . $module . "/";
        }
        foreach ($folder_names_arr as $folder) {
            if (!($CFG['site']['relative_url'] == $CFG['site']['url'] . $folder)) {
                continue;
            }
            $relativeUrl = $CFG['site']['url'] . $module . "/" . $folder;
            break;
            break;
        }
        foreach ($CFG['site']['modules_arr'] as $mod) {
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/") {
                $relativeUrl = $CFG['site']['url'] . $module . "/";
                break;
            }
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/members/") {
                $relativeUrl = $CFG['site']['url'] . $module . "/members/";
                break;
            }
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/rss/") {
                $relativeUrl = $CFG['site']['url'] . $module . "/rss/";
                break;
            }
            if (!($CFG['site']['relative_url'] == $CFG['site']['url'] . "admin/" . $mod . "/")) {
                continue;
            }
            $relativeUrl = $CFG['site']['url'] . "admin/" . $module . "/";
            break;
            break;
        }
        $siteUrl = $CFG['site']['url'] . $module . "/";
    } else {
        foreach ($CFG['site']['modules_arr'] as $mod) {
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/") {
                $CFG['site']['relative_url'] = $CFG['site']['url'];
            }
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/members/") {
                $relativeUrl = $CFG['site']['url'] . "members/";
                break;
            }
            if ($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/rss/") {
                $relativeUrl = $CFG['site']['url'] . "rss/";
                break;
            }
            if (!($CFG['site']['relative_url'] == $CFG['site']['url'] . $mod . "/admin/")) {
                continue;
            }
            $relativeUrl = $CFG['site']['url'] . "admin/";
            break;
            break;
        }
        $siteUrl = $CFG['site']['url'];
    }
    if (!$relativeUrl) {
        $relativeUrl = $CFG['site']['relative_url'];
        $siteUrl     = $CFG['site']['url'];
    }
    switch ($change) {
    case "current":
        if ($CFG['feature']['rewrite_mode'] == "htaccess") {
            return $relativeUrl . $htaccess;
        }
        return $relativeUrl . $normal;
    case "root":
    case "members":
        if ($CFG['feature']['rewrite_mode'] == "htaccess") {
            return $siteUrl . $htaccess;
        }
        return $siteUrl . $normal;
    case "admin":
        if ($CFG['feature']['rewrite_mode'] == "htaccess") {
            return $siteUrl . "admin/" . $htaccess;
        }
        return $siteUrl . "admin/" . $normal;
    case "nothing":
        if ($CFG['feature']['rewrite_mode'] == "htaccess") {
            return $htaccess;
        }
        return $normal;
    }
}

function getCurrentUrl($with_query_string = false)
{
    global $CFG;
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    if (!$with_query_string) {
        if (strpos($url, "?")) {
            $url = substr($url, 0, strpos($url, "?"));
        }
        if (strpos($url, ".php")) {
            $url = substr($url, 0, strpos($url, ".php") + 4);
        }
    }
    return $url;
}

function chkAllowedModule($module_arr = array())
{
    global $CFG;
    foreach ($module_arr as $key => $value) {
        if (!(!isset($CFG['admin']['module'][$value]) || !$CFG['admin']['module'][$value])) {
            continue;
        }
        return false;
    }
    return true;
}

function isMember()
{
    if (isset($_SESSION['user']['user_id']) && $_SESSION['user']['user_id']) {
        return true;
    }
    return false;
}

function isAdmin()
{
    if (isset($_SESSION['user']['user_id']) && $_SESSION['user']['user_id'] && (isset($_SESSION['user']['is_admin']) && $_SESSION['user']['is_admin'])) {
        return true;
    }
    return false;
}

function displayBlock($allowed_pages = array(), $reverse = false)
{
    global $CFG;
    $REQUEST_UNAME = isset($_REQUEST['uname']) ? $_REQUEST['uname'] : isset($CFG['user']['name']) ? $CFG['user']['name'] : "";
    $script_name   = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    if (!$reverse) {
        if (in_array($script_name, $allowed_pages)) {
            return true;
        }
        return false;
    }
    if (!in_array($script_name, $allowed_pages)) {
        return true;
    }
    return false;
}

function makeClickableLinks($text)
{
    $text = eregi_replace("(([[:space:]()[{}])|^)(http://[-a-zA-Z0-9@:%_\\+.~#?&//=]+)(([[:space:]()[{}])|\$)", "\\1<a href=\"\\3\">\\3</a>", $text);
    $text = eregi_replace("(([[:space:]()[{}])|^)(https://[-a-zA-Z0-9@:%_\\+.~#?&//=]+)(([[:space:]()[{}])|\$)", "\\1<a href=\"\\3\">\\3</a>", $text);
    $text = eregi_replace("(([[:space:]()[{}])|^)(www.[-a-zA-Z0-9@:%_\\+.~#?&//=]+)(([[:space:]()[{}])|\$)", "\\1<a href=\"http://\\3\">\\3</a>", $text);
    $text = eregi_replace("([_\\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\\.)+[a-z]{2,3})", "<a href=\"mailto:\\1\">\\1</a>", $text);
    return $text;
}

function dbConnect()
{
    global $db;
    global $CFG;
    $db->Connect($CFG['db']['hostname'], $CFG['db']['username'], $CFG['db']['password'], $CFG['db']['name']);
    if (!$db) {
        trigger_error("DB Connection Error", E_USER_ERROR);
    }
}

function dbDisconnect()
{
    global $db;
    global $CFG;
    $db->Disconnect();
}

function getUserDisplayName($user_fields_arr)
{
    global $db;
    global $CFG;
    $user_fields_arr['display_name'] = isset($user_fields_arr['display_name']) ? $user_fields_arr['display_name'] : "";
    return stripString(trim($user_fields_arr['display_name']), $CFG['username']['short_length']);
}

function getUserMailName($user_fields_arr)
{
    global $db;
    global $CFG;
    $user_fields_arr['name'] = isset($user_fields_arr['name']) ? $user_fields_arr['name'] : "";
    return trim($user_fields_arr['name']);
}

function populateRichTextEdit($field_name = "", $value = "", $useHtmlSpChars = true)
{
    global $CFG;
    global $LANG;
    global $EDITOR_LANG;
    $param            = $CFG['site']['name'] . "page";
    $_SESSION[$param] = urlencode($value);
    echo "\t";
    echo "<script language=\"JavaScript\" type=\"text/javascript\" src=\"";
    echo $CFG['site']['url'];
    echo "js/richtext.js\"></script>\r\n\t";
    echo "<script language=\"JavaScript\" type=\"text/javascript\">\r\n\t\tvar palette_url = '";
    echo $CFG['site']['url'] . "editor/palette.htm";
    echo "';\r\n\t\tvar field_name = '";
    echo $field_name;
    echo "';\r\n\t\t";
    echo "var EDITOR_LANG = " . php2js($EDITOR_LANG);
    echo ";\r\n\t\tvar filenameNew = \"";
    echo $CFG['site']['url'];
    echo "richText.php?htmSpChar=";
    echo $useHtmlSpChars ? 1 : 0;
    echo "&source=";
    echo $param;
    echo "\";\r\n\t\tfunction submitForm() {\r\n\t\t\tupdateRTE('rte1');\r\n\t\t\talert(\"rte1 = \" + document.RTEDemo.rte1.value);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tinitRTE(\"";
    echo $CFG['site']['url'];
    echo "editor/images/\", \"";
    echo $CFG['site']['url'] . "editor/";
    echo "\", \"\");\r\n\t</script>\r\n\t<noscript><p><b>";
    echo $LANG['javascript_enabled'];
    echo "</b></p></noscript>\r\n\t";
    echo "<script language=\"JavaScript\" type=\"text/javascript\">\r\n\t\tif(!b.isFirefox())\r\n\t\t\t{\r\n\t\t\t\twriteRichText('rte1', '', 400, 200, true, false);\r\n\t\t\t}\r\n\t</script>\r\n\t";
    if ($useHtmlSpChars) {
        $value = htmlspecialchars($value);
    }
    echo "\t<input type=\"hidden\" id=\"";
    echo $field_name;
    echo "\" name=\"";
    echo $field_name;
    echo "\" value=\"";
    echo $value;
    echo "\" />\r\n\t";
    echo "<script language=\"JavaScript\" type=\"text/javascript\">\r\n\t\tif(b.isFirefox())\r\n\t\t\t{\r\n\t\t\t\twriteRichText('rte1', '', 400, 200, true, false);\r\n\t\t\t}\r\n\t</script>\r\n";
}

function writeLog($file_name, $data)
{
    global $CFG;
    if ($CFG['feature']['log']) {
        $path      = $CFG['site']['project_path'] . "files/logs/" . $file_name;
        $seperator = "\n--------------------------------------------------------------------\n\n";
        $data      = date("Y-m-d H:i:s") . "\n.....................\n" . $data . $seperator;
        write_file($path, $data, "a+");
    }
}

function isMemberShipValid($date)
{
    global $db;
    global $CFG;
    $sql  = "SELECT NOW()<'" . $date . "' AS date_diff";
    $stmt = $db->Prepare($sql);
    $rs   = $db->Execute($stmt);
    if (!$rs) {
        trigger_db_error($db);
    }
    $row = $rs->FetchRow();
    return $row['date_diff'];
}

function to7bit($text)
{
    global $CFG;
    $text = mb_convert_encoding($text, "HTML-ENTITIES", $CFG['site']['charset']);
    $text = preg_replace(array(
        "/&szlig;/",
        "/&(..)lig;/",
        "/&([aouAOU])uml;/",
        "/&(.)[^;]*;/"
    ), array(
        "ss",
        "\$1",
        "\$1" . "e",
        "\$1"
    ), $text);
    return $text;
}

function getUrlTitle($text)
{
    $text = to7bit($text);
    $text = ereg_replace("[^a-zA-Z0-9]", "_", $text);
    return $text;
}

function stripString($text, $length = 25)
{
    global $CFG;
    if (!$CFG['feature']['wrap_content']) {
        return $text;
    }
    if ($length < utf8_strlen($text)) {
        $text = utf8_substr($text, 0, $length - 3) . "...";
    }
    return $text;
}

function getUserLevelClass($points)
{
    global $CFG;
    if ($CFG['user']['level_six']['points'] <= $points) {
        $userLevelClass = "clsLevelSix";
    } else if ($CFG['user']['level_five']['points'] <= $points) {
        $userLevelClass = "clsLevelFive";
    } else if ($CFG['user']['level_four']['points'] <= $points) {
        $userLevelClass = "clsLevelFour";
    } else if ($CFG['user']['level_three']['points'] <= $points) {
        $userLevelClass = "clsLevelThree";
    } else if ($CFG['user']['level_two']['points'] <= $points) {
        $userLevelClass = "clsLevelTwo";
    } else {
        $userLevelClass = "clsLevelOne";
    }
    return $userLevelClass;
}

function ShowToolTip($tip_key = "")
{
}

function seoFriendlyText($text, $from_enc)
{
    $charsToRemove = array(
        "~",
        "`",
        "@",
        "#",
        "\$",
        "%",
        "^",
        "&amp;",
        "*",
        "(",
        ")",
        "_",
        "+",
        "=",
        "{",
        "[",
        "}",
        "]",
        ":",
        "&quot;",
        "'",
        "|",
        "\\",
        "&lt;",
        ",",
        "&gt;",
        ".",
        "?",
        "/",
        "!",
        ";",
        " "
    );
    $text          = str_replace($charsToRemove, "-", $text);
    return $text;
}

function isFireFox()
{
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (eregi("(Firebird)|(Firefox)", $userAgent)) {
        return true;
    }
    return false;
}

function isMacOs()
{
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (eregi("(Mac_PowerPC)|(Macintosh)", $userAgent)) {
        return true;
    }
    return false;
}

function getContents($url)
{
    $result = "";
    if (!strstr($url, "://")) {
        $url = "http://" . $url;
    }
    if (function_exists("curl_init")) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (!curl_errno($ch)) {
            curl_close($ch);
        } else {
            $result = false;
        }
    } else {
        set_time_limit(180);
        $result = file_get_contents($url);
    }
    return $result;
}

function postForm($url, $post_value)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_value);
    $result = curl_exec($ch);
    curl_close($ch);
}

function setPageTitle($title)
{
    global $LANG;
    global $CFG;
    $currentPage = strtolower($CFG['html']['current_script_name']);
    if (isset($LANG["meta_" . $currentPage . "_title"])) {
        $LANG["meta_" . $currentPage . "_title"] = $title;
    } else {
        $LANG["meta_" . $currentPage . "_title"] = $title;
    }
}

function getKeyValuePair($toKeyValArr)
{
    $str_transLog = "";
    if ($toKeyValArr) {
        foreach ($toKeyValArr as $field => $value) {
            $str_transLog .= $field . "=" . urlencode(stripslashes($value)) . "&";
        }
    } else {
        $str_transLog = "";
    }
    return $str_transLog;
}

populategetvalue();
include_once($CFG['site']['project_path'] . "common/functions_customize.php");
?>