<?php
/*
+-----------------------------------------------------------------------------+
| $Id: function.php 2009-10-12 11:21:34Z Bleakwind $
| Global function
| Copyright (c) 2003-2010 Bleakwind (www.weaverdream.com)
| http://www.weaverdream.com/
| Release under the GNU Lesser General Public License Version 3 (LGPLv3):
|   http://www.gnu.org/licenses/lgpl.html
+-----------------------------------------------------------------------------+
*/

class func
{

    // Return file data
    function read_file($filename, $degree = 1)
    {
        $contents = @file_get_contents($filename);
        $i = 1;
        while( false ===  $contents) {
            if ( ($i < $degree) || $degree == "*") {
                $contents = @file_get_contents($filename);
            } else {
                break;
            }
        }
        return $contents;
    }

    // Put the data into file
    function write_file($filename, $data, $mode="rb+")
    {
        touch($filename);
        $handle = fopen($filename, $mode);
        flock($handle, LOCK_EX);
        $fettle = fwrite($handle, $data);
        if ($mode == "rb+") {ftruncate($handle, strlen($data));}
        fclose($handle);
        return $fettle;
    }

    // Clean value
    function clean_value($val,$strip=false)
    {
        if ( get_magic_quotes_gpc() ) {
            $val = stripslashes($val);
        }
        if ($strip === true) {
            $val = strip_tags($val);
            $val = strtolower($val);
            $val = trim($val);
        }
        return $val;
    }

    // Cut a string
    function str_cut($string, $start, $width="", $trimmarker="", $encoding="UTF-8")
    {
        if ($width == "") {
            $width = mb_strwidth($string,"UTF-8");
        }
        return mb_strimwidth($string, $start, $width, $trimmarker, $encoding);
    }

    // Rand a rand string
    function str_rand($len, $except=array("l","1","o","0","s","5"))
    {
        $str   = "";
        $array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
        foreach($except as $value) {
            unset($array[array_search($value, $array)]);
        }
        $key = array_rand($array,$len);
        for ($i=0;$i<$len;$i++) {
            $str .= $array[$key[$i]];
        }
        return $str;
    }

    // Encrypt the string
    function str_encrypt($str, $mix = "", $len = 40)
    {
        if ( $mix != "" ) {
            $mix_str = sha1($mix);
        } else {
            $mix_str = "385fa818765bcf363e6de0a13aecb90ddc68cd6a";
        }
        $encrypt = "";
        $str     = sha1($str);
        $str     = substr($str, 0, 20).trim($mix_str).substr($str, -20);
        $str     = sha1($str);
        for ($i=0;$i<$len;$i++) {
            $encrypt .= $str{$i%40};
        }
        return $encrypt;
    }

    // Return length str
    function return_lenstr($str, $len=0)
    {
        if ($len == 0) {
            $str_new = $str;
        } else {
            $str_len = strlen($str);
            for ($i=0;$i<$len;$i++) {
                $str_new .= $str{$i%$str_len};
            }
        }
        return $str_new;
    }

    // Return a 16 color to a 10 color
    function color_hexdec($color)
    {
        $color = substr(trim($color), 0, 1) == "#" ? substr(trim($color), 1) : trim($color);
        if (!preg_match("/^[a-z0-9]{6}$/i",$color)) {
            return false;
        } else {
            $color_array[0] = hexdec(substr($color,0,2));
            $color_array[1] = hexdec(substr($color,2,2));
            $color_array[2] = hexdec(substr($color,4,2));
            return $color_array;
        }
    }

    // clean array
    function array_clean($var)
    {
        foreach($var as $k => $v) {
            if (!empty($v)) {
                $array[$k] = $v;
            }
        }
        return $array;
    }

    // Read dir to list
    function return_dir($directory, $except_list = null)
    {
        if (!empty($except_list)) {
            if (!is_array($except_list)) { $except_list = explode(",", $except_list); }
        }
        $file_list = array();
        if ($handle = opendir($directory)) {
            while (false !== ($file = readdir($handle))) {
                if ( ($file != ".") && ($file != "..") ) {
                    if (!empty($except_list)) {
                        if (!in_array($file,$except_list)) {
                            $file_list[] = $file;
                        }
                    } else {
                        $file_list[] = $file;
                    }
                }
            }
            closedir($handle);
        }
        sort($file_list);
        return $file_list;
    }

    // Hold the last file
    function last_file_hold($dir, $mode="time")
    {
        global $SETTING;

        $chmod_mode_file = preg_match("/^[0-9]{4}$/", $SETTING['chmod_mode_file']) ? $SETTING['chmod_mode_file'] : "0777";

        $dir = trim($dir);
        $dir = substr($dir, -1) != "/" ? $dir."/" : $dir;
        $file_list = array();
        $file_time = array();
        if ($handle = opendir($dir)) {
            while (false !== ($file = readdir($handle))) {
                if (($file != ".")&&($file != "..")&&(is_file($dir.$file))) {
                    $file_list[] = $file;
                    $file_time[] = filemtime($dir.$file);
                }
            }
            closedir($handle);
        }
        asort($file_time);
        array_pop($file_time);
        if (!empty($file_time)) {
            foreach ($file_time as $key => $value) {
                @chmod($dir.$file_list[$key],$chmod_mode_file);
                @unlink($dir.$file_list[$key]);
                unset($file_list[$key]);
            }
        }
        return $file_list;
    }

    // Make dir use recursive
    function make_dir($dir, $mode = "", $recursive = true)
    {
        global $SETTING;

        if (!preg_match("/^[0-9]{4}$/", $mode)) {
            $mode = preg_match("/^[0-9]{4}$/", $SETTING['chmod_mode_dir']) ? $SETTING['chmod_mode_dir'] : "0777";
        }
        if ( is_dir($dir) || $dir === "/" ) {
            return TRUE;
        }
        if ($recursive === true) {
            if ( func::make_dir(dirname($dir), $mode, $recursive) ) {
                return mkdir($dir, $mode);
            }
        } else {
            if ( is_dir(dirname($dir)) ) {
                return mkdir($dir, $mode);
            }
        }
        return FALSE;
    }

