<?php
	// tomekk
        // http://tomekk.org/
        // GPL - http://www.gnu.org/copyleft/gpl.html
        // last fix: 02-08-2013

	class pgin
	{
		// separate arrays for GET and POST
		var $p = array();
		var $g = array();

		// some defines at the start
		function pgin()
		{
			define('HSC', 'html_special_chars');
		        define('NR', 'numbers');
		        define('LT', 'letters');
		        define('LTNR', 'letters_numbers');
		        define('CSR', 'custom_regexp');
		        define('ALLC', 'all_chars');
		}

		// main parse function (input args)
		function parse( $src, $vars )
		{
			// temp array for vars
			$parsed_out = array();

			// which method?
			switch ($src)
			{
				case 'p':
					$method = $_POST;
					break;
				case 'g':
					$method = $_GET;
					break;
			}
	
			// only GET or POST
			if (isset($method))
			{
				foreach ($vars as $var => $type)
				{
					// what to do with the data - switches
					$data_format = '';

					// quick check if we need to do smth with the data
					// and remove our special format chars for further processing
					if (strpos($var, '^') !==  FALSE)
					{
						$var = str_replace('^', '', $var);
						$data_format .= 'u';
					}
					
					if (strpos($var, ',') !==  FALSE)
					{
						$var = str_replace(',', '', $var);
						$data_format .= 'l';
					}
					
					if (strpos($var, '-') !==  FALSE)
					{
						$var = str_replace('-', '', $var);
						$data_format .= 't';
					}

					// only for custom_regexp - extracts key as type and value as pattern
					if (is_array($type))
					{
						$csr_key = key($type);
						$csr = $type[$csr_key];
						$type = $csr_key;
					}

					// input array arg is set, so go on
					if (isset($method[$var]))
					{
						// format data 
						if (strpos($data_format, 'u') !==  FALSE) $method[$var] = strtoupper($method[$var]);
						if (strpos($data_format, 'l') !==  FALSE) $method[$var] = strtolower($method[$var]);
						if (strpos($data_format, 't') !==  FALSE) $method[$var] = trim($method[$var]);

						// empty as default
						$parsed_out[$var] = '';

						// switch through types
						switch ($type)
						{
							case 'html_special_chars':
								$parsed_out[$var] = htmlspecialchars($method[$var], ENT_QUOTES);
								break;
							case 'numbers':
								if (preg_match("/^[0-9]+$/D", $method[$var])) $parsed_out[$var] = $method[$var];
								break;
							case 'letters':
								if (preg_match("/^[a-z]+$/Di", $method[$var])) $parsed_out[$var] = $method[$var];
								break;
							case 'letters_numbers':
								if (preg_match("/^[a-z0-9]+$/Di", $method[$var])) $parsed_out[$var] = $method[$var];
								break;
							case 'custom_regexp':
								if (preg_match($csr, $method[$var])) $parsed_out[$var] = $method[$var];
								break;
							case 'all_chars':
								$parsed_out[$var] = $method[$var];
								break;
						}
					}
				}

				// assign proper array
				($src == 'p') ? $this->p = $parsed_out : $this->g = $parsed_out;
			}
		}
	}
?>
