<?php

class Utils {
	const METRES_TO_FEET=3.2808399;
	const KILOMETRES_TO_MILES=0.621371192;

	public static function TableMaker($data, $buttonContent="Submit", $action="", $method="post") {
		ob_start();
		echo '<form action="', $action, '" method="', $method, '"><table>';
		foreach ($data as $datum) {
			if (!isset($datum['value']))
				$datum['value']="";
			if (!isset($datum['type']))
				$datum['type']="text";

			$html="";
			switch ($datum['type']) {
				case "select":
					$html="<select id=\"$datum[name]\" name=\"$datum[name]\">";
					foreach ($datum['options'] as $value=> $option) {
						$html.="<option value=\"$value\"";
						if ($value==$datum['value'])
							$html.="selected=\"selected\"";
						$html.=">$option</option>";
					}
					$html.="</select>";
					break;
				case "checkbox":
					$checked="";
					if ($datum['checked'])
						$checked='checked="checked"';
					$html="<input type=\"checkbox\" id=\"$datum[name]\" name=\"$datum[name]\" $checked />";
					break;
				default:
					$html="<input id=\"$datum[name]\" name=\"$datum[name]\" type=\"$datum[type]\" value=\"$datum[value]\" />";
					break;
			}
			if ($datum['type']=="hidden") {
				echo $html;
				continue;
			}

			echo '<tr><td><label for="', $datum['name'], '">', $datum['display'], ': </label></td>',
			'<td>', $html, '</td></tr>';
		}
		echo '<tr><td></td><td><button name="submit_form" type="submit">', $buttonContent, '</button></td></tr>',
		'</table></form>';
		return ob_get_clean();
	}

	public static function IsValidEmail($email) {
		if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email))
			return false;
		return true;
		list($userName, $mailDomain)=explode("@", $email);
		if (checkdnsrr($mailDomain, "MX"))
			return true;
		else
			return false;
	}

	public static function DeleteCookie($cookie) {
		unset($_COOKIE[$cookie]);
		setcookie($cookie, null, -1, '/');
	}

	public static function MakeStringUrlSafe($string) {
		$string=strtolower($string);
		$string=preg_replace('/[^a-zA-Z0-9\.]+/', '-', $string);
		return $string;
	}

	public static function MakeUniqueURL($table, $field, $string) {
		$PDO=BaseRepository::GetPDO();
		$baseUrl=Utils::MakeStringUrlSafe($string);
		$prep=$PDO->prepare("SELECT COUNT(*) FROM blog_posts WHERE post_url=?");
		$prep->execute(array($baseUrl));
		$found=$prep->fetchColumn()>0;
		$url=$baseUrl;
		$count=0;
		while ($found) {
			$prep->execute(array($url));
			$found=(int)$prep->fetchColumn()>0;
			if ($found) {
				$count++;
				$url=$baseUrl.'-'.$count;
			}
		}
		return $url;
	}

	//stolen (with a few edits) from http://stackoverflow.com/questions/5695145/how-to-read-and-write-to-an-ini-file-with-php
	public static function WriteINIFile($array, $path, $hasSections) {
		$content="";
		if ($hasSections) {
			foreach ($array as $key=> $elem) {
				$content.="\n[".$key."]\n";
				foreach ($elem as $key2=> $elem2) {
					if (is_array($elem2)) {
						for ($i=0; $i<count($elem2); $i++) {
							$content.=$key2."[]=".$elem2[$i]."\n";
						}
					} else if ($elem2=="")
						$content.=$key2."=\"\"\n";
					else
						$content.=$key2."=".$elem2."\n";
				}
			}
		} else {
			foreach ($array as $key=> $elem) {
				if (is_array($elem)) {
					for ($i=0; $i<count($elem); $i++) {
						$content.=$key."[]=".$elem[$i]."\n";
					}
				} else if ($elem=="")
					$content.=$key."=\"\"\n";
				else
					$content.=$key."=".$elem."\n";
			}
		}

		if (!$handle=fopen($path, 'w')) {
			return false;
		}

		$content=trim($content);
		$success=fwrite($handle, $content);
		fclose($handle);

		return $success;
	}

	public static function CloseOpenTags($html) {
		preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
		$openedtags=$result[1];
		preg_match_all('#</([a-z]+)>#iU', $html, $result);
		$closedtags=$result[1];
		$len_opened=count($openedtags);
		if (count($closedtags)==$len_opened) {
			return $html;
		}
		$openedtags=array_reverse($openedtags);
		for ($i=0; $i<$len_opened; $i++) {
			if (!in_array($openedtags[$i], $closedtags)) {
				$html.='</'.$openedtags[$i].'>';
			} else {
				unset($closedtags[array_search($openedtags[$i], $closedtags)]);
			}
		}
		return $html;
	}

	public static function FileUploadErrorToMessage($errorNo) {
		switch ($errorNo) {
			case UPLOAD_ERR_OK:
				return "Success";
			case UPLOAD_ERR_INI_SIZE:
			case UPLOAD_ERR_FORM_SIZE:
				return "Exceeded file size limit";
			case UPLOAD_ERR_PARTIAL:
				return "File not fully uploaded";
			case UPLOAD_ERR_NO_FILE:
				return "No file uploaded";
			case UPLOAD_ERR_NO_TMP_DIR:
				return "No temp dir";
			case UPLOAD_ERR_CANT_WRITE:
				return "Failed to write file to disc";
			case UPLOAD_ERR_EXTENSION:
				return "Upload stopped by PHP extension";
			default:
				return "Uknown error";
		}
	}

	public static function GenerateRandomString($length=10) {
		$characters='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength=strlen($characters);
		$randomString='';
		for ($i=0; $i<$length; $i++) {
			$randomString.=$characters[rand(0, $charactersLength-1)];
		}
		return $randomString;
	}

	public static function var_dump_email() {
		ob_start();
		debug_print_backtrace();
		var_dump(func_get_args());
		$output=ob_get_clean();
		mail("var_dump@robware.uk", "var_dump", $output);
	}

	public static function ParseSize($size) {
		$unit=preg_replace('/[^bkmgtpezy]/i', '', $size);
		$size=preg_replace('/[^0-9\.]/', '', $size);
		return round($unit ? $size*pow(1024, stripos('bkmgtpezy', $unit[0])) : $size);
	}

	public static function GetMaxUploadSize() {
		$maxUpload=Utils::ParseSize(ini_get('upload_max_filesize'));
		$maxPost=Utils::ParseSize(ini_get('post_max_size'));
		$memoryLimit=Utils::ParseSize(ini_get('memory_limit'));
		return min($maxUpload, $maxPost, $memoryLimit);
	}
}
