CHips L MINI SHELL

CHips L pro

Current Path : /opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/
Upload File :
Current File : //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/String.php

<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// WebSite:  http://www.rvglobalsoft.com
// Unauthorized copying is strictly forbidden and may result in severe legal action.
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
//
// =====YOU MUST KEEP THIS COPYRIGHTS NOTICE INTACT AND CAN NOT BE REMOVE =======
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
// This Agreement is a legal contract, which specifies the terms of the license
// and warranty limitation between you and RV Global Soft Co.,Ltd. and RV Site Builder.
// You should carefully read the following terms and conditions before
// installing or using this software.  Unless you have a different license
// agreement obtained from RV Global Soft Co.,Ltd., installation or use of this software
// indicates your acceptance of the license and warranty limitation terms
// contained in this Agreement. If you do not agree to the terms of this
// Agreement, promptly delete and destroy all copies of the Software.
//
// =====  Grant of License =======
// The Software may only be installed and used on a single host machine.
//
// =====  Disclaimer of Warranty =======
// THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
// WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
// WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
// AND SOFTWARE ENVIRONMENTS INTO WHICH RV SITE BUILDER MAY BE USED, NO WARRANTY OF
// FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.  THE USER MUST ASSUME THE
// ENTIRE RISK OF USING THIS PROGRAM.  ANY LIABILITY OF RV GLOBAL SOFT CO.,LTD. WILL BE
// LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
// IN NO CASE SHALL RV GLOBAL SOFT CO.,LTD. BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
// CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
// OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
// BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
// NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
// RV GLOBAL SOFT CO.,LTD. IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
// RV GLOBAL SOFT CO.,LTD.'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
// BY LICENSEE TO RV GLOBAL SOFT CO.,LTD.
// +---------------------------------------------------------------------------+
// $Id$
// +---------------------------------------------------------------------------+

/**
 * RvSiteBuilder string libary
 *
 * @package RvsLibs
 * @author  Pairote Manunphol <pairote@rvglobalsoft.com>
 * @version $Revision$
 * @since   PHP 5.1
 */
