<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 
/**
 * Backup controller
 * 
 * Yii module to backup, restore databse
 * 
 * @version 1.0
 * 
 * @author Amaney
 * @package application.controllers
 */
class BackupController extends Controller {

    /**
     * @var array Array of tables names
     */
    public $tables = array();
    /**
     * @var File The text file we create it for puting the backup result in
     */
    public $fp;
    /**
     * @var String The name of the backup file
     */
    public $file_name;
    /**
     * @var String The full path of the backup file
     */
    public $_path = null;
    /**
     * @var String The temporary name of the backup file
     */
    public $back_temp_file = 'db_backup_';
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
	return array(
	    'accessControl', // perform access control for CRUD operations
	);
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
	return array(
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('index', 'delete', 'download'),
		'roles' => array(User::SYSTEM_ADMIN_ROLE),
	    ),
	);
    }

    /**
     * Deletes a particular model.
     * If deletion is successful or not , the browser will be give a message
     * @param string $file the file we want to delete it 
     */
    public function actionDelete($file = null) {
	$settings_array = Setting::getSettingsArray();
	$path = (isset($settings_array["backup_file_path"]) && ($settings_array["backup_file_path"] != null) && ($settings_array["backup_file_path"] != '')) ? $settings_array["backup_file_path"] . '/' : './protected/backup/';

	$success_msg = Yii::t('default', 'The Backup file ({n}) has been deleted successfully ', $file);
	$failer_msg = Yii::t('default', 'The Backup file ({n}) couldn\'t be deleted , File Not Found ', $file);

	if (isset($file)) {
	    $zip_file = $path . $file;
	    if (file_exists($zip_file)) {
		unlink($zip_file);
		Yii::app()->user->setFlash('success', $success_msg);
		echo "<div class='flash-msg'>" . "<br>";
		$this->widget('bootstrap.widgets.TbAlert');
		echo "</div>";
	    } else {
		$path = './protected/backup/';
		$zip_file = $path . $file;
		if (file_exists($zip_file)) {
		    unlink($zip_file);
		    Yii::app()->user->setFlash('success', $success_msg);
		    echo "<div class='flash-msg'>" . "<br>";
		    $this->widget('bootstrap.widgets.TbAlert');
		    echo "</div>";
		} else {
		    Yii::app()->user->setFlash('error', $failer_msg);
		    echo "<div class='flash-msg'>" . "<br>";
		    $this->widget('bootstrap.widgets.TbAlert');
		    echo "</div>";
		}
	    }
	} else {
	    Yii::app()->user->setFlash('error', $failer_msg);
	    echo "<div class='flash-msg'>" . "<br>";
	    $this->widget('bootstrap.widgets.TbAlert');
	    echo "</div>";
	}
    }

    /**
     * Lists all files.
     */
    public function actionIndex() {
	$settings_array = Setting::getSettingsArray();
	$path = isset($settings_array["backup_file_path"]) && $settings_array["backup_file_path"] != null && $settings_array["backup_file_path"] != '' ? $settings_array["backup_file_path"] : Yii::app()->basePath . '\\backup\\';
	$slash = ( substr($path, -1) == "\\") ? "" : "\\";
	$path .= $slash;
	$path_inside_project = Yii::app()->basePath . '\\backup\\';
	$list = glob($path . '*.zip');
	$list = array_map('basename', $list);
	sort($list);

	$dataArray = array();
	foreach ($list as $id => $filename) {
	    $columns = array();
	    $columns['id'] = $id;
	    $columns['name'] = basename($filename);
	    $columns['size'] = floor(filesize($path . $filename) / 1024) . ' KB';
	    $columns['create_time'] = date(DATE_RFC822, filectime($path . $filename));
	    //this colmun is only for ordering purpose
	    $columns['create_time_order'] = date(filectime($path . $filename));
	    $columns['path'] = $path;
	    $dataArray[] = $columns;
	}
	//------------------------------------------------
	$list = glob($path_inside_project . '*.zip');
	$list = array_map('basename', $list);
	sort($list);

	foreach ($list as $id => $filename) {
	    $columns = array();
	    $columns['id'] = $id;
	    $columns['name'] = basename($filename);
	    $columns['size'] = floor(filesize($path_inside_project . $filename) / 1024) . ' KB';
	    $columns['create_time'] = date(DATE_RFC822, filectime($path_inside_project . $filename));
	    $columns['path'] = $path_inside_project;
	    //this colmun is only for ordering purpose
	    $columns['create_time_order'] = date(filectime($path_inside_project . $filename));
	    $dataArray[] = $columns;
	}

	//sort files according the recent date
//        $sort = new CSort;
	$sort = new CSort();
	$sort->attributes = array(
	    '*',
	    'create_time_order' => array(
		'asc' => 'create_time_order',
		'desc' => 'create_time_order desc',
	    ),
	    'create_time' => array(
		'asc' => 'create_time',
		'desc' => 'create_time desc',
	    ),
	    'id' => array(
		'asc' => 'id',
		'desc' => 'id desc',
	    ),
	    'name' => array(
		'asc' => 'name',
		'desc' => 'name desc',
	    ),
	    'size' => array(
		'asc' => 'size',
		'desc' => 'size desc',
	    ),
	);

	$dataProvider = new CArrayDataProvider($dataArray, array('id' => 'backupFiles', 'sort' => $sort));

	$this->render('index', array(
	    'dataProvider' => $dataProvider,
	));
    }

    /**
     * Download a file.
     * @param string $file the file we want to download it
     */
    public function actionDownload($file = null, $path = null) {
	if ($path == null) {
	    $settings_array = Setting::getSettingsArray();
	    $path = (isset($settings_array["backup_file_path"]) && ($settings_array["backup_file_path"] != null) && ($settings_array["backup_file_path"] != '')) ? $settings_array["backup_file_path"] . '/' : './protected/backup/';
	}

	if (isset($file)) {
	    $sqlFile = $path . $file;
	    if (file_exists($sqlFile)) {
		$request = Yii::app()->getRequest();
		$request->sendFile(basename($sqlFile), file_get_contents($sqlFile));
	    }
	}
	throw new CHttpException(404, Yii::t('app', 'File not found'));
    }

}