<?php
class Dbo {
	public $database;

	function connect() {
		global $db_engine;
		global $db_host;
		global $db_username;
		global $db_password;
		global $db_name;

		try {
			$this->database = new medoo(array(
					'database_type' => $db_engine,
					'database_name' => $db_name,
					'server' => $db_host,
					'username' => $db_username,
					'password' => $db_password,
					'charset' => 'utf8',
					'option' => array(
							\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION)));

			$this->database->query("SET sql_mode = ''");

			return true;
		}
		catch ( Exception $e ) {
			$this->error($e, "Errore durante la connessione al database", false);
		}
	}

	function clean($sql) {
		return $sql;
	}

	function prepare($sql, $quotes = true) {
		$result = $this->database->quote($sql);
		if(!$quotes) $result = substr($result, 1, strlen($result)-1);
		return $result;
	}

	function query($sql) {
		try {
			$this->database->query($this->clean($sql));
			$id = $this->last_inserted_id();
			if ($id == 0) return 1;
			else return $id;
		}
		catch ( PDOException $e ) {
			$this->error($e, $sql);
		}
	}

	function fetchArray($sql) {
		try {
			$result = $this->database->query($this->clean($sql))->fetchAll(PDO::FETCH_ASSOC);
			return $result;
		}
		catch ( PDOException $e ) {
			$this->error($e, $sql);
		}
	}

	function fetchRows($sql) {
		try {
			$result = $this->database->query($this->clean($sql))->fetchAll(PDO::FETCH_NUM);
			return $result;
		}
		catch ( PDOException $e ) {
			$this->error($e, $sql);
		}
	}

	function fetchRow($sql) {
		$result = $this->fetchArray($sql);
		if (is_array($result)) return $result[0];
		return $result;
	}

	function fetchNum($sql) {
		$result = $this->fetchArray($sql);
		if (is_array($result)) return count($result);
		return $result;
	}

	function last_inserted_id() {
		try {
			return $this->database->pdo->lastInsertId();
		}
		catch ( PDOException $e ) {
			$this->error($e, $sql);
		}
	}

	function multiQuery($filename, $delimiter = ';') {
		global $docroot;
		$inString = false;
		$escChar = false;
		$sql = '';
		$stringChar = '';
		$queryLine = array();
		$queryBlock = file_get_contents($filename);
		$sqlRows = explode("\n", $queryBlock);
		$delimiterLen = strlen($delimiter);
		do {
			$sqlRow = current($sqlRows) . "\n";
			$sqlRowLen = strlen($sqlRow);
			for($i = 0; $i < $sqlRowLen; $i ++) {
				if ((substr(ltrim($sqlRow), $i, 2) === '--') && ! $inString) {
					break;
				}
				$znak = substr($sqlRow, $i, 1);
				if ($znak === '\'' || $znak === '"') {
					if ($inString) {
						if (! $escChar && $znak === $stringChar) {
							$inString = false;
						}
					}
					else {
						$stringChar = $znak;
						$inString = true;
					}
				}
				if ($znak === '\\' && substr($sqlRow, $i - 1, 2) !== '\\\\') {
					$escChar = ! $escChar;
				}
				else {
					$escChar = false;
				}
				if (substr($sqlRow, $i, $delimiterLen) === $delimiter) {
					if (! $inString) {
						$sql = trim($sql);
						$delimiterMatch = array();
						if (preg_match('/^DELIMITER[[:space:]]*([^[:space:]]+)$/i', $sql, $delimiterMatch)) {
							$delimiter = $delimiterMatch[1];
							$delimiterLen = strlen($delimiter);
						}
						else {
							$queryLine[] = $sql;
						}
						$sql = '';
						continue;
					}
				}
				$sql .= $znak;
			}
		}
		while ( next($sqlRows) !== false );
		foreach ($queryLine as $singleQuery) {
			try {
				$this->database->query($this->clean($singleQuery));
			}
			catch ( PDOException $e ) {
				file_put_contents($docroot . '/setup.log', "[" . date("Y-m-d H:i:s") . "] [" . $_SERVER["SCRIPT_NAME"] . "] ERR: " . $e . " - " . $singleQuery . PHP_EOL . PHP_EOL, FILE_APPEND);
			}
		}
	}

	function close() {
		$this->database = null;
	}

	function error($e, $sql = "", $session = true) {
		global $docroot;
		global $rootdir;
		global $_SESSION;

		if ($e->getCode() != 'HY000') {
			$errore = $e . '<br>' . $sql;
			if ($session) array_push($_SESSION['errors'], "Si è verificato un'errore. Se il problema persiste siete pregati di chiedere assistenza tramite la sezione <a href=\"".$rootdir."/bug.php\">Bug</a>.<br><small>".$e->getMessage()."</small>");
			file_put_contents($docroot . '/mysql.log', "[" . date("Y-m-d H:i:s") . "] [" . $_SERVER["SCRIPT_NAME"] . "] ERR: " . str_replace("<br>", " - ", $errore) . PHP_EOL . PHP_EOL, FILE_APPEND);
		}
	}
}

function prepare($sql, $quotes = true) {
	global $dbo;
	return $dbo->prepare($sql, $quotes);
}

	

?>