if (class_exists('RvsLibs_String') === false) {
	class RvsLibs_String
	{
		public static function isPHP53()
		{
			SGL::logMessage('rvdebug: php version: ' . PHP_VERSION, PEAR_LOG_DEBUG);
			if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
				return true;
			} else {
				return false;
			}
		}

		public static function translate($key, $filter = false, $aParams = array())
		{
		    // optimize :nipaporn
			return SGL_String::translate($key, $filter, $aParams);
			///RVS remove getConvertFunc: apiruk
		}

		/**
		 * Generate Unique Id
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @return string
		 */
		public static function genUniqueId($values=null)
		{
			$sessID = (isset($_COOKIE['SGLSESSID'])) ? $_COOKIE['SGLSESSID'] : RVS_USER_NAME;
			return trim(md5(microtime() . $sessID . $values));
		}

		/**
		 * Description : double-byte encodings stripslashes
		 * to deal with slashes in double-byte encodings, such as shift_jis or big5
		 */
		public static function dbeStripslashes($str = null)
		{
			$projetCharset = isset($_SESSION['project_charset']) ? $_SESSION['project_charset'] : '';
			if(is_null($str) === false) {
				if ($projetCharset == 'big5' || $projetCharset == 'shift_jis') {
					$str = RvsLibs_String::str_replace("\\\"", "\"", $str);
					$str = RvsLibs_String::str_replace("\\'", "'", $str);
					$str = RvsLibs_String::str_replace("\\\\", "\\", $str);
				} else {
					//$str = str_replace(chr(92),chr(92).chr(92),$str);
					$str = RvsLibs_String::_stripslashes($str);
					if(SGL::isError($str) === true) {
						return SGL::raiseError(
						RvsLibs_String::translate(
                        'cannot un-quotes a quoted string. Because %MESSAGE'
                        , 'vprintf'
                        , array('MESSAGE' => $str->getMessage())
                        )
                        );
					}
				}
			}
			return $str;
		}

		/**
		 * ใช้สำหรับลบ ข้อความที่มีการขึ้นบรรทัดใหม่ ให้เหลือแค่บรรทัดเดียว
		 * @param $str
		 * @return unknown_type
		 */
		public static function removeNewline($str)
		{
			$str = RvsLibs_String::preg_replace('/[\r\n]/si', '', $str);
			$str = RvsLibs_String::str_replace('<br>', '', $str);
			$str = RvsLibs_String::str_replace('<br />', '', $str);
			return 	$str;
		}

		/**
		 * Un-quotes a quoted string
		 *
		 * @param $string $str
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return a string with backslashes stripped off.
		 *       (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).
		 */
		public static function _stripslashes($str, $flagTestErrorMode = false)
		{
			return (RvsLibs_System::function_exists('stripslashes') === true)
			                 ? stripslashes($str)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'stripslashes')));
		}

		/**
		 * allowProgramCode
		 *
		 * include wysiwyg function remove tag allowApplet , allowScript , allowPhp,
		 * <?xml ... >, <html .....>, <body ...>, <head>....</head>, <o:p>....</o:p>
		 *
		 * @param string $htmlcode
		 * @return string
		 */
		public static function allowProgramCode($htmlcode)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oSglMgr = SGL_Manager::singleton();
			// include_once(WYSIWYG_ROOT_PATH . "/editor_functions.php");

			// Try to keep JavaScript <script...>.....</script> and <link....> inside <head>.....</head>
			$aRemoveTage = array();

			// Remove Tag '<Applet>'
			if ($oSglMgr->conf['wysiwyg']['allowApplet'] != 1) {
				$aRemoveTage['applet'] = true;
			}
			// Remove Tag '<Script>'
			if ($oSglMgr->conf['wysiwyg']['allowScript'] != 1) {
				$aRemoveTage['script'] = true;
			}
			$htmlcode = RvsLibs_WysiwygPro::removeTags($htmlcode, $aRemoveTage);
			$htmlcode = RvsLibs_WysiwygPro::removeInavalidTags($htmlcode);
			// Allow Php
			if ($oSglMgr->conf['wysiwyg']['allowPhp'] == 1 || RvsLibs_Project::isPublishCompoDB()) {
				$htmlcode = RvsLibs_WysiwygPro::comment2php($htmlcode);
			}
			return $htmlcode;
		}

		/**
		 * Set/Get internal character encoding
		 *
		 * @param string $encoding : encoding  is the character encoding name used for
		 *      the HTTP input character encoding conversion
		 *      , HTTP output character encoding conversion
		 *      , and the default character encoding for string functions defined by the mbstring module.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return bool : If encoding  is set
		 *      , then Returns TRUE on success or FALSE on failure.
		 *       If encoding  is omitted, then the current character encoding name is returned.
		 */
		public static function mb_internal_encoding($encoding = null)
		{
			if (RvsLibs_System::function_exists('mb_internal_encoding') === true) {

				if (is_null($encoding) === true) {
					return mb_internal_encoding();
				} elseif (is_string($encoding) === true) {
					return mb_internal_encoding($encoding);
				}
				return SGL::raiseError(
					RvsLibs_String::translate(
                         'Unknow encoding %ENCODING.'
                         ,'vprintf'
                         , array('ENCODING' => $encoding)
                    )
                );
			} else {
				return SGL::raiseError(
					RvsLibs_String::translate(
                    	'Function %FUNCTION is undefine.'
                    	,'vprintf'
                    	, array('FUNCTION' => 'mb_internal_encoding')
                    )
                );
			}
		}

		/**
		 * For Split multibyte string
		 *
		 * @param string $pattern
		 * @param string $str
		 * @param int $limit
		 * @return array
		 *      If have error return raisError
		 */
		public static function dbeExplode($pattern, $str,  $limit = null)
		{
			$aCharsetDbe = array('big5', 'shift_jis');
			$projetCharset = $GLOBALS['_SGL']['CHARSET'];
			$aRarry = array();
			if (in_array($projetCharset, $aCharsetDbe)) {
				$aRegs = array(
                '#\^#i' => '\^',
                '#\$#i' => '\$',
                '#\(#i' => '\(',
                '#\)#i' => '\)',
                '#\{#i' => '\{',
                '#\}#i' => '\}',
                '#\|#i' => '\|',
                '#\/#i' => '\/',
                '#\+#i' => '\+',
                '#\-#i' => '\-',
                '#\.#i' => '\.',
                '#\?#i' => '\?',
                '#\*#i' => '\*',
                '#\[#i' => '\[',
                '#\]#i' => '\]',
                '#\<#i' => '\<',
                '#\>#i' => '\>',
				);
				$aPatt = array_keys($aRegs);
				$aRepl = array_values($aRegs);
				$pattern = RvsLibs_String::preg_replace($aPatt, $aRepl , $pattern);
				//Set/Get internal character encoding
				$resEncoding = RvsLibs_String::mb_internal_encoding($projetCharset);
				if (SGL::isError($resEncoding) === true) {
					return SGL::raiseError(
					RvsLibs_String::translate(
                		'Can not Set internal character encoding. Because %MESSAGE'
                		,'vprintf'
                		, array('MESSAGE' => $resEncoding->getMessage())
                		)
                		);
				}
				//Returns current encoding for multibyte regex as string
				$resMbRegexEncoding = RvsLibs_String::mb_regex_encoding($projetCharset);
				if (SGL::isError($resMbRegexEncoding) === true) {
					return SGL::raiseError(
					RvsLibs_String::translate(
                    	'Can not current encoding for multibyte regex as string. Because %MESSAGE'
                    	, 'vprintf'
                    	, array('MESSAGE' => $resMbRegexEncoding->getMessage())
                    	)
                    	);
				}
				//$aRarry = ($limit) ? mb_split($pattern, $str, $limit) : mb_split($pattern, $str);
				$aRarry = RvsLibs_String::mb_split($pattern, $str, $limit);
				if (SGL::isError($aRarry) === true) {
					return SGL::raiseError(
					RvsLibs_String::translate(
                    	'Can not Split multibyte string. Because %MESSAGE'
                    	, 'vprintf'
                    	, array('MESSAGE' => $aRarry->getMessage())
                    	)
                    	);
				}
			} else {
				$aRarry = RvsLibs_String::_explode($pattern, $str, $limit);
				if(SGL::isError($aRarry) === true) {
					return SGL::raiseError(
					RvsLibs_String::translate(
                    	'Can not explode string. Because %MESSAGE'
                    	, 'vprintf'
                    	, array('MESSAGE' => $aRarry->getMessage())
                    	)
                    	);
				}
			}
			return $aRarry;
		}

		/**
		 * cut lengh is string
		 *
		 * @param string $string
		 * @param int $start
		 * @param int $lengh
		 * @return  part of a string
		 */
		public static function dbeSubstr($string, $start, $lengh = null)
		{
			$string = (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) == 'utf-8')
			                     ? RvsLibs_String::mb_substr($string, $start, $lengh, 'utf-8')
			                     : RvsLibs_String::_substr($string, $start, $lengh);
			return (SGL::isError($string) === true)
			                 ? SGL::raiseError(RvsLibs_String::translate('Cannot get part of a string. Because %MESSAGE', 'vprintf', array('MESSAGE' => $string->getMessage())))
			                 : $string;
		}

		/**
		 * count sub string ...
		 * @param $haystack
		 * @param $needle
		 * @return mix total substrcount(integer) or raiseError on failue.
		 */
		public static function dbeSubStrCount($haystack, $needle)
		{
			$haystack = (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($haystack)) =='utf-8')
									? mb_substr_count($haystack, $needle, 'utf-8')
									: substr_count($haystack, $needle);
			return (SGL::isError($haystack) === true)
							? SGL::raiseError(RvsLibs_String::translate('Cannot get part of a string. Because %MESSAGE', 'vprintf', array('MESSAGE' => $haystack->getMessage())))
							: $haystack;
		}

		/**
		 * Split a string by string
		 *
		 * @param string $delimiter : The boundary string.
		 * @param string $string
		 * @param int $limit
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return If delimiter  is an empty string ("")
		 *  , explode() will return FALSE.
		 *      If delimiter  contains a value that is not contained in string  and a negative limit  is used,
		 *       then an empty array will be returned. For any other limit ,
		 *      an array containing string  will be returned.
		 *       If have error return raisError
		 */
		public static function _explode($delimiter, $string, $limit = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('explode') === true && $flagTestErrorMode === false ) {
				return (is_null($limit) === true) ? explode($delimiter, $string) : explode($delimiter, $string, $limit);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'explode')));
		}

		/**
		 * current encoding for multibyte regex as string
		 *
		 * @param string $encoding : The encoding parameter is the character encoding.
		 *        If it is omitted, the internal character encoding value will be used.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The character encoding used by multibyte regex functions.
		 *   If have error return raisError
		 */
		public static function mb_regex_encoding($encoding = null)
		{
			if (RvsLibs_System::function_exists('mb_regex_encoding') === true) {

				if (is_null($encoding) === true) {
					return mb_regex_encoding();
				} elseif (is_string($encoding)) {
					return mb_regex_encoding($encoding);
				}
				return SGL::raiseError(
					RvsLibs_String::translate(
                    	'Unknow encoding %ENCODING.'
                    	, 'vprintf'
                    	, array('ENCODING' => $encoding)
                	)
            	);
			} else {
				return SGL::raiseError(
					RvsLibs_String::translate(
                		'Function %FUNCTION is undefine.'
                		, 'vprintf'
                		, array('FUNCTION' => 'mb_regex_encoding')
                	)
                );
			}
		}

		/**
		 * Split multibyte string using regular expression
		 *
		 *
		 * @param string $pattern : The regular expression pattern.
		 * @param string $string
		 * @param int $limit
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return array : If mb_split success return Array ( [0] => Test [1] => mb_split )
		 *                          else return  Array ( [0] => Testmb_split or  Array ( [0] => )
		 *      If have error return raisError
		 */
		public static function mb_split($pattern, $string, $limit = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('mb_split') === true && $flagTestErrorMode === false) {
				return (is_null($limit) === true) ? mb_split($pattern, $string) : mb_split($pattern, $string, $limit);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'mb_split')));
		}

		/**
		 * Get part of string
		 *
		 * @param string $string : The string being checked.
		 * @param int $start : The first position used in $string .
		 * @param int $length : The maximum length of the returned string.
		 * @param string $encoding : The encoding parameter is the character encoding.
		 *              If it is omitted, the internal character encoding value will be used.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return the portion of str  specified by the start  and length  parameters.
		 *      If cannot get part of string return ""
		 *      If have error return raisError
		 */
		public static function mb_substr($string, $start, $length = null, $encoding = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('mb_substr') === true
			    && $flagTestErrorMode === false) {

				if (is_null($length) == true && is_null($encoding) === true) {
					$mbSubStr = mb_substr($string, $start);
				} elseif (is_null($encoding) === true) {
					$mbSubStr = mb_substr($string, $start, $length);
				} else {
					$mbSubStr = mb_substr($string, $start, $length, $encoding);
				}
				return $mbSubStr;
				/*
				return (is_null($mbSubStr) === false)
				        ? $mbSubStr
				        : SGL::raiseError(
				RvsLibs_String::translate(
                        'cannot get part of %STRING.'
                        , 'vprintf'
                        , array('STRING' => $string)
                        )
                        );
                        */
			} else {
				return SGL::raiseError(
				RvsLibs_String::translate(
                	'Function %FUNCTION is undefine.'
                	, 'vprintf'
                	, array('FUNCTION' => 'mb_substr')
                	)
                	);
			}
		}

		/**
		 * fix unserialize content utf-8
		 * @param $serial_str
		 * @return unknown_type
		 */
		public static function mb_unserialize($serial_str)
		{
			return RvsLibs_String::unserialize(RvsLibs_String::preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str));
		}

		/**
		 *  part of a string
		 *
		 * @param string $string
		 * @param int $start
		 * @param int $length
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return  part of a string
		 */
		public static function _substr($string, $start, $length = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('substr') === true && $flagTestErrorMode === false) {
				return (is_null($length) === true) ? substr($string, $start) : substr($string, $start, $length);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'substr')));
		}

		/**
		 *Convert special characters to HTML entities
		 *
		 * @param string $string : The string being converted.
		 * @param int $quote_style
		 * @param string $charset : Defines character set used in conversion. The default character set is ISO-8859-1.
		 * @param bool $double_encode
		 * @return The converted string.
		 */
		public static function htmlspecialchars($string, $quote_style = ENT_COMPAT, $charset = null, $double_encode = true)
		{
			if (RvsLibs_System::function_exists('htmlspecialchars') === true) {
				return (phpversion() <= 5.2) ? htmlspecialchars($string, $quote_style, $charset) : htmlspecialchars($string, $quote_style, $charset, $double_encode);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'htmlspecialchars')));
		}

		/**
		 * Replace all occurrences of the search string with the replacement string for case-insensitive replace.
		 *
		 * @param mixed $search
		 * @param mixed $replace
		 * @param mixed $subject
		 * @param int $count
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return Returns a string or an array of replacements.
		 */
		public static function str_ireplace($search, $replace, $subject, &$count  = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('str_ireplace') === true && $flagTestErrorMode === false) {
				return (phpversion() >= 5) ? str_ireplace($search, $replace, $subject, $count) : str_ireplace($search, $replace, $subject);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'htmlspecialchars')));
		}

		/**
		 * Find first occurrence of a string
		 *
		 * @param string $haystack : The string to search in
		 * @param unknown_type $nedle :If needle  is not a string, it is converted to an integer and applied as the ordinal value of a character.
		 * @param bool $beforeNeedle
		 * @return Returns the portion of string, or FALSE if needle  is not found.
		 */
		public static function stristr($haystack, $nedle = null, $beforeNeedle = null)
		{
			if (RvsLibs_System::function_exists('stristr') === true) {
				return (phpversion() >= 5.3) ? stristr($haystack, $nedle, $beforeNeedle) : stristr($haystack, $nedle);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'stristr')));
		}

		/**
		 * Get string length
		 *
		 * @param string $string : The string being measured for length.
		 * @return The length of the string  on success, and 0 if the string  is empty.
		 */
		public static function strlen($string)
		{
			if (extension_loaded('mbstring') && RvsLibs_System::function_exists('mb_strlen') === true) {
				$enc = RvsLibs_String::mb_detect_encoding($string);
				return @mb_strlen($string, $enc);
			} else {
				return strlen($string);
			}
		}

		/**
		 * Make a string lowercase
		 *
		 * @param string $string
		 *  @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The lowercased string.
		 */
		public static function strtolower($string, $flagTestErrorMode = false)
		{
			if (extension_loaded('mbstring') && RvsLibs_System::function_exists('mb_strtolower') === true) {
				// Fatal error: Maximum function nesting level of '100' reached
				$enc = RvsLibs_String::mb_detect_encoding($string);
				return mb_strtolower($string, $enc);
			} else {
				return strtolower($string);
			}
		}

		/**
		 * Make a string uppercase
		 *
		 * @param string $string
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The uppercased string.
		 */
		public static function strtoupper($string)
		{
			if (extension_loaded('mbstring') && RvsLibs_System::function_exists('mb_strtoupper') === true) {
				$enc = RvsLibs_String::mb_detect_encoding($string);
				return mb_strtoupper($string, $enc);
			} else {
				return strtoupper($string);
			}
		}

		/**
		 * Replace text within a portion of a string
		 *
		 * @param mixed $string : The input string.
		 * @param string $replacement : The replacement string.
		 * @param int $start : If start is positive, the replacing will begin at the start 'th offset into string .
		 *               If start is negative, the replacing will begin at the start 'th character from the end of string .
		 * @param int $length : If given and is positive
		 *              , it represents the length of the portion of string  which is to be replaced.
		 *               If it is negative, it represents the number of characters from the end of string  at which to stop replacing.
		 *               If it is not given, then it will default to strlen( string  ); i.e. end the replacing at the end of string .
		 *               Of course, if length  is zero then this function will have the effect of inserting replacement  into string  at the given start  offset.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The result string is returned. If string  is an array then array is returned.
		 */
		public static function substr_replace($string, $replacement, $start, $length = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8') {
				return RvsLibs_String::utf8_substr_replace($string, $replacement, $start, $length);
			} else {
				return (is_null($length) == true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
			}
		}

		/**
		 * fix UTF-8 substr_replace
		 *
		 * @param string $string
		 * @param string $replacement
		 * @param int $start
		 * @param int $length
		 * @author duangdao.k
		 * @return The result string is returned. If string  is an array then array is returned.
		 */
		public static function utf8_substr_replace($string, $replacement, $start,$length = null)
		{
			$mb_res1 = RvsLibs_String::mb_substr($string, 0, $start);
			return ($length == null) ? $mb_res1 . $replacement : $mb_res1 . $replacement . RvsLibs_String::mb_substr($string, $start+$length);
		}

		/**
		 * Strip whitespace (or other characters) from the beginning and end of a string
		 *
		 * @param string $str : The string that will be trimmed.
		 * @param string $charlist : Optionally, the stripped characters can also be specified using the charlist  parameter.
		 *              Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The trimmed string.
		 */
		public static function trim($str, $charlist = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($str)) =='utf-8'){
				return RvsLibs_String::utf8_trim($str, $charlist);
			} else {
				return (is_null($charlist) === true) ? trim($str) : trim($str, $charlist);
			}
		}


		public static function utf8_trim($str, $charlist = NULL)
		{
			if ($str != '' ) {
				return RvsLibs_String::ltrim(RvsLibs_String::rtrim($str, $charlist), $charlist);
			}
		}

		/**
		 * fix utf-8 function trim
		 *
		 * @param string $string
		 * @param string $charlist
		 * @return The trimmed string.
		 * @author duangdao.k
		 */
		/*
		 function trim_utf8($string, $charlist = null)
		 {
		 if (is_null($charlist) === true) {
		 return RvsLibs_String::preg_replace("/^\s*|\s*$/", "", $string);
		 } else {
		 $stop   = mb_strlen($charlist);
		 if ($stop > 1) {
		 $result = array();
		 for( $idx = 0; $idx < $stop; $idx++) {
		 $subcharlist = mb_substr( $string, $idx, 1);
		 $result[] = $subcharlist;
		 $string = RvsLibs_String::str_replace($subcharlist, "", $string);
		 }
		 } else {
		 $string = RvsLibs_String::str_replace($charlist, "", $string);
		 }
		 return $string;
		 }
		 }

		 */


		/**
		 * Strip whitespace (or other characters) from the beginning of a string
		 *
		 * @param string $str
		 * @param string $charlist
		 * @return a string with whitespace stripped from the beginning of str .
		 */
		//TODO ใช้กับ utf8 ยังไม่ได้
		public static function ltrim($str, $charlist = null)
		{
			if (RvsLibs_System::function_exists('ltrim') == true) {
				return (is_null($charlist) === true) ? ltrim($str) : ltrim($str, $charlist);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprint', array('FUNCTION' => 'ltrim')));
		}


		/**
		 * Strip whitespace (or other characters) from the end of a string
		 *
		 * @param string $str
		 * @param string $charlist
		 * @return Returns the modified string.
		 */
		//TODO ใช้กับ utf8 ยังไม่ได้
		public static function rtrim($str, $charlist = null)
		{
			if (RvsLibs_System::function_exists('rtrim') === true) {
				return (is_null($charlist) === true) ? rtrim($str) : rtrim($str, $charlist);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprint', array('FUNCTION' => 'rtrim')));
		}

		/**
		 * Dumps information about a variable
		 *
		 * @param mixed $expression : The variable you want to export.
		 * @param mixed $expression2 : The variable you want to export.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return No value is returned.
		 */
		public static function var_dump($expression = null, $expression2 = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('var_dump') === true && $flagTestErrorMode === false) {
				return var_dump($expression, $expression2);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'var_dump')));
		}

		/**
		 * Replace all occurrences of the search string with the replacement string : This function is case-sensitive.
		 *
		 * @param mixed $search
		 * @param mixed $replace
		 * @param mixed $subject
		 * @param int $count :  If passed, this will hold the number of matched and replaced needles.
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return This function returns a string or an array with the replaced values.
		 */
		public static function str_replace($search, $replace, $subject, &$count = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('str_replace') === true && $flagTestErrorMode === false) {
				// check version
				return (RvsLibs_String::dbeSubstr(phpversion(),0,1) < 5) ? str_replace($search, $replace, $subject) : str_replace($search, $replace, $subject, $count);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'str_replace')));
		}


		/**
		 * Perform a regular expression match
		 *
		 * @param string $patten
		 * @param string $subject
		 * @param array $match
		 * @param int $flags
		 * @param int $offset : Using offset  is not equivalent to passing substr($subject, $offset)
		 *      to preg_match() in place of the subject string, because pattern  can contain assertions
		 *      such as ^, $ or (?<=x). Compare:
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return The number of times pattern  matches.
		 *       That will be either 0 times (no match) or 1 time
		 *      because preg_match() will stop searching after the first match.
		 *      preg_match_all()  on the contrary will continue until it reaches the end of subject .
		 *       preg_match() returns FALSE if an error occurred.
		 */
		public static function preg_match($patten, $subject, &$match = null, $flags = null, $offset = null, $flagTestErrorMode = false)
		{
			return (RvsLibs_System::function_exists('preg_match') === true && $flagTestErrorMode === false)
                 ? preg_match($patten, $subject, $match, $flags, $offset)
                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'preg_match')));
		}

		/**
		 * Perform a global regular expression match
		 *
		 * @param string $pattern : The pattern to search for, as a string.
		 * @param string $subject : The input string.
		 * @param array $matches : Array of all matches in multi-dimensional array ordered according to flags .
		 * @param int $flags : Can be a combination of the following flags
		 *              PREG_PATTERN_ORDER : Orders results so that $matches[0] is an array of full pattern matches
		 *                   , $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
		 *              PREG_SET_ORDER :  Orders results so that $matches[0] is an array of first set of matches
		 *                  , $matches[1] is an array of second set of matches, and so on.
		 *               PREG_OFFSET_CAPTURE : If this flag is passed
		 *                  , for every occurring match the appendant string offset will also be returned.
		 *                   Note that this changes the value of matches  in an array
		 *                  where every element is an array consisting of the matched string at offset 0
		 *                   and its string offset into subject  at offset 1.
		 * @param int $offset : Normally, the search starts from the beginning of the subject string.
		 *              The optional parameter offset  can be used to specify the alternate place from which to start the search (in bytes).
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return  the number of full pattern matches (which might be zero), or FALSE if an error occurred.
		 *
		 */
		public static function preg_match_all($pattern, $subject, &$matches, $flags = null, $offset = null, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('preg_match_all') === true
			    && $flagTestErrorMode === false
			) {
				return preg_match_all($pattern, $subject, $matches, $flags, $offset);

			} else {
				return SGL::raiseError(
					RvsLibs_String::translate(
	                    'Function %FUNCTION is undefine.'
	                    , 'vprintf'
	                    , array('FUNCTION' => 'preg_match_all')
	                )
                );
			}
		}

		/**
		 * Perform a regular expression search and replace
		 *
		 * @param mixed $pattern
		 * @param mixed $replacement
		 * @param mixed $subject
		 * @param int $limit
		 * @param int $count
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @param int $flagTestVersionPhp : Flag for test mode version
		 * @return an array if the subject  parameter is an array, or a string otherwise.
		 *              If matches are found, the new subject will be returned
		 *              , otherwise subject will be returned unchanged or NULL if an error occurred.
		 */
		public static function preg_replace($pattern, $replacement, $subject, $limit = -1, &$count = null, $flagTestErrorMode = false, $flagTestVersionPhp = null)
		{
			if (RvsLibs_System::function_exists('preg_replace') === true
			    && $flagTestErrorMode === false) {

				$VersionPhp = (is_null($flagTestVersionPhp)) ? phpversion() : $flagTestVersionPhp;
				if ( $VersionPhp < 5) {
					return @preg_replace($pattern, $replacement, $subject, $limit);
				} elseif ($VersionPhp >= 5) {
					return @preg_replace($pattern, $replacement, $subject, $limit, $count);
				}
			} else {
				return SGL::raiseError(
				RvsLibs_String::translate(
                    'Function %FUNCTION is undefine.'
                    , 'vprintf'
                    , array('FUNCTION' => 'preg_replace')
                    )
                    );
			}
		}

		/**
		 * Convert string to requested character encoding
		 *
		 * @param string $in_charset : The input charset.
		 * @param string $out_charset :  The output charset. If you append the string //TRANSLIT to out_charset transliteration is activated.
		 *            This means that when a character can't be represented in the target charset
		 *           , it can be approximated through one or several similarly looking characters.
		 *            If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded.
		 *            Otherwise, str is cut from the first illegal character and an E_NOTICE is generated.
		 *
		 * @param string $str
		 * @param bool $flagTestErrorMode; Flag for test mode error
		 * @return Returns the converted string or FALSE on failure
		 *   if have error return raiseError
		 */
		public static function iconv($in_charset, $out_charset, $str, $flagTestErrorMode = false)
		{
			$convertValue = '';
			if (RvsLibs_System::function_exists('iconv') === true
			    && $flagTestErrorMode === false) {
				if (!preg_match('/(\/\/IGNORE$|\/\/TRANSLIT$)/', $out_charset)) {
					$out_charset = $out_charset . '//IGNORE';
				}
				$convertValue = @iconv($in_charset, $out_charset, $str);
			}  elseif (RvsLibs_System::function_exists('mb_convert_encoding') === true && RvsLibs_System::function_exists('mb_internal_encoding') === true) {
				mb_internal_encoding($in_charset);
				$convertValue = mb_convert_encoding($str, $out_charset, $in_charset);
			} elseif (RvsLibs_System::function_exists('utf8_decode') === true) {
				$convertValue = utf8_decode($str);
			} else {
				return SGL::raiseError(
				RvsLibs_String::translate(
                     'Function %FUNCTION is undefine.'
                     , 'vprintf'
                     , array('FUNCTION' => 'iconv')
                     )
                     );
			}
			return $convertValue;
		}

	 /**
	  * Iconv File
	  *
	  * @param string $fileName
	  * @param string $inCharset
	  * @param string $outCharset
	  */
		public static function iconvFile($fileOriginal, $fileNew, $inCharset, $outCharset)
		{
			$iconv = '';
			if (is_file($fileOriginal)) {
				$handle = RvsLibs_File::fopen($fileOriginal, 'r');
				if (SGL::isError($handle) === true) {
				    return $handle;
				}
				if ($handle) {
					while (!feof($handle)) {
						$buffer = fgets($handle, 4096);
						$iconv .= RvsLibs_String::iconv($inCharset, $outCharset, $buffer);
					}
				}
				$finaldata = $iconv;
				RvsLibs_File::fclose($handle);

				$handle = RvsLibs_File::fopen($fileNew, "w+");
				if (SGL::isError($handle) === true) {
				    return $handle;
				}
				RvsLibs_File::fwrite($handle, $finaldata);
				RvsLibs_File::fclose($handle);

			}
			if (is_file($fileNew) === false) {
				return SGL::raiseError(
				RvsLibs_String::translate(
                     		'The file %FILE is not exists and not regular file.'
                     		, 'vprintf'
                     		, array('FILE' => $fileNew)
                     		)
                     		);
			} else {
				return true;
			}
		}

		/**
		 * Verity iconv support charset - Find character set is supported by iconv on server or not.
		 *
		 * @param string $fileName : write iconv list to fileName
		 * @param string $projectId : project ID
		 * @return Returns TRUE on charset is supported by iconv on server,
		 *         or False on charset is not supported by iconv on server,
		 *         or mixed PEAR_Error on system server off or cannot open file to read iconv list
		 */
		public static function verityIconvSupportedCharset($fileName, $charset)
		{
			$supportCharset = false;
			$resRemove = true;

			if (file_exists($fileName) === true) {
				$resRemove = System::rm($fileName);

				if (SGL::isError($resRemove) === true
				    || $resRemove === false) {
					//ถ้า remove file ไม่ได้ pop out
					SGL_Error::pop();
					$resRemove = false;
				}
			} //ถ้า $resRemove = false แสดงว่า มี $fileName อยู่
			if ($resRemove == true) {
				$command = 'iconv -l > ' . $fileName;
				$resSystem = RvsLibs_System::exec($command);

				if (SGL::isError($resSystem) === true) {
					//ถ้า system ไม่เปิด
					return $resSystem;
				}
			}
			$strContent = file_get_contents($fileName);
			if (RvsLibs_String::preg_match("/" . $charset . "/i", $strContent)) {
				$supportCharset = true;
			}
			return $supportCharset;
		}

		public static function rand($min, $max)
		{
			if (RvsLibs_System::function_exists('rand') === true) {
				return rand($min, $max);
			}
            return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'rand')));
		}

		/**
		 * Wrapper for microtime().
		 *
		 * @return float
		 */
		public function getMicrotime() {
			$microtime = explode(' ', microtime());
			return $microtime[1] . substr($microtime[0], 1);
		}

		/**
		 *
		 * @return string   Execution time in milliseconds
		 */
		public function getSystemTime()
		{
			$time = @gettimeofday();
			$resultTime = $time['sec'] * 1000;
			$resultTime += floor($time['usec'] / 1000);
			return $resultTime;
		}

        public static function getExecuteTime($sqlWaitTime=null)
        {
        	static $lastTime;
        	static $reloadTime;
			$startTime = @SGL_START_TIME;
			$maxExecuteTimeSec = intval(ini_get('max_execution_time'));
			if ($maxExecuteTimeSec == 0 || ($maxExecuteTimeSec > 120)) {
				$maxExecuteTimeSec = 120;
			}

			$finishTime = self::getSystemTime();
			$useTime = ($finishTime - $startTime)/1000;
			if (!$lastTime) {
				$lastTime = 0;
			}
			$reloadTime += ($useTime - $lastTime);
			//SGL::logMessage('Witoon***** max Time:' . $maxExecuteTimeSec . 's', PEAR_LOG_DEBUG);
			//SGL::logMessage('Witoon***** Use Time:' . $useTime . 's', PEAR_LOG_DEBUG);
			$lastTime = $useTime;
			if (is_null($sqlWaitTime) === false && ($reloadTime > ($sqlWaitTime-5))) {
				//SGL::logMessage('Witoon***** wait time:' . $sqlWaitTime . 's, reload time:' . $reloadTime . 's', PEAR_LOG_DEBUG);
				$reloadTime = 0;
				return 9;
			}
			//return time of sec
			return ($maxExecuteTimeSec - $useTime);
		}

		public function pingSqlServer($sqlWaitTime=null)
		{
			$sqlWaitTime = is_null($sqlWaitTime) ? 10 : $sqlWaitTime;
			static $lastTime;
            static $reloadTime;
            $startTime = @SGL_START_TIME;
            if (!$lastTime) {
                $lastTime = 0;
            }
            $finishTime = self::getSystemTime();
            $useTime = ($finishTime - $startTime)/1000;
            $reloadTime += ($useTime - $lastTime);
            $lastTime = $useTime;
            SGL::logMessage('Witoon***** Use Time:' . $useTime . 's', PEAR_LOG_DEBUG);
            if ($reloadTime > ($sqlWaitTime-5)) {
            	SGL::logMessage('Witoon***** wait time:' . $sqlWaitTime . 's, reload time:' . $reloadTime . 's', PEAR_LOG_DEBUG);
                $reloadTime = 0;
            	$locator = SGL_ServiceLocator::singleton();
            	$dbh = $locator->get('DB');
            	if (!mysql_ping($dbh->connection)) {
            		SGL_Error::pop();
            		SGL_DB::setConnection();
            	}
            }
		}

		/**
		 * Detect character encoding
		 *
		 * @param string $string
		 * @param mixde $encoding_list :::  encoding_list is list of character encoding.
		 *                                                Encoding order may be specified by array or comma separated list string.
		 *                                               If encoding_list is omitted, detect_order is used.
		 *
		 * @param bool $strict  :::  strict  specifies whether to use the strict encoding detection or not. Default is FALSE.
		 * @return The detected character encoding or FALSE if the encoding cannot be detected from the given string.
		 */
		public static function mb_detect_encoding($string, $encoding_list = null, $strict = false)
		{
			$enc = (RvsLibs_System::function_exists('mb_detect_encoding') === true)
			                 ?  mb_detect_encoding($string, $encoding_list, $strict)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'mb_detect_encoding')));
			if (empty($enc)) {
				//default endcoding = ASCII or ISO-8859-1 or UTF-8
				$enc = 'UTF-8';
			}
			return $enc;
		}

		/**
		 * Encodes an ISO-8859-1 string to UTF-8
		 *
		 * @param string $string
		 * @return  the UTF-8 translation of data .
		 */
		public static function utf8_encode($string)
		{
			if (RvsLibs_System::function_exists('utf8_encode') === true) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) !='utf-8') ? utf8_encode($string) : $string;
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'utf8_encode')));
		}

		/**
		 *  Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
		 *
		 * @param string $string
		 * @return Returns the ISO-8859-1 translation of data .
		 */
		public static function utf8_decode($string)
		{
			return (RvsLibs_System::function_exists('utf8_decode') === true)
			                 ? utf8_decode($string)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'utf8_decode')));
		}

		/**
		 * Convert all applicable characters to HTML entities
		 *
		 * @param string $string
		 * @param int $quote_style : the optional second quote_style  parameter lets you define what will be done with 'single' and "double" quotes.
		 *                                       It takes on one of three constants with the default being ENT_COMPAT:
		 *                                      ENT_COMPAT :      Will convert double-quotes and leave single-quotes alone.
		 *                                      ENT_QUOTES :     Will convert both double and single quotes.
		 *                                      ENT_NOQUOTES :  Will leave both double and single quotes unconverted.
		 * @param string $charset
		 * @param bool $double_encode
		 * @return the encoded string.
		 */
		public static function htmlentities($string, $quote_style = ENT_COMPAT, $charset = null, $double_encode = true)
		{
			if (RvsLibs_System::function_exists('htmlentities') === true) {
				if (phpversion() >= 5.2) {
					if (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8') {
						return htmlentities($string, $quote_style, 'UTF-8', $double_encode);
					} else {
						return htmlentities($string, $quote_style, $charset, $double_encode);
					}
				} elseif (phpversion() >= 4.1){
					if (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8') {
						return htmlentities($string, $quote_style, 'UTF-8');
					} else {
						return htmlentities($string, $quote_style, $charset);
					}
				} else {
					return htmlentities($string, $quote_style);
				}
			} else {
				return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'htmlentities')));
			}
		}

		/**
		 * Generates a storable representation of a value
		 *
		 * @param mixed $value
		 * @return Returns a string containing a byte-stream representation of value  that can be stored anywhere.
		 */
		public static function serialize($value)
		{
			return (RvsLibs_System::function_exists('serialize') === true)
			                     ? serialize($value)
			                     : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'serialize')));
		}

		/**
		 *  Creates a PHP value from a stored representation
		 *
		 * @param string $str
		 * @return  The converted value is returned, and can be a boolean, integer, float, string, array or object.
		 *              In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.
		 */
		public static function unserialize($str)
		{
			return (RvsLibs_System::function_exists('unserialize') === true)
			                 ? unserialize($str)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'unserialize')));
		}

		/**
		 * formatted string
		 * max 8 value
		 *
		 * @param string $format
		 * @param mixed $value1
		 * @param mixed $value2
		 * @param mixed $value3
		 * @return Returns a string produced according to the formatting string format .
		 */
		public static function sprintf($format, $value1 = null, $value2 = null, $value3 = null, $value4 = null, $value5 = null, $value6 = null, $value7 = null, $value8 = null)
		{
			return (RvsLibs_System::function_exists('sprintf') === true)
			                 ? sprintf($format, $value1, $value2, $value3, $value4, $value5, $value6, $value7, $value8)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'sprintf')));
		}

		/**
		 * Convert all HTML entities to their applicable characters
		 *
		 * @param string $string
		 * @param int $quote_style
		 * @param string $charset
		 * @return  If the optional split_length  parameter is specified,
		 *              the returned array will be broken down into chunks with each being split_length  in length,
		 *              otherwise each chunk will be one character in length.
		 *              FALSE is returned if split_length is less than 1.
		 *              If the split_length length exceeds the length of string , the entire string is returned as the first (and only) array element.
		 */
		public static function html_entity_decode($string, $quote_style = ENT_COMPAT, $charset = null)
		{
			if (RvsLibs_System::function_exists('html_entity_decode') === true) {
				if (phpversion() >= 5) {
					if ($charset == null) {
						return  html_entity_decode($string, $quote_style);
					} else {
						return html_entity_decode($string, $quote_style, $charset);
					}

				} else {
					return html_entity_decode($string, $quote_style);
				}
			} else {
				return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'html_entity_decode')));
			}
		}

		/**
		 * Convert a string to an array
		 *
		 * @param string $string
		 * @param int $split_length
		 * @return  If the optional split_length  parameter is specified,
		 *      the returned array will be broken down into chunks with each being split_length  in length
		 *      ,otherwise each chunk will be one character in length.
		 *      FALSE is returned if split_length is less than 1.
		 *      If the split_length length exceeds the length of string
		 *       , the entire string is returned as the first (and only) array element.
		 *
		 */
		public static function str_split($string, $split_length = 1)
		{
			if (RvsLibs_System::function_exists('str_split') === true) {
				//test utf-8 ใน unittest ใช้ได้ แต่ test ใน program ไม่ได
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8')
				                ? RvsLibs_String::str_split_utf8($string, $split_length)
				                : str_split($string, $split_length);
			}

			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'str_split')));
		}

		/**
		 * Convert a string to an array for UTF-8
		 *
		 * @param string $string
		 * @param int $string_length
		 * @return array
		 */

		public static function str_split_utf8($string,$string_length=1)
		{
			if(RvsLibs_String::strlen($string)>$string_length || !$string_length) {
				do {
					$parts[] = RvsLibs_String::mb_substr($string,0,$string_length);//RvsLibs_String::dbeSubstr($string,0,$string_length);
					$string = RvsLibs_String::mb_substr($string,$string_length);//RvsLibs_String::dbeSubstr($string,$string_length);
				} while($string != false);
			} else {
				$parts = array($string);
			}
			return $parts;
		}

		/**
		 * Find position of first occurrence of a string : ยังใช้กับ ภาษา จีน ยังไม่ได
		 *
		 * @param string $haystack : The string to search in
		 * @param mixed $needle : If needle  is not a string, it is converted to an integer and applied as the ordinal value of a character.
		 * @param int $offset : The optional offset  parameter allows you to specify which character in haystack  to start searching.
		 *              The position returned is still relative to the beginning of haystack .
		 * @return the position as an integer. If needle  is not found, strpos() will return boolean  FALSE.
		 */
		public static function strpos($haystack, $needle, $offset = 0)
		{
			if (RvsLibs_System::function_exists('strpos')) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($haystack)) =='utf-8')
				                ? mb_strpos($haystack, $needle, $offset)
				                : strpos($haystack, $needle, $offset);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strpos')));
		}

		/**
		 * Reverse a string
		 *
		 * @param string $string
		 * @return the reversed string.
		 */
		public static function strrev($string)
		{
			if (RvsLibs_System::function_exists('strrev') === true) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8')
				                ? RvsLibs_String::_utf8_strrev($string)
				                : strrev($string);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strrev')));
		}

		/**
		 * Reverse a string for UTF-8
		 *
		 * @param string $str
		 * @param bool $reverse_numbers
		 * @return reverse a string for UTF-8
		 */
		public static function _utf8_strrev($str, $reverse_numbers = true)
		{
			$pattern = ($reverse_numbers) ? '/./us' : '/(\d+)?./us';
			preg_match_all($pattern, $str, $ar);
			return join('',array_reverse($ar[0]));
		}

		/**
		 * Make a string's first character uppercase
		 *
		 * @param string $string
		 * @return Returns the resulting string.
		 */
		public static function ucfirst($string)
		{
		    if (RvsLibs_System::function_exists('ucfirst') === true) {
		        return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8')
		                      ? RvsLibs_String::_ucfirst_utf8($string)
		                      : ucfirst($string);
		    }
		    return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'ucfirst')));
		}

		/**
		 * Make a string's first character uppercase : fix utf-8
		 *
		 * @param string $string
		 * @param string $e
		 * @return Returns the resulting string. string is utf-8
		 */
		public static function _ucfirst_utf8($string, $e ='utf-8')
		{
			if (RvsLibs_System::function_exists('mb_strtoupper') && RvsLibs_System::function_exists('mb_substr') && !empty($string)) {
				$string = mb_strtolower($string, $e);
				$upper = mb_strtoupper($string, $e);
				preg_match('#(.)#us', $upper, $matches);
				$string = $matches[1] . RvsLibs_String::mb_substr($string, 1, mb_strlen($string, $e), $e);
			} else {
				$string = ucfirst($string);
			}
			return $string;
		}

		/**
		 * Uppercase the first character of each word in a string
		 *
		 * @param string $string
		 * @return the modified string.
		 */
		public static function ucwords($string)
		{
			if (RvsLibs_System::function_exists('ucwords') === true) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string)) =='utf-8')
				                ? RvsLibs_String::mb_convert_case($string, MB_CASE_TITLE, "UTF-8")
				                : ucwords($string);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'ucwords')));
		}

		/**
		 * Perform case folding on a string
		 *
		 * @param string $str
		 * @param int $mode : The mode of the conversion. It can be one of MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE.
		 * @param string $encoding : The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.
		 * @return A case folded version of string  converted in the way specified by mode .
		 */
		public static function mb_convert_case($str, $mode = MB_CASE_UPPER, $encoding = "UTF-8")
		{
			return (RvsLibs_System::function_exists('mb_convert_case') === true)
			                 ? mb_convert_case($str, $mode, $encoding)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'mb_convert_case')));

		}

		/**
		 * Find position of last occurrence of a char in a string
		 *
		 * @param string $haystack
		 * @param string $needle
		 * @param int $offset
		 * @return position of last occurrence of a char in a string
		 * @author duangdao.k
		 */
		public static function strrpos($haystack, $needle, $offset = 0)
		{
			if (RvsLibs_System::function_exists('strrpos') === true) {
				if (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($haystack)) =='utf-8') {
					return (RvsLibs_System::function_exists('mb_strrpos') === true)
					                   ? mb_strrpos($haystack, $needle, $offset)
					                   : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'mb_strrpos')));

				}

				return strrpos($haystack, $needle, $offset);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strrpos')));
		}

		/**
		 *  Finds the length of the first segment of a string consisting entirely of characters contained within a given mask.
		 *
		 * @param string $subject
		 * @param string $mask
		 * @param int $start
		 * @param int $length
		 * @return the length of the initial segment of str1  which consists entirely of characters in str2 .
		 * @author duangdao.k
		 */
		//TODO ยังไม่สามารถใช้กับ utf-8 ได้
		public static function strspn($subject, $mask = null, $start = null, $length = null)
		{
			return (RvsLibs_System::function_exists('strspn') === true)
			                 ? (empty($length))
			                 		? strspn($subject, $mask, $start)
			                 		: strspn($subject, $mask, $start, $length)
			                 : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strspn')));
		}

		/**
		 * Binary safe case-insensitive string comparison
		 *
		 * @param string $string1
		 * @param string $string2
		 * @return < 0 if str1  is less than str2 ; > 0 if str1  is greater than str2 , and 0 if they are equal.
		 * @author duangdao.k
		 */
		public static function strcasecmp($string1, $string2)
		{
			if (RvsLibs_System::function_exists('strcasecmp') === true) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string1)) =='utf-8'
                             && RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($string2)) == 'utf-8')
                                ? RvsLibs_String::strcasecmp_utf8($string1, $string2)
                                : strcasecmp($string1, $string2);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strcasecmp')));
		}

		/**
		 * fix utf-8 function strcasecmp
		 *
		 * @param string $string1
		 * @param string $string2
		 * @return < 0 if str1  is less than str2 ; > 0 if str1  is greater than str2 , and 0 if they are equal.
		 * @author duangdao.k
		 */
		public static function strcasecmp_utf8($string1, $string2)
		{
			return strcmp(RvsLibs_String::strtoupper($string1), RvsLibs_String::strtoupper($string2));
		}
		/**
		 * Find length of initial segment not matching mask
		 *
		 * @param string $str1 : The first string.
		 * @param string $str2 : The second string.
		 * @param int $start : The start position of the string to examine.
		 * @param int $length : The length of the string to examine.
		 * @return the length of the segment as an integer.
		 */
		//TODO ยังใช้กับ utf-8ไม่ได้
		public static function strcspn($str1, $str2, $start = null, $length = null)
		{
			return (RvsLibs_System::function_exists('strcspn') === true)
					? (empty($length))
						? strcspn($str1, $str2, $start)
						: strcspn($str1, $str2, $start, $length)
					: SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'strcspn')));
		}

		/**
		 * Dumps a string representation of an internal zend value to output
		 *
		 * @param mixed $variable
		 * @return No value is returned.
		 */
		//TODO unittest กับ function ค่ายังไม่ตรงกัน
		public static function debug_zval_dump($variable)
		{
			return (RvsLibs_System::function_exists('debug_zval_dump') === true)
			             ? debug_zval_dump($variable)
			             : SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'debug_zval_dump')));
		}

		/**
		 * Wraps a string to a given number of characters
		 *
		 * @param string $str
		 * @param int $width : The column width. Defaults to 75.
		 * @param string $break : The line is broken using the optional break  parameter. Defaults to '\n'.
		 * @param bool $cut : If the cut  is set to TRUE, the string is always wrapped at or before the specified width.
		 *              So if you have a word that is larger than the given width, it is broken apart. (See second example).
		 * @return  the given string wrapped at the specified column.
		 */
		public static function wordwrap($str, $width = 75, $break = "\n", $cut = false)
		{
			if (RvsLibs_System::function_exists('wordwrap') === true) {
				return (RvsLibs_String::strtolower(RvsLibs_String::mb_detect_encoding($str)) =='utf-8')
				                ? RvsLibs_String::_utf8_wordwrap($str, $width, $break)
				                : wordwrap($str, $width, $break, $cut);
			}

			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'wordwrap')));
		}

		/**
		 * Wraps a string to a given number of characters : fix utf-8
		 *
		 * @param string $str
		 * @param int $width
		 * @param string $break
		 * @return the given string wrapped at the specified column. String is utf-8
		 */
		public static function _utf8_wordwrap($str, $width = 75, $break = "\n")
		{
			$str = preg_split('#[\s\n\r]+#', $str);
			$len = 0;
			$string = '';
			foreach ($str as $val)
			{
				$val .= ' ';
				$tmp = mb_strlen($val, 'utf-8');
				$len += $tmp;
				if ($len >= $width) {
					$string .= $break . $val;
					$len = $tmp;
				} else {
					$string .= $val;
				}
			}
			return $string;
		}

		// when passed a string in this format [0-9]+ [A-Za-z]+ it returns it as bytes
		public static function returnBytes($val) {
			if (empty($val) === false) {
				$val = trim($val);
				$last = strtolower(preg_replace("/^[0-9]+\s*([A-Za-z]+)$/si", "$1", $val));//strtolower($val{strlen($val)-1});
				$val = preg_replace("/[^0-9]/si", "", $val);
				switch($last) {
					// The 'G' modifier is available since PHP 5.1.0
					case 't':
					case 'tb':
						$val *= 1024;
					case 'g':
					case 'gb':
						$val *= 1024;
					case 'm':
					case 'mb':
						$val *= 1024;
					case 'k':
					case 'kb':
						$val *= 1024;
				}
			}
			return $val;
		}

		public static function quoteSmart($value)
		{
			// Stripslashes
			// if magic quotes are enabled, any slashes are removed by $req->get();
			// optimize : nipaporn
			return "'" . mysql_real_escape_string($value) . "'";
		}

		public static function ctype_digit($text)
		{
			if (RvsLibs_System::function_exists('ctype_digit')) {
				return empty($text) ? false : ctype_digit($text);
			}

			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is not exists on your server.', 'vprintf', array('FUNCTION' => 'ctype_digit')));
		}

		/**
		 * replace url(http://xxxxxxx.com:2082/3rdparty  to url(/3rdparty
		 * replace url(http://cpanel.xxxxxxxx.com/3rdparty) to url(/3rdparty
		 *
		 * @param <string> $data
		 * @return <string> $data
		 */
		public static function removeCssFullURLWithPort($data)
		{
			$data = preg_replace("/url\((.*?):208[2|3]/", "url(", $data);
			$data = preg_replace("/url\((.*?)\/\/cpanel\.(.*)\/3rdparty/", "url(/3rdparty", $data);
			return $data;
		}

		public static function jsAddSlashes($str)
		{
			$pattern = array(
           "/\\\\/"  , "/\n/"    , "/\r/"    , "/\"/"    ,
           "/\'/"    , "/&/"    , "/</"    , "/>/"
           );
           $replace = array(
           "\\\\\\\\", "\\n"    , "\\r"    , "\\\""    ,
           "\\'"    , "\\x26"  , "\\x3C"  , "\\x3E"
           );
           return preg_replace($pattern, $replace, $str);
		}

		/**
		 * Remove space for the macthes HTML comment
		 * and return back to the preg_replace_callback function
		 *
		 * @package rvsitebuilder
		 * @author Pairote Manunphol
		 */
		public function removeSpaceCallback($matches)
		{
			return RvsLibs_String::strtolower(RvsLibs_String::str_replace(' ', '', $matches[1]));
		}

		public static function buildHtmlMsg($msg, $class = 'warning', $translate = true)
		{
			if ($translate == true) {
				$msg = RvsLibs_String::translate($msg);
			}
			$msg = RvsLibs_String::jsAddSlashes($msg);
			if ($class == "info") {
				$border = "successBorder";
				$cssName = 'success';
				$imgSuccess = '<img src="' . PUBLIC_IMG_URL . '/success.gif" alt="" width="30" height="30" hspace="15" />';
			} else {
				$border = "warningBorder";
				$cssName = 'error';
				$imgSuccess = '';
			}
			$msg =  '<div style="height: 10px;"></div><table border="0" cellspacing="0" cellpadding="0" class="' . $border . '" align="center" width="92%">
                                <tr>
                                    <td class="' . $cssName . '">' . $imgSuccess . $msg . '</td>
                                </tr>
                      </table>';

			$msg = str_replace("\n" , '', $msg);
			return $msg;
		}

	    /**
         * Split string by a regular expression
         *
         * @param mixed $pattern
         * @param mixed $subject
         * @param int $limit
         * @param int $flags
         * @param bool $flagTestErrorMode; Flag for test mode error
         * @param int $flagTestVersionPhp : Flag for test mode version
         * @return an array containing substrings of subject  split along boundaries matched by pattern.
         */
		public static function preg_split($pattern, $subject, $limit = -1, $flags = 0, $flagTestErrorMode = false)
		{
			if (RvsLibs_System::function_exists('preg_split') === true && $flagTestErrorMode === false) {
				return @preg_split($pattern, $subject, $limit, $flags);
			}
			return SGL::raiseError(RvsLibs_String::translate('Function %FUNCTION is undefine.', 'vprintf', array('FUNCTION' => 'preg_split')));
		}


    public static function quotedPrintableEncode($str)
    {
        return str_replace(
                    array(' ', "\r" ,"\n", '=', "\f", "\t", "\v")
                   ,array('%20', '%0D','%0A', '%3D', '%0C', '%09', '%0B')
                   , rawurlencode($str));
    }

    public static function quotedPrintableDecode($str)
    {
        return str_replace(
                   array("%20", "%0D","%0A", "%3D", "%0C", "%09", "%0B")
                   , array(' ', "\r" ,"\n", '=', "\f", "\t", "\v")
                   , rawurldecode($str));
    }

    public static function  brToNewline($str, $strReplace="\n")
    {
    	return str_replace('[[BR]]', $strReplace, $str);
    }

	public function getHtmlIsEmptyData($data)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $patternHtml = array('/<[\/\!]*?[^<>]*?>/si', '/\&nbsp;/si');
        $text = preg_replace($patternHtml, '', $data);
        $text = trim($text);
        //echo htmlspecialchars($text);
        return ($text == '') ? '' : $data;
    }

	public static function compilerFlixyError($sideValue, $output)
    {
    	$view = new SGL_Output();
    	$path = SGL_TMP_DIR ;
        $patFile = SGL_TMP_DIR . '/flexy.htm';
        $res = RvsLibs_System::rm(array('-f', $patFile));
    	if (SGL::isError($res) === true) {
    	    SGL_Error::pop();
    	}
    	if ($sideValue != '') {
    		RvsLibs_File::writeFile($patFile, $sideValue, 'w+');
    		$option = array('templateDir' => $path
    		              , 'fatalError' => HTML_TEMPLATE_FLEXY_ERROR_RETURN
    		              , 'allowPHP' => true);

    		$flexy = new HTML_Template_Flexy($option);
    		$masterTemplate = 'flexy.htm';
    		$ok = $flexy->compile($masterTemplate);
    		$data = $flexy->bufferedOutputObject($view, array());
    		if (SGL::isError($ok)) {
    			$output->errorFlixy = $ok->message;
    			$msg1 = RvsLibs_String::translate('The incorrect Tag insert');
    			$msg2 = RvsLibs_String::translate('Click here see error');
    			SGL::raiseMsg($msg1 . ' ' . $msg2, false, SGL_MESSAGE_ERROR);
    			return true;
    		} else {
    			return false;
    		}
    	}
    }

	}
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez