<?php
	require '../redbean/rb.php'; 			
	R::setup("sqlite:database.txt"); 
	
	function camelToLower($string) {
		$str = str_replace("_", ' ', $string);
		$str = preg_replace("/[^A-Za-z ]/", '', $str);
		$str = str_replace(" ", '', $str);
		return $str;
	}
	
	function lowerToCamel($string) {
		$str = str_replace("_", ' ', $string);
		$str = ucwords(strtolower($str));
		$str = str_replace(" ", '', $str);
		return $str;
	}
	
	function allToLower($string) {
		$str = trim($string);
		$str = str_replace("_", ' ', $str);
		$str = preg_replace('/\s\s+/', ' ', $str);
		$str = preg_replace("/[^A-Za-z ]/", '', $str);
		$str = str_replace(" ", '_', $str);
		$str = strtolower($str);
		return $str;
	}
	
	function lowerToName($string) {
		$str = ucwords(strtolower($string));
		$str = str_replace("_", ' ', $str);
		return $str;
	}

	function scaffold_check_md5($name) {
		$q = "select * from md5 where name='$name'";
		$file = R::getAll($q);
		foreach ($file as $f) {
			$content = file_get_contents($f['path']);
			if ($f['md5'] != md5($content)) return "changed";
		}
		return "unchanged";
	}
	
	$file = $_GET['file'];
	if ($file != "") {
		error_reporting(0);
		chmod($file, 0777);
		error_reporting(E_ALL ^E_NOTICE);
		
		if (get_magic_quotes_gpc()) {
			$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
			while (list($key, $val) = each($process)) {
				foreach ($val as $k => $v) {
					unset($process[$key][$k]);
					if (is_array($v)) {
						$process[$key][stripslashes($k)] = $v;
						$process[] = &$process[$key][stripslashes($k)];
					} else {
						$process[$key][stripslashes($k)] = stripslashes($v);
					}
				}
			}
			unset($process);
		}

		file_put_contents($file,$_POST['content']);
		
		echo "success";
		$path = explode("/",$_POST['path']);
		$file = str_replace(".php","",$path[3]);
		$file = allToLower($file);
		if (scaffold_check_md5($file) == "changed") echo "|$file";
		else echo "|null"; 
	}
?>

