<?php
	require_once('config.php');
	
	toLog('старт');
	
	$link = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
	if (mysqli_connect_errno($link)) {
		toLog("Can't connect to MySQL: " . mysqli_connect_error());
		exit;
	}
	
	$maxinsert = 1000;
	
	$link->set_charset('utf8');
	
	$zipfile = 'db-backup-'.date("Y-m-d_H-i-s").'.sql';
	$file = DIR_BACKUP.'db-backup-'.date("Y-m-d_H-i-s").'.sql';
	toLog("сохраняю " . $file);
	
	$cr = chr(13).chr(10);

	$tables = array();
	$result = mysqli_query($link,'SHOW TABLES');
	while($row = mysqli_fetch_row($result)){
		if(substr($row[0],0,strlen(DB_PREFIX))==DB_PREFIX){
			$tables[] = $row[0];
		}
	}

    foreach($tables as $table){

		$return= 'DROP TABLE IF EXISTS `'.$table.'`;';
        
		$result = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));
        $return.= $cr.$cr.$result[1].";".$cr.$cr;
		
	    $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);
		if ($num_rows>0){
			$return.= 'INSERT INTO `'.$table.'` VALUES';
			$i=0;
			while($row = mysqli_fetch_row($result)){
				$i++;
				for($j=0; $j<$num_fields; $j++){
					if(is_null($row[$j])){
						$row[$j] = 'null';
/*					}elseif(is_numeric($row[$j])){
						$row[$j] = $link->real_escape_string($row[$j]);
*/					}else{
						$row[$j] = "'" . $link->real_escape_string($row[$j]) . "'";
					}
				}
				$return.= '(' . implode(',',$row) . ')';
				
				if ($i==$num_rows){
					$return.= ";".$cr;
				}elseif ($i%$maxinsert==0){
					$return.= ";" . $cr . 'INSERT INTO ' . $table . ' VALUES';
				}else{
					$return.= ",".$cr;
				}
			}
		}
        $return .= $cr.$cr.$cr;
		file_put_contents($file, $return, FILE_APPEND | LOCK_EX);
    }
	toLog("всего " . count($tables));

	if(extension_loaded('zip')){
		$zip = new ZipArchive();
		mkdir ( DIR_BACKUP . date("Y"), 0777);
		mkdir ( DIR_BACKUP . date("Y/Y-m"), 0777);
		mkdir ( DIR_BACKUP . date("Y/Y-m/Y-m-d"), 0777);
		if($zip->open(DIR_BACKUP . date("Y/Y-m/Y-m-d") . '/' . $zipfile . '.zip', ZIPARCHIVE::CREATE)==TRUE){
			$zip->addFile($file, DIR_TO_BACKUP);
			$zip->close();
			unlink ($file);
		}
	}
	toLog("запаковано, стоп");
	toLog('');

	
	function toLog($text){
		file_put_contents(DIR_BACKUP . date("Y/Y-m/") . 'backup.log', chr(13) . chr(10) . date('d/m/Y H:i:s') . chr(9) . 'база:' . chr(9) . $text, FILE_APPEND | LOCK_EX);
	}
?>
