<?php
if (!defined('SECRET_KEY')){ header("HTTP/1.0 404 Not Found"); exit; }

###
### GENERAL FUNCTIONS
###


function detectAppleMobile($query = '') {

    $container = $_SERVER['HTTP_USER_AGENT'];
	
	// Single Query?
	if( $query!='' )
		return ( strpos( $container, $query ) > -1 );
	
    $useragents = array(
        "iphone",            // Apple iPhone
        "ipad",           	 // Apple iPad
        "ipod",              // Apple iPod touch
        "aspen",             // iPhone simulator
        "dream",             // Pre 1.5 Android
        "android",           // 1.5+ Android
        "cupcake",           // 1.5+ Android
        "blackberry9500",    // Storm
        "blackberry9530",    // Storm
        "opera mini",        // Experimental
        "webos",             // Experimental
        "incognito",         // Other iPhone browser
        "webmate"            // Other iPhone browser
    );
			
    foreach ( $useragents as $useragent ) {
        if ( preg_match('/'.$useragent.'/i', $container) )
            return true;
    }
    return false;
}


###
### Compatibility Library
###

if( !function_exists('stripTags') ):
function stripTags($t){

	$t = preg_replace(
		array(
			### add \n
			'@/p>@',
			'@/div>@',
			### Remove invisible content
			'@<head[^>]*?>.*?</head>@siu',
			'@<style[^>]*?>.*?</style>@siu',
			'@<script[^>]*?.*?</script>@siu',
			'@<object[^>]*?.*?</object>@siu',
			'@<embed[^>]*?.*?</embed>@siu',
			'@<applet[^>]*?.*?</applet>@siu',
			'@<noframes[^>]*?.*?</noframes>@siu',
			'@<noscript[^>]*?.*?</noscript>@siu',
			'@<noembed[^>]*?.*?</noembed>@siu',
			### Add line breaks before and after blocks
			'@</?((address)|(blockquote)|(center)|(del))@iu',
			'@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
			'@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
			'@</?((table)|(th)|(td)|(caption))@iu',
			'@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
			'@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
			'@</?((frameset)|(frame)|(iframe))@iu'
		),
		array( "/p><br/>", "/div><br/>",  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',  "$0", "$0", "$0", "$0", "$0", "$0","$0"), $t );
    
	return strip_tags( $t, '<n>' ); ### you can exclude some html tags here, in this case B and A tags     
}
endif;

if( !function_exists('_e') ):
function _e($t,$d='default'){
	if ( function_exists('gettext') )
		echo gettext($t);
	 else
	    echo $t;
}
endif;

if( !function_exists('__') ):
function __($t,$d='default'){
	if ( function_exists('gettext') )
		return gettext($t);
	 else
	    return $t;
}
endif;


if( !function_exists('get_locale') ):
function get_locale() {

		return (defined('LANG')) ? LANG : 'en_US';

}
endif;


if( !function_exists('load_textdomain') ):
function load_textdomain($l='') {

	if ( !function_exists('bindtextdomain') )
		return false;

	$codeset 	= 'UTF8'; 					 // warning ! not UTF-8 with dash '-'
	$l 			= ($l=='')?get_locale():$l;
	
	// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems
	if( !ini_get('safe_mode') ) {
		putenv('LANG='.$l.'.'.$codeset);
		putenv('LANGUAGE='.$l.'.'.$codeset);
	}
    bindtextdomain('recipeshelf', dirname(__FILE__).'/../locale');
	bind_textdomain_codeset('recipeshelf', $codeset);

	setlocale( LC_ALL, $l.'.'.$codeset );

	### echo "***".$l.$codeset.'***'.get_locale().textdomain('recipeshelf');

	if ( textdomain('recipeshelf') )
    	return true;
	return false;
}
endif;


### Remove TEMP dir
function deleteFile($f) {
    if (!file_exists($f)) return true;
    if (!is_dir($f) || is_link($f)) return unlink($f);
}
    

### if cookie set, load LANG
if( array_key_exists('rSlang', $_COOKIE) && $_COOKIE['rSlang']<>'' ){
	load_textdomain( $_COOKIE['rSlang'] );
}else
	load_textdomain();


if( !function_exists('current_time') ):
function current_time( $t, $gmt = 0 ) {
	switch ( $t ) {
		case 'mysql':
			return ( !$gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s' );
			break;
		case 'timestamp':
			return ( !$gmt ) ? time() : time() ;
			break;
	}
}
endif;


if( !function_exists('getGenericFROM') ):
function getGenericFROM() {
	$site = strtolower( $_SERVER['SERVER_NAME'] );
	if ( substr( $site, 0, 4 ) == 'www.' )
		$site = substr( $site, 4 );
	return 'recipeShelf@' . $site;
}
endif;


if( !function_exists('sanitize') ):
function sanitize($v,$removeQuotes=false,$removeSpecial=false) {
	if( $removeQuotes ){
		if(get_magic_quotes_gpc())
		   $v = stripslashes($v);
	    $v = str_replace(array('"','\''),array('',''),$v);
	    }

	if( $removeSpecial ){
		if(get_magic_quotes_gpc() && !$removeQuotes)
		   $v = stripslashes($v);
		$v = str_replace(array('&','"','\'','<','>',"\t",'\\'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;',''), $v);
	}
	
		$v = mysql_real_escape_string ($v);
	return $v;
}
endif;


if( !function_exists('unsanitize') ):
function unsanitize($v,$addSpecial=false) {
	if( $addSpecial )
		$v = str_replace(array('&amp;','&quot;','&#039;','&lt;','&gt;'), array('&','"','\'','<','>'), $v);
	return stripslashes($v);
}
endif;

function _rem_script($v){
	return preg_replace('/<\s*\/?\s*script\s*>/i', '****', $v );
}

if( !function_exists('sort_by_mtime') ):
### SORT
function sort_by_mtime($file1,$file2) {
    $time1 = filemtime($file1);
    $time2 = filemtime($file2);
    if ($time1 == $time2) {
        return 0;
    }
    return ($time1 < $time2) ? 1 : -1;
    }
endif;

if( !function_exists('_rem_magic_quote') ):
function _rem_magic_quote($v) {
	if( get_magic_quotes_gpc() )
		return stripslashes($v);
	else
		return $v;
    }
endif;

if( !function_exists('_add_magic_quote') ):
function _add_magic_quote($v) {
	if( get_magic_quotes_gpc() )
		return addslashes($v);
	else
		return $v;
    }
endif;

if( !function_exists('chkSession') ):
function chkSession() {
	@session_cache_limiter('private, must-revalidate');
	@session_cache_expire(0);
	if (!isset($_SESSION)){
		@session_start();
	}
}
endif;
chkSession();

if( !function_exists('call_debug') ):
function call_debug($v,$die=true){
	//echo '<div style="font-size:12px; color:#000; border-top:2px solid #444; font-weight:bold; background:#f5f5f5;">';
	echo '<br>'.$v.'<br/>';
	echo 'POST<pre>'.print_r($_POST,1).'</pre>';
	echo 'SESSION<pre>'.print_r($_SESSION,1).'</pre>';
	echo 'COOKIE<pre>'.print_r($_COOKIE,1).'</pre>';
	echo '</div>';
	if( $die ) 
		die();
}
endif;

if( !function_exists('esc_html') ):
function esc_html($string) {

	$string = (string) $string;

	if ( 0 === strlen( $string ) ) {
		return '';
	}
	
	if ( !preg_match( '/[&<>"\']/', $string ) ) {
		return $string;
	}

	$quote_style 	= ENT_QUOTES;
	$charset 		= 'UTF-8';

	$string = @htmlspecialchars( $string, $quote_style, $charset );
	return $string;
    }
endif;

if( !function_exists('esc_sql') ):
function esc_sql($sql) {
	$cleanSql = mysql_real_escape_string( $sql );
    return $cleanSql;
    }
endif;

if( !function_exists('esc_url') ):
function esc_url( $url, $_context = 'display' ) {
	
	if ( '' == $url )
		return $url;
		
	$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
	$strip = array('%0d', '%0a', '%0D', '%0A');
	$url = _rec_replace($strip, $url);
	$url = str_replace(';//', '://', $url);
	
	// Display specifics
	if ( 'display' == $_context ) {
		$url = str_replace( '&amp;', '&#038;', $url );
		$url = str_replace( "'", '&#039;', $url );
	}
	return $url;
}
function _rec_replace( $a, $v ) {
	$f = true;
	$v = (string) $v;
	while ( $f ) {
		$f = false;
		foreach ( (array) $a as $val ) {
			while ( strpos( $v, $val ) !== false ) {
				$f = true;
				$v = str_replace( $val, '', $v );
			}
		}
	}
	return $v;
}
endif;

### $_ data sanatation
### $newGET = cleanGlobals( $_GET );

if( !function_exists('cleanGlobals') ):

    function parseCleanKey( $key )
    {
        if ( $key == "" )
        {
            return "";
        }

        $key = htmlspecialchars( urldecode( $key ) );
        $key = str_replace( "..", "", $key );
        $key = preg_replace( "/\_\_(.+?)\_\_/", "", $key );
        $key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );

        return $key;
    }

    function parseCleanValue( $val )
    {
        if ( $val == "" )
        {
            return "";
        }

        $val = str_replace( "&#032;", " ", stripslashes( $val ) );

        # Convert all carriage return combos
        $val = str_replace( array( "\r\n", "\n\r", "\r" ), "\n", $val );
        $val = str_replace( "&", "&amp;", $val );
        $val = str_replace( "<!--", "&#60;&#33;--", $val );
        $val = str_replace( "-->", "--&#62;", $val );
        $val = str_ireplace( "<script", "&#60;script", $val );
        $val = str_replace( ">", "&gt;", $val );
        $val = str_replace( "<", "&lt;", $val );
        $val = str_replace( '"', "&quot;", $val );
        $val = str_replace( "\n", "<br />", $val ); // Convert literal newlines
        $val = str_replace( "$", "&#036;", $val );
        $val = str_replace( "!", "&#33;", $val );
        $val = str_replace( "'", "&#39;", $val ); // IMPORTANT: It helps to increase sql query safety.

        return $val;
    }
    function cleanGlobals( $data, $iteration = 0 )
    {
        if ( $iteration >= 10 )
        {
            return;
        }

        foreach ( $data as $k => $v )
        {
            if ( is_array( $v ) )
            {
                $data[$k] = cleanGlobals( $data[$k], ++$iteration );
            }
            else
            {
                # Null byte characters
                $v = str_replace( chr( '0' ), '', $v );
                $v = str_replace( "\0", '', $v );
                $v = str_replace( "\x00", '', $v );

                $v = str_replace( '%00'   , '', $v );

                # File traversal
                $v = str_replace( "../", "&#46;&#46;/", $v );

                /* RTL override */
                $v = str_replace( '&#8238;', '', $v );

                $data[parseCleanKey( $k )] = parseCleanValue( $v );
            }
        }
	return $data;
    }
endif;	

/* NONCE */

if ( !function_exists('rS_create_nonce') ) :
	function rS_nonce_field( $action = -1, $name = "_rSnonce", $referer = true , $echo = true ) {
		$name = esc_html( $name );
		$nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . rS_create_nonce( $action ) . '" />';
		if ( $echo )
			echo $nonce_field;

		if ( $referer )
			rS_referer_field( $echo );

		return $nonce_field;
	}
	function curPageURL() {
	    $pageURL = 'http';
	    if (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] == 'on') {$pageURL .= 's';}
	    $pageURL .= '://';
	    if ($_SERVER['SERVER_PORT'] != '80')
	        $pageURL .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
	    else
	        $pageURL .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

	    return strtolower( substr( $pageURL,0 , strrpos ($pageURL,'/') ) );
	}
	function rS_referer_field( $echo = true ) {
		$ref = esc_html( esc_url(curPageURL()) );
		$referer_field = '<input type="hidden" name="_rS_http_referer" value="'. $ref . '" />';

		if ( $echo )
			echo $referer_field;
		return $referer_field;
	}
	function rS_get_referer() {
		$ref = '';
		if ( ! empty( $_REQUEST['_rS_http_referer'] ) )
			$ref = $_REQUEST['_rS_http_referer'];
		else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
			$ref = strtolower( $_SERVER['HTTP_REFERER'] );

		if ( $ref !== curPageURL() )
			return $ref;
		return false;
	}
	function rS_create_nonce($action = -1,$uname="rS") {
		global $user;
		
		if( is_object($user) ){
			if ( $user->_logged_in )
				$uname = substr($user->_user_name,0,2);
		}

		$uid = (int) ( ord(substr($uname,0,1)) + ord(substr($uname,1,1)) );

		#echo "<br>create UID=".$uid; //debug
		
		$i = rS_nonce_tick();

		$hash = substr(rS_hash($i . $action . $uid, 'nonce'), -12, 10);
		
		//debug
		//if( is_object($user) && $user->_logged_in )
		//	$hash = $hash .' *** ' .$user->_logged_in.' '.$uname.' '. $i .'+'.$action .'+'. $uid;

		return $hash;
	}
	function check_ajax_referer( $action = -1, $die = true, $uname="rS" ) {
		
		$_nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_rSnonce'];
		$result = rS_verify_nonce( (string)$_nonce, $action, $uname );
		//debug_backtrace
		//die('debug: '.$_nonce.$action.$uname);

		if ( $die && false == $result )
			die('-1');

		return $result;
	}
	function check_admin_referer($action = -1, $query_arg = '_rSnonce') {
		global $rSdb;
		$adminurl = $rSdb->getSiteURL(); 
		$referer = strtolower(rS_get_referer());
		#echo '<br>chk SITEURL='.$adminurl; // debug 
		#echo '<br>chk REFERER='.$referer; // debug 
		#echo '<br>CURPageURL='.curPageURL();
		#echo '<br><pre>'.print_r($_REQUEST,1).'</pre>';
		
		$result = isset($_REQUEST[$query_arg]) ? rS_verify_nonce($_REQUEST[$query_arg], $action) : false;
		
		if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
			$html = '<div class="title">'. __( 'recipeShelf Failure Notice','recipeshelf' ).'</div>'.__('Direct access to recipeShelf files is denied.','recipeshelf');
			$rSdb->dieNow( $html, false, '' ); 
			die();
		}
		return $result;
	}
	function rS_verify_nonce($nonce, $action = -1, $uname="rS") {
		global $user;

		if( is_object($user) ){
			if ( $user->_logged_in )
				$uname = substr($user->_user_name,0,2);
		}

		$uid = (int) ( ord(substr($uname,0,1)) + ord(substr($uname,1,1)) );
			
		$i = rS_nonce_tick();

		#echo 'uid='.$uid.', hash='.substr(rS_hash($i . $action . $uid, 'nonce'), -12, 10);

		$last12 = substr(rS_hash($i . $action . $uid, 'nonce'), -12, 10);
		$last24 = substr(rS_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10);
		
		// generated 0-12 hours ago
		if ( $last12 == $nonce )
			return 1;
		// generated 12-24 hours ago
		if ( $last24 == $nonce )
			return 2;

		//debug
		//die('debug: '.print_r($user,1));
		//die('debug: '.$user->_logged_in.' '.$uname.' '. $i .'+'.$action .'+'. $uid .'-'.$last12.'/'.$last24);
			
		return false;
	}
	function rS_nonce_tick() {
		$nonce_life = 86400;
		return ceil(time() / ( $nonce_life / 2 ));
	}	
	function rS_hash($data, $scheme = 'auth') {
		$salt = rS_salt($scheme);
		return hash_hmac('md5', $data, $salt);
	}
	function rS_salt($scheme = 'auth') {
		$secret_key = '';
		if ( defined('SECRET_KEY') && ('' != SECRET_KEY) )
			$secret_key = SECRET_KEY;
		if ( defined('NONCE_SALT') && ('' != NONCE_SALT) )
			$salt = hash_hmac('md5', NONCE_SALT, NONCE_KEY);		
		return  $secret_key . $salt;
	}	
endif;

?>