<?php

/* Generic string processors */

if(!function_exists('http_build_query')) {
	function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
		$res = array();
		foreach ((array)$formdata as $k=>$v) {
			$tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
			if ($key) $tmp_key = $key.'['.$tmp_key.']';
			$res[] = ( ( is_array($v) || is_object($v) ) ? http_build_query($v, null, $tmp_key) : $tmp_key."=".urlencode($v) );
		}
		$separator = ini_get('arg_separator.output');
		return implode($separator, $res);
	}
}

function wp_get_referer() {
	if ( !empty( $_SERVER['HTTP_REFERER'] ) ) return $_SERVER['HTTP_REFERER'];
	return false;
}

function clean_url( $url, $protocols = null ) {
	if ('' == $url) return $url;
	$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%]|i', '', $url);
	$strip = array('%0d', '%0a');
	$url = str_replace($strip, '', $url);
	if ( strpos($url, '://') === false && substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
		$url = 'http://' . $url;
	
	$url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);
	return $url;
}

// Like htmlspecialchars except don't double-encode HTML entities
function mt_specialchars( $text, $quotes = false ) {
	
	$text = str_replace('&&', '&#038;&', $text);
	$text = str_replace('&&', '&#038;&', $text);
	$text = preg_replace('/&(?:$|([^#])(?![a-z1-4]{1,8};))/', '&#038;$1', $text);
	$text = str_replace('<', '&lt;', $text);
	$text = str_replace('>', '&gt;', $text);
/*	if ( 'double' === $quotes ) {
		$text = str_replace('"', '&quot;', $text);
	} elseif ( 'single' === $quotes ) {
		$text = str_replace("'", '&#039;', $text);
	} else
 */
		if ( $quotes ) {
		$text = str_replace('"', '&quot;', $text);
		$text = str_replace("'", '&#039;', $text);
	}
	return $text;
}

function add_query_arg($param,$value,$url) {
	return $url . ( (strpos( $url, '?' )===false)  ? '?' : '&' ) . $param . '=' . urlencode($value);
}

function Excerpt( $excerpt, $maxlen = 455) {
	$excerpt = strip_tags( $excerpt );
	if (strlen($excerpt) > $maxlen) {
		$excerpt = substr($excerpt,0,$maxlen-3) . '...';
	}
	return $excerpt;
}

/* Type names may consist of digits, letters, -, ', :, and whitespace */
function sanitize_type_name( $name ) {
	return preg_replace( '/[^\d\w\':\s-]+/', '', $name );
}

function check_type_name( $name ) {
	global $error;
	
	if( $name == '' )
		$error.='A type must be supplied with a name, but none was given. Valid characters include letters, numbers, apostrophes, colons, and whitespace.';
	elseif ( $name !== sanitize_type_name($name) )
		$error.='Supplied name contains invalid characters. Valid characters include letters, numbers, apostrophes, colons, and whitespace.';
	else
		return true;
	return false;
}

function _objectInArrayWithIdExists( $id, $arrobj ) {
	foreach( $arrobj as $v )
		if( $v->id == $id ) return true;
	return false;
}

?>