<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

class System
{

	public function backupDatabase($tables = "*"){
		Logger::debug('	--> DB_BACKUP: ' . $tables);
		$return = "";
		$db = DBConnector::getZendDbConnection();

		//get all of the tables
		if($tables == '*') {
			$tables = array();
			
			$selectString = "SHOW TABLES";
			$query = $db->query($selectString, $db::QUERY_MODE_EXECUTE);
			// print_r($query);
			$res = $query->toArray();
			// print_r($res);
			foreach ($res as $key => $val) {
				$tables[] = $val['Tables_in_' . DATABASE_DB_DBNAME];
			}
			// print_r($tables);
		}else{
			$tables = is_array($tables) ? $tables : explode(',',$tables);
		}

		//cycle through
		foreach($tables as $table){
			$pos = stripos($table, DATABASE_DB_TABLEPREFIX);
			if ($pos !== false){
				$sql = new Zend\Db\Sql\Sql($db);
				$select = $sql->select();
				$select->from($table);

				$selectString = $sql->getSqlStringForSqlObject($select);
				$results = $db->query($selectString, $db::QUERY_MODE_EXECUTE);
				$num_fields = $results->getFieldCount();
				$arr = $results->toArray();

				$return.= 'DROP TABLE '.$table.';';
				
				$selectString = "SHOW CREATE TABLE " . $table;
				$query = $db->query($selectString, $db::QUERY_MODE_EXECUTE);
				// print_r($query);
				$res = $query->toArray();
				// print_r($res);

				// $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
				// $return.= "\n\n".$res[1].";\n\n";
				foreach ($res as $key => $val){
					$return .= "\n\n".$val['Create Table'].";\n\n";
				}

				foreach($arr as $row => $val){
					$return.= 'INSERT INTO '.$table.' VALUES(';
					$j=0;
					foreach ($val as $k => $v)
					{
						$dd = addslashes($v);
						// $dd = preg_replace("\n","\\n",$dd);
						if (isset($dd)) { $return.= '"'.$dd.'"' ; } else { $return.= '""'; }
						if ($j<($num_fields-1)) { $return.= ','; }
						$j++;
					}
					$return.= ");\n";
				}
				$return.="\n\n\n";
			}
		}

		$baseFilename = DBBACKUP_FILENAME;
        switch(strtolower(DBBACKUP_FREQUENCY)){
            case 'daily':
                $logFilename = $baseFilename.'_'.date('Y_m_d') . ".sql";
                break;
             case 'weekly':
                $logFilename = $baseFilename.'_'.date('Y_W') . ".sql";
                break;
             case 'monthly':
                $logFilename = $baseFilename.'_'.date('Y_m') . ".sql";
                break;
             case 'yearly':
                $logFilename = $baseFilename.'_'.date('Y') . ".sql";
                break;
             default:
                $logFilename = $baseFilename;
		}
		//save file only if NOT exist
		if (!file_exists($logFilename)){
			$handle = fopen($logFilename,'w+');
			fwrite($handle,$return);
			fclose($handle);
			Logger::info('		Backup done. Here is the file: ' . $logFilename);
			Logger::debug('		Backup criteria: ' . DBBACKUP_FREQUENCY);
		}else{
			Logger::debug('		Backup not needed. File already exists: ' . $logFilename);
		}
		Logger::debug('	<-- DB_BACKUP');
	}
	
	public function deleteFilesOlderThan($fname, $days) {
		$files = glob($fname);
		$time  = time();

		Logger::debug('		Nb of files found : ' . count($files));
		foreach ($files as $file) {
			if (is_file($file)) {
				if ($time - filemtime($file) >= 60*60*24*$days) {
					unlink($file);
				}
			}
		}
	}
}