    // Del dir use recursive
    function del_dir($dir, $file_list = "*", $recursive = true)
    {
        global $SETTING;

        $chmod_mode_dir   = preg_match("/^[0-9]{4}$/", $SETTING['chmod_mode_dir'])  ? $SETTING['chmod_mode_dir']    : "0777";
        $chmod_mode_file  = preg_match("/^[0-9]{4}$/", $SETTING['chmod_mode_file']) ? $SETTING['chmod_mode_file']   : "0777";

        $dir = trim($dir);
        $dir = substr($dir, -1) == "/" ? substr($dir, 0, -1) : $dir;
        if (!is_array($file_list) && $file_list != "*") {
            $file_list = explode(",", $file_list);
            if (count($file_list) <= 0) {
                $file_list = "*";
            }
        }
        if (!is_dir($dir) || is_link($dir)) {
            if ($file_list == "*" || in_array($dir, $file_list)) {
                @chmod($dir,$chmod_mode_file);
                @unlink($dir);
            }
            return;
        } else {
            if ($handle = opendir($dir)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != "." && $item != "..") {
                        if (!is_dir($dir."/".$item) || is_link($dir."/".$item)) {
                            if ($file_list == "*" || in_array($item, $file_list)) {
                                @chmod($dir."/".$item,$chmod_mode_file);
                                @unlink($dir."/".$item);
                            }
                        } else {
                            if ($recursive === true) {
                                func::del_dir($dir."/".$item, $file_list, $recursive);
                            } elseif($file_list == "*" || in_array($item, $file_list)) {
                                @chmod($dir."/".$item,$chmod_mode_dir);
                                @rmdir($dir."/".$item);
                            }
                        }
                    }
                }
                closedir($handle);
            }
            if($file_list == "*" || in_array($dir, $file_list)) {
                @chmod($dir,$chmod_mode_dir);
                @rmdir($dir);
            }
            return;
        }
    }

    // Copy dir use recursive
    function copy_dir($dir_from,$dir_to,$mode="",$except_dir=array(),$except_file=array())
    {
        global $SETTING;

        if (!preg_match("/^[0-9]{4}$/", $mode)) {
            $mode = preg_match("/^[0-9]{4}$/", $SETTING['chmod_mode_dir']) ? $SETTING['chmod_mode_dir'] : "0777";
        }

        $except     = array('.','..');
        $dir_from   = preg_replace("/[\/\\\]{1,}/","/",$dir_from);
        $dir_to     = preg_replace("/[\/\\\]{1,}/","/",$dir_to);
        if (!file_exists($dir_from)) {
            $error[]="The directory ".$dir_from." does not exist!";
        } elseif (!is_dir ($dir_from)) {
            $error[]="The directory ".$dir_from." is not a directory!";
        }
        if (!file_exists($dir_to)) {
            func::make_dir($dir_to);
        } elseif (!is_dir ($dir_to)) {
            $error[]="The directory ".$dir_to." is not a directory!";
        }
        if (!is_readable($dir_from)) {
            @chmod($dir_from, $mode);
            if (!is_readable($dir_from)) {
                $error[]="The directory ".$dir_from." is not readable!";
            }
        }
        if (!is_writable($dir_to)) {
            @chmod($dir_to, $mode);
            if (!is_writable($dir_to)) {
                $error[]="The directory ".$dir_to." is not writable!";
            }
        }
        if ($handle = opendir($dir_from)) {
            while (false !== ($filename = readdir($handle))) {
                if (!in_array($filename,$except)) {
                    $from   = preg_replace("/[\/\\\]{1,}/","/",$dir_from.'/'.$filename);
                    $to     = preg_replace("/[\/\\\]{1,}/","/",$dir_to.'/'.$filename);
                    if (is_file($from)) {
                        if (!is_array($except_file) || count($except_file)<=0 || !@in_array($dir,$except_file)) {
                            if (copy($from,$to)) {
                                @chmod($to,$mode);
                            } else {
                                $error[]="Failed to copy from ".$from." to ".$to."<br>\n";
                            }
                        }
                    } elseif (is_dir($from)) {
                        if (!is_array($except_dir) || count($except_dir)<=0 || !@in_array($from,$except_dir)) {
                            if (!file_exists($to)) {
                                if (!mkdir($to,$mode)) {
                                    $error[]="Failed to create directory ".$to."!<br>\n";
                                }
                            }
                            func::copy_dir($from,$to,$mode,$except_dir,$except_file);
                        }
                    }
                }
            }
            closedir($handle);
        } else {
            $error[]="The directory ".$dir_from." can't open!";
        }
        if (!empty($error)) {
           echo "<strong>Error:</strong>";
           foreach($error as $value) {
               echo "<br>\n - ".$value;
           }
        }
        return true;
    }

    // Add a parameter to url
    function url_addvar($url, $array)
    {
        $addvar = "";
        foreach($array as $k => $v) {
            $addvar .= "&".$k."=".$v;
        }
        $addvar     = substr($addvar,1);
        $result     = parse_url($url);
        $fragment   = $result['fragment'] == "" ? "" : "#".$result['fragment'];
        $query      = $result['query'] == "" ? "?" : "?".$result['query']."&";
        $account    = $result['user'] != "" ? $result['user'].":".$result['pass']."@" : "";
        $site       = $result['scheme']."://".$account.$result['host'].$result['path'].$query.$addvar.$fragment;
        return $site;
    }

    // Remove a parameter from url
    function url_removevar($url, $array)
    {
        $query_new = "";
        $result    = parse_url($url);
        $query     = preg_split("/\?|&/", $result['query']);
        foreach($query as $v) {
            $query_tmp = explode("=", $v);
            if (!array_key_exists($query_tmp[0], $array)) {
                $query_new .= "&".$v;
            }
        }
        $query_new = substr($query_new, 1);
        $query_new = $query_new == "" ? "" : "?".$query_new;
        $fragment  = $result['fragment'] == "" ? "" : "#".$result['fragment'];
        $account   = $result['user'] != "" ? $result['user'].":".$result['pass']."@" : "";
        $site      = $result['scheme']."://".$account.$result['host'].$result['path'].$query_new.$fragment;
        return $site;
    }

    // Return current dir
    function return_rootdir($url)
    {
        $result = parse_url($url);
        $account = $result['user'] != "" ? $result['user'].":".$result['pass']."@" : "";
        $url = $result['scheme']."://".$account.$result['host'].$result['path'];
        $url = substr($url, 0, strrpos($url, '/')+1);
        return $url;
    }

    // Return visitor's IP
    function return_ip()
    {
        if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ($_SERVER['HTTP_CLIENT_IP']) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif ($_SERVER['REMOTE_ADDR']) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = "Unknown";
        }
        return trim($ip);
    }

    // Return visitor's OS
    function return_os()
    {
        $agent = $_SERVER["HTTP_USER_AGENT"];

        if (preg_match('/Win/i', $agent) && preg_match('/NT 5.2/i', $agent)) {
            $os = "Win2003";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/NT 5.1/i', $agent)) {
            $os = "WinXP";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/NT 5.0/i', $agent)) {
            $os = "Win2000";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/NT/i', $agent)) {
            $os = "Win2000";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/4.90/i', $agent)) {
            $os = "Win9X";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/98/i', $agent)) {
            $os = "Win9X";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/95/i', $agent)) {
            $os = "Win9X";
        } elseif (preg_match('/Win/i', $agent) && preg_match('/32/i', $agent)) {
            $os = "Win9X";
        } elseif (preg_match('/Linux/i', $agent)) {
            $os = "Linux";
        } elseif (preg_match('/BSD/i', $agent)) {
            $os = "Unix";
        } elseif (preg_match('/Unix/i', $agent)) {
            $os = "Unix";
        } elseif (preg_match('/Sun/i', $agent)) {
            $os = "SunOS";
        } elseif (preg_match('/Mac/i', $agent)) {
            $os = "Macintosh";
        } elseif (preg_match('/IBM/i', $agent)) {
            $os = "IBMOS";
        } else {// Other
            $os = "Other";
        }
        return trim($os);
    }

    // Return visitor's browser
    function return_browser()
    {
        $agent = $_SERVER["HTTP_USER_AGENT"];

        if (preg_match('/Firefox/i',$agent)) {
            $browser="Firefox";
        } elseif (preg_match('/Netscape/i',$agent)) {
            $browser="Netscape";
        } elseif (preg_match('/NetCaptor/i',$agent)) {
            $browser="NetCaptor";
        } elseif (preg_match('/MSN/i',$agent)) {
            $browser="MSN Explorer";
        } elseif (preg_match('/Opera/i',$agent)) {
            $browser="Opera";
        } elseif (preg_match('/AOL/i',$agent)) {
            $browser="AOL";
        } elseif (preg_match('/JAVA/i',$agent)) {
            $browser="JAVA";
        } elseif (preg_match('/MacWeb/i',$agent)) {
            $browser="MacWeb";
        } elseif (preg_match("/MSIE/i", $agent)) {
            $str = explode(";",$agent);
            $str = $str[1];
            $str = explode(" ",$str);
            $browser_ver = $str[2];
            if ($browser_ver == "6.0") {
                $browser = "IE6";
            } else {
                $browser = "IE5";
            }
        } else {
            $browser = "Other";
        }
        return trim($browser);
    }

    // Count query record
    function db_query_record($sql, $cache="0")
    {
        global $db;
        $total_record = 0;
        if ( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $result = &$db->CacheExecute($sql);
        } else {
            $result = &$db->Execute($sql);
        }
        if (!$result) {
            //echo $db->ErrorMsg();
        } else {
            $total_record = (int)$result->RecordCount();
        }
        if ($total_record <= 0) { $total_record = 0; }
        return $total_record;
    }

    // Count the table record
    function db_count_record($table,$condition="",$field="*", $cache="0")
    {
        global $db;
        $total_record = 0;
        if ($condition == "") {
            $sql = "SELECT count(".$field.") as total_record FROM ".$table;
        } else {
            $sql = "SELECT count(".$field.") as total_record FROM ".$table." WHERE ".$condition;
        }
        if ( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $result = &$db->CacheExecute($sql);
        } else {
            $result = &$db->Execute($sql);
        }
        if (!$result) {
            //echo $db->ErrorMsg();
        } else {
            $total_record = (int)$result->fields['total_record'];
        }
        if ($total_record <= 0) { $total_record = 0; }
        return $total_record;
    }

    // select from database
    function db_select($table, $field, $condition="", $limit="", $order="", $cache="0")
    {
        global $db;
        $fields = array();
        if (is_array($field)) {
            $str_query = implode(",",$field);
        } else {
            $str_query = $field;
        }
        $condition  = $condition != ""  ? " WHERE ".$condition  : " ";
        $limit      = (int)$limit > 0   ? " LIMIT ".(int)$limit : " ";
        $order      = $order     != ""  ? " ORDER BY ".$order   : " ";
        $sql = "SELECT ".$str_query." FROM ".$table.$condition.$order.$limit;
        if ( $cache > 0 ) {
            $db->cacheSecs = $cache;
            $result = &$db->CacheExecute($sql);
        } else {
            $result = &$db->Execute($sql);
        }
        if (!$result) {
            //echo $db->ErrorMsg();
        } else {
            while (!$result->EOF) {
                $fields[] = $result->fields;
                $result->MoveNext();
            }
        }
        return $fields;
    }

    // select from database
    function return_db_list($array)
    {
        global $CONFIG, $CONFIGURE, $SETTING, $ADMIN, $MEMBER, $db;
        $return     = array();
        $field      = implode(",", $array['field']);
        $condition  = !empty($array['condition'])   ? "WHERE ".$array['condition']  : "";
        $groupby    = !empty($array['groupby'])     ? "GROUP BY ".$array['groupby'] : "";
        $orderby    = !empty($array['orderby'])     ? "ORDER BY ".$array['orderby'] : "";
        $sql = "SELECT ".$field."
                FROM ".CONFIG_DB_PREFIX.$array['table']."
                ".$condition."
                ".$groupby."
                ".$orderby;
        $result = &$db->Execute($sql);
        if (!$result) {
            echo $db->ErrorMsg();
            return $return;
        } else {
            while (!$result->EOF) {
                $return[] = array(
                                "candidate_value"   => $result->fields[$array['field'][0]],
                                "candidate_name"    => $result->fields[$array['field'][1]],
                            );
                $result->MoveNext();
            }
            return $return;
        }
    }

    // insert for database
    function db_insert($table, $field)
    {
        global $db;
        if (is_array($field)) {
            $str_query = "";
            foreach ($field as $k => $v) {
                $str_query .= $k."=".$v.",";
            }
            $str_query = substr(trim($str_query), 0, -1);
        } else {
            $str_query = trim($field);
        }
        $sql = "INSERT INTO ".$table." SET ".$str_query;
        $result = &$db->Execute($sql);
        if (!$result) {
            //$db->ErrorMsg();
            $return = false;
        } else {
            $return = (int)$db->Insert_ID();
            if (!preg_match("/^[1-9][0-9]{0,10}$/i", $return)) {
                $return = true;
            }
        }
        return $return;
    }

    // update to database
    function db_update($table, $field, $condition)
    {
        global $db;
        if (is_array($field)) {
            $str_query = "";
            foreach ($field as $k => $v) {
                $str_query .= $k."=".$v.",";
            }
            $str_query = substr(trim($str_query), 0, -1);
        } else {
            $str_query = trim($field);
        }
        $sql = "UPDATE ".$table." SET ".$str_query." WHERE ".$condition;
        $result = &$db->Execute($sql);
        if (!$result) {
            //$db->ErrorMsg();
            $return = FALSE;
        } else {
            $return = TRUE;
        }
        return $return;
    }

    // delete for database
    function db_delete($table, $condition)
    {
        global $db;
        $sql = "DELETE FROM ".$table." WHERE ".$condition;
        $result = $db->Execute($sql);
        if (!$result) {
            //echo $db->ErrorMsg();
            $return = FALSE;
        } else {
            $return = TRUE;
        }
        return $return;
    }

    // confer
     function cmp_rank($a, $b)
    {
        if ($a['rank'] == $b['rank']) {
            return 0;
        } elseif ($a['rank'] < $b['rank']) {
            return -1;
        } else {
            return 1;
        }
    }

    // check the value
    function check_value($value, $check)
    {
        if ($check['begin'] == "") {
            $repetition = "+";
        } else {
            if ($check['end'] == "*") {
                $repetition = "{".$check['begin'].",}";
            }elseif ($check['end'] != "") {
                $repetition = "{".$check['begin'].",".$check['end']."}";
            } else {
                $repetition = "{".$check['begin']."}";
            }
        }
        if ($check['type'] == "int") {
            $match = "/^[0-9]".$repetition."$/i";
        } elseif ($check['type'] == "float") {
            if ($check['begin'] == "") {
                $check['begin'] = "+";
            } elseif ( preg_match("/^[0-9]+$/",$check['begin']) ) {
                $check['begin'] = "{1,".$check['begin']."}";
            }
            if ($check['end'] == "") {
                $check['end'] = "+";
            } elseif ( preg_match("/^[0-9]+$/",$check['end']) ) {
                $check['end'] = "{1,".$check['end']."}";
            }
            $match = "/^[0-9]".$check['begin']."\.[0-9]".$check['end']."$/i";
        } elseif ($check['type'] == "string") {
            $match = "/^[a-z0-9]".$repetition."$/i";
        } elseif ($check['type'] == "multibyte") {
            $match = "/^[^\x01-\x2E\\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]".$repetition."$/i";
        } elseif ($check['type'] == "email") {
            $match = "/^[a-z0-9-_\.]+@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,4}$/i";
        } elseif ($check['type'] == "any") {
            return true;
        } else {
            return false;
        }
        if (preg_match($match,$value)) {
            return true;
        } else {
            return false;
        }
    }

    // Put html to js
    function html2js($str,$charset="")
    {
        $result   = "";
        if (!empty($charset)) {
            $str = iconv("utf-8", $charset, $str);
        }
        $str_list = preg_split("/\n/",$str);
        $str_num  = count($str_list);
        for ($i=0;$i<$str_num;$i++) {
            $result .= "document.writeln(\"".addslashes(trim($str_list[$i]))."\");\n";
        }
        return $result;
    }

    // Flush now
    function flush_now()
    {
        @apache_setenv('no-gzip', 1);
        @ini_set('output_buffering', 0);
        @ini_set('zlib.output_compression', 0);
        @ini_set('implicit_flush', 1);
        for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
        if (ob_get_length()){
            @ob_flush();
            @flush();
            @ob_end_flush();
        }
        ob_implicit_flush(1);
        return true;
    }

    // Write data to article
    function write_jsarticle($filename, $data)
    {
        $str_begin = "document.write(\"";
        $str_end   = "\");";

        $str = $data;
        $str = str_replace("\"", "\\\"", $str);
        $str = $str_begin.$str.$str_end;
        $fettle = func::write_file($filename,$str);
        return $fettle;
    }

    // Write data to article
    function read_jsarticle($filename)
    {
        $str_begin = "document.write(\"";
        $str_end   = "\");";

        $str = func::read_file($filename);
        $str = str_replace($str_begin, "", $str);
        $str = str_replace($str_end, "", $str);
        $str = str_replace("\\\"", "\"", $str);
        return $str;
    }

    /*
    +-----------------------------------------------------------------------------+
    | Put the string
    +-----------------------------------------------------------------------------+
    */
    //
    function str_enbr($str)
    {
        $search  = array("\r\n",   "\n\r",   "\r",     "\n");
        $replace = array("<br />", "<br />", "<br />", "<br />");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }
    //
    function str_debr($str)
    {
        $search  = array("<br />", "<br>");
        $replace = array("\n",     "\n");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }
    //
    function str_stripbr($str)
    {
        $search  = array("\r\n", "\n\r", "\r", "\n");
        $replace = array("",     "",     "",   "");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }

    //
    function str_enspace($str)
    {
        $search  = array("  ");
        $replace = array("&nbsp;&nbsp;");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }
    //
    function str_despace($str)
    {
        $search  = array("&nbsp;");
        $replace = array(" ");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }
    //
    function str_stripspace($str)
    {
        $search  = array(" ");
        $replace = array("");
        $str     = str_replace($search, $replace, $str);
        return $str;
    }

    // en tag
    function str_entag($str, $array="")
    {
        $search         = array();
        $replace        = array();
        $check['space'] = "0";
        $check['br']    = "0";
        if (!empty($array)) {
            if (!is_array($array)) {
                $array = explode(",", $array);
            }
            foreach ($array as $v) {
                if ($v == "space") {
                    $check['space'] = "1";
                } elseif ($v == "br") {
                    $check['br'] = "1";
                }
            }
        }
        $search  = array("&");
        $replace = array("&amp;");
        if ($check['space'] == "1") {
            $search  = array_merge($search,     array("  "));
            $replace = array_merge($replace,    array("&nbsp;&nbsp;"));
        }
        $search  = array_merge($search,         array("\"",     "'",    "<",     ">",    "$",));
        $replace = array_merge($replace,        array("&quot;", "&#39;", "&lt;", "&gt;", "&#36;"));
        if ($check['br'] == "1") {
            $search  = array_merge($search,     array("\r\n",   "\n\r",   "\r",     "\n"));
            $replace = array_merge($replace,    array("<br />", "<br />", "<br />", "<br />"));
        }
        $str     = str_replace($search, $replace, $str);

        return $str;
    }
    // de tag
    function str_detag($str, $array="")
    {
        $search         = array();
        $replace        = array();
        $check['space'] = "0";
        $check['br']    = "0";
        if (!empty($array)) {
            if (!is_array($array)) {
                $array = explode(",", $array);
            }
            foreach ($array as $v) {
                if ($v == "space") {
                    $check['space'] = "1";
                } elseif ($v == "br") {
                    $check['br'] = "1";
                }
            }
        }
        if ($check['br'] == "1") {
            $search  = array("<br />");
            $replace = array("\n");
        }
        $search     = array_merge($search,      array("&quot;", "&#39;", "&lt;", "&gt;", "&#36;"));
        $replace    = array_merge($replace,     array("\"",     "'",    "<",     ">",    "$",));
        if ($check['space'] == "1") {
            $search  = array_merge($search,     array("&nbsp;"));
            $replace = array_merge($replace,    array(" "));
        }
        $search  = array_merge($search,         array("&amp;"));
        $replace = array_merge($replace,        array("&"));
        $str     = str_replace($search, $replace, $str);

        return $str;
    }
    // strip tag
    function str_striptag($str, $allow = "")
    {
        if (!empty($allow)) {
            $str = strip_tags($str, $allow);
        } else {
            $str = strip_tags($str);
        }
        return $str;
    }
    //////

    // Debug for print var
    function fp($var,$type="")
    {
        $print = !empty($type) ? "var_dump" : "print_r";
        echo "<pre>";
        $print($var);
        echo "</pre>";
    }
}
?>