<?php
//Chemin vers mysqldump.exe, utile sur en environnement windows uniquement
define('MYSQL_DUMP_FILE','C:\Program Files\UwAmp\bin\database\mysql-5.7.11\bin\mysqldump.exe');
define('DUMP_DIRECTORY',__DIR__.DIRECTORY_SEPARATOR.'dumps'.DIRECTORY_SEPARATOR);
if(!file_exists(DUMP_DIRECTORY)){
	mkdir(DUMP_DIRECTORY,0755,true);
	file_put_contents(DUMP_DIRECTORY.'.htaccess', 'deny for all');
}
require_once(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'common.php');
global $myUser,$lastQuery,$db,$steps;
if(!$myUser->superadmin && (empty($_['token']) || $_['token']!= sha1(CRYPTKEY) )  ) throw new Exception("Permission denied");
ini_set('max_execution_time', 36000);
ob_implicit_flush(true);
ini_set('memory_limit', '2048M');
setlocale( LC_ALL, "fr_FR.utf8" );

/* ACTION NECESSITANT UN CLEAN HEADER*/
if(isset($_['action'])){
	switch($_['action']){
		case 'download_restore':

		    $file = DUMP_DIRECTORY.$_['file'];
		    if(!file_exists($file)) throw new Exception("Le fichier n'existe pas");
		    if(filesize($file)==0 || filesize($file)<900) throw new Exception("Le fichier est vide ou trop petit, annulation...");

		    $stream = file_get_contents($file);
		    ob_end_clean();
		    header_remove();
			header("Content-Type: plain/text");
			header("Content-Length: " . strlen($stream));
			header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header('Cache-Control: post-check=0, pre-check=0', FALSE);
			header('Pragma: no-cache');
			header("Content-Disposition: "."attachment"."; filename=\"".utf8_decode($_['file'])."\"");
			echo $stream;

		    exit();
		break;
	}
}

/*

Pour autoriser les droits sur la table a un user :
grant_table($base,$table,$user);

ex : grant_table('erp','resource_article','erp-maintenance');

*/

//Ne pas supprimer cette étape
addStep('Dump de la base actuelle',function($mode){
	mysqldump(BASE_NAME,BASE_LOGIN,BASE_PASSWORD);
});



addStep('Ajout colonne superadmin aux Ranks',function($mode){
	Rank::staticQuery('ALTER TABLE `rank` ADD `superadmin` BOOLEAN NOT NULL DEFAULT FALSE AFTER `description`;');
});

global $connected;
$connected = null;
addStep('Création des rangs superadmin',function($mode){
	global $connected;

	$ranks = array();
	foreach(Rank::loadAll() as $rank)
		$ranks[$rank->label] = $rank;

	info('Rang Super Admin...');
	if(!isset($ranks['Super Admin'])){
		info('Création du rang Super Admin...');
		//create super admin rank
		$admin = new Rank();
		$admin->label = 'Super Admin';
		$admin->description = 'Dispose de tous les accès';
		$admin->superadmin = true;
		$admin->save();
		$admin = $admin;
	} else {
		info('Rang Super Admin déjà existant...');
		$admin = $ranks['Super Admin'];
	}

	info('Rang Tout le monde - Anonyme...');
	if(!isset($ranks['Tout le monde - Anonyme'])){
		info('Création du rang Tout le monde - Anonyme...');
		//create all anonymous rank
		$anonymous = new Rank();
		$anonymous->label = 'Tout le monde - Anonyme';
		$anonymous->description = 'Utilisateur non connecté à la plateforme';
		$anonymous->superadmin = false;
		$anonymous->save();
		$anonymous = $anonymous;
	} else {
		info('Rang Tout le monde - Anonyme déjà existant...');
		$anonymous = $ranks['Tout le monde - Anonyme'];
	}

	info('Rang Tout le monde - Connecté...');
	if(!isset($ranks['Tout le monde - Connecté'])){
		info('Création du rang Tout le monde - Connecté...');
		//create all connected rank
		$connected = new Rank();
		$connected->label = 'Tout le monde - Connecté';
		$connected->description = 'Utilisateur connecté à la plateforme';
		$connected->superadmin = false;
		$connected->save();
		$connected = $connected;
	} else {
		info('Rang Tout le monde - Connecté déjà existant...');
		$connected = $ranks['Tout le monde - Connecté'];
	}

	info('ID du rang "Tout le monde - Connecté" : '.$connected->id);


	info('<br><br>Définition des permissions pour CRUD sur ces rangs');
	foreach (array($admin,$anonymous,$connected) as $rank) {
		info('Permissions uniquement par le SuperAdmin sur le rang : '.$rank->label);
		$permission = new Permission;
		$permission->scope = 'rank';
		$permission->uid = $rank->id;
		$permission->read = 1;
		$permission->edit = 1;
		$permission->delete = 1;
		$permission->configure = 1;
		$permission->recursive = 1;
		$permission->targetScope = 'rank';
		$permission->targetUid = $admin->id;
		$permission->save();
	}
});

addStep('Ajout visibilité par défaut aux utilisateurs connectés pour les menus',function($mode) {
	global $connected, $conf;
	if(empty($connected)){
		info('Aucun identfiaint de rank Tout le monde - Connecté, annulation...');
		return;
	}
	info('<strong class="text-danger">Attention, spécifier le rang en configuration du plugin Menus & Navigation !!!</strong>');

	Plugin::need('navigation/MenuItem');
	foreach(MenuItem::staticQuery('SELECT * FROM {{table}} WHERE visibility IS NULL OR visibility = ""', array(), true) as $menu){
		info('Menu : <strong>'.$menu->label.'</strong>');
		$menu->visibility = $connected->id;
		$menu->save();
	}

	$conf->put('default_menu_visibility', $connected->id);
});

addStep('Migration des users Super Admin avec le rang Super Admin',function($mode){
	foreach(User::getAll() as $user){
		if(!isset($user->superadmin) || empty($user->superadmin)) continue;

		info('<strong class="text-danger">User en Super Admin : '.$user->login.'</strong>');

		$superAdminRank = Rank::load(array('superadmin'=>true));
		$ufrs = array();
		foreach(UserFirmRank::loadAll(array('user'=>$user->login, 'rank'=>$superAdminRank->id)) as $ufr)
			$ufrs[$ufr->firm] = $ufr;

		foreach(Firm::loadAll() as $firm){
			if(isset($ufrs[$firm->id])) continue;
			info('Création du lien UFR pour le combo UFR : '.$user->login.'/'.$firm->label.'/'.$superAdminRank->label);
		    $newUfr = new UserFirmRank;
		    $newUfr->firm = $firm->id;
		    $newUfr->user = $user->login;
		    $newUfr->rank = $superAdminRank->id;
		    $newUfr->save();
		}
	}
});
addStep('Suppression de la colonne superadmin de la table user',function($mode){
	User::staticQuery('ALTER TABLE {{table}} DROP COLUMN superadmin;');
});

addStep('Client : ajout du champs pseudonyme',function($mode){
	User::staticQuery('ALTER TABLE `client` ADD `pseudonym` VARCHAR(225) NULL AFTER `label`;');
});

addStep('Contacts personne : ajout du champs commentaire',function($mode){
	ContactPerson::staticQuery('ALTER TABLE {{table}} ADD `comment` TEXT NULL AFTER `state`;');
});



addStep('Stats : alteration table vers nouveau système de connexion <span class="text-warning">(ne fonctionne que pour mysql)</span>', function(){
	info('Déplacement ancienne table connexion');
	move_table('statistic_connection','statistic_connection_old');

	info('Création nouvelle table connexion');
	Plugin::need('statistic/Connection');
	Connection::create();

	info('Migration des connexions');

	foreach (Connection::staticQuery('SELECT * FROM statistic_connection_old')->fetchAll() as $value) {
		$connection = new Connection();
		$connection->label = $value['label'];
		$connection->handler = 'Mysql';
		$json = array();
		$json["host"] = $value['host'];
		$json["login"] = $value['login'];
		$json["password"] = $value['password'];
		$json["name"] = $value['database'];

		$connection->meta = json_encode($json);
		$connection->save();
	}

});

addStep('Business : Ajout colonne qualification',function($mode){
	Rank::staticQuery('ALTER TABLE `business` ADD `qualification` INT(3) NULL AFTER `description`;');

	info('Migration des affaires existantes');
	Rank::staticQuery("UPDATE business SET qualification = 10 WHERE step IN ('approved','checked','draft','opportunity')");
	Rank::staticQuery("UPDATE business SET qualification = 60 WHERE step IN ('client_waiting')");
	Rank::staticQuery("UPDATE business SET qualification = 100 WHERE step IN ('invoiced','ordered_client','paid','ready','supplier_waiting','to_invoice','to_prepare','ordered_provider')");

});

addStep('Stats : Ajout colonne meta', function($mode){
	User::staticQuery('ALTER TABLE `statistic_widget` ADD `meta` TEXT NULL AFTER `creator`;');
});

addStep('Tickets : Changement structure table pour colonne "from"', function($mode){
	Plugin::need('issue/IssueReport');
	IssueReport::staticQuery('ALTER TABLE `issue_report` CHANGE `from` `from` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;');
});

addStep('Contact person : Ajout d\'une colonne tag',function($mode){
	User::staticQuery('ALTER TABLE contact_person ADD `tag` TEXT NULL AFTER `uid`;');
});

addStep('Contacts personne : ajout du champs type',function($mode){
	ContactPerson::staticQuery('ALTER TABLE {{table}} ADD `type` VARCHAR(225)  NULL AFTER `state`;');
	ContactPerson::staticQuery('UPDATE {{table}} SET `type`= "user" WHERE account IS NOT NULL AND account !=""');
});

addStep('DynamicForm : ajout du champs firm',function($mode){
	Plugin::need('dynamicform/DynamicForm');
	DynamicForm::staticQuery('ALTER TABLE {{table}} ADD `firm` INT(11) NULL AFTER `state`;');
	DynamicForm::staticQuery('UPDATE {{table}} SET `firm`= 0 ');
});


addStep('Firm : Déplacement des logos dans le rep public', function(){
	$source = File::dir().'core'.SLASH.'firm';
	$destination = File::dir().'core'.SLASH.'public'.SLASH.'firm';

	if(!is_dir($source)) throw new Exception("Dossier source inexistant");

	File::copy($source, $destination);
});


addStep('Droits : fusion permission et droits ', function(){
	global $myFirm;
	info('Création des colonnes targetScope,uid,recursive');
	Right::staticQuery('ALTER TABLE {{table}} ADD `targetScope` VARCHAR(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;');
	Right::staticQuery('ALTER TABLE {{table}} ADD `uid` INT(11) NULL AFTER `firm`;');
	Right::staticQuery('ALTER TABLE {{table}} ADD `recursive` INT(11) NULL AFTER `firm`;');

	info('Migrations des colonnes section-> scope, rank->targetUid');
	Right::staticQuery('ALTER TABLE {{table}} CHANGE `section` `scope` VARCHAR(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;');
	Right::staticQuery('ALTER TABLE {{table}} CHANGE `rank` `targetUid` VARCHAR(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;');

	info('Fill des targetScope en "rank"');
	Right::staticQuery('UPDATE  {{table}} SET targetScope = "rank"');
	info('Fill des uid en 0');
	Right::staticQuery('UPDATE  {{table}} SET uid = 0');

	info('Migration de la table permission dans la table right');
	$oldPermissions = Right::staticQuery('SELECT * FROM permission',array())->fetchAll();
	foreach($oldPermissions as $oldPermission){
		$right = new Right();
		$right->firm = $myFirm->id;
		$right->read = $oldPermission['read'];
		$right->edit = $oldPermission['edit'];
		$right->delete = $oldPermission['delete'];
		$right->configure = $oldPermission['configure'];
		$right->scope = $oldPermission['scope'];
		$right->uid = $oldPermission['uid'];
		$right->targetScope = $oldPermission['targetScope'];
		$right->targetUid = $oldPermission['targetUid'];
		$right->recursive = $oldPermission['recursive'];
		$right->save();
	}
	info('Suppression de la table de permissions');
	//Right::staticQuery('DROP TABLE IF EXISTS permission');
});

addStep('Client : ajout du champs firm',function($mode){
	Plugin::need('client/Client');
	Client::staticQuery('ALTER TABLE {{table}} ADD `firm` INT(11) NULL AFTER `state`;');
	Client::staticQuery('UPDATE {{table}} SET `firm`= 0 ');
});


addStep('Navigation : ajout du champs firm',function($mode){
	Plugin::need('navigation/MenuItem');
	MenuItem::staticQuery('ALTER TABLE {{table}} ADD `firm` INT(11) NULL AFTER `sort`;');
	MenuItem::staticQuery('UPDATE {{table}} SET `firm`= 0 ');
});


addStep('Tickets : Changement structure table pour colonne "from"', function($mode){
	Plugin::need('issue/IssueReport');
	IssueReport::staticQuery('ALTER TABLE `issue_report` CHANGE `from` `from` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;');
});

addStep('Summary : Ajout de la configuration', function(){
	global $conf;
	$conf->put('summary_files_extension', 'jpg,png,svg,bmp,gif,jpeg,doc,xls,ppt,docx,xlsx,pptx,pdf,msg,eml,txt');
});

addStep('Stats : modification statistic en statistic_widget', function($mode){
	User::staticQuery('UPDATE `right` SET scope="statistic_widget" WHERE scope="statistic";');
});

addStep('User : Ajout colonne meta', function(){

	User::staticQuery('ALTER TABLE `user` ADD `meta` TEXT NULL AFTER `origin`;');
});
/** SCRIPT DE MIGRATION ICI **/
/*
addStep('',function($mode){

});
*/


addStep('Changement interclassement des tables et colonnes en utf8_general_ci',function($mode){
	global $databases_credentials;
	$dbConstant = $databases_credentials['local'];

	info("Récupération des requêtes à passer...");
	$query = '
		SELECT CONCAT("ALTER DATABASE `",TABLE_SCHEMA,"` CHARACTER SET = utf8 COLLATE = utf8_general_ci;") AS query
		FROM `TABLES` WHERE TABLE_SCHEMA LIKE "'.$dbConstant['name'].'" AND TABLE_TYPE=\'BASE TABLE\' GROUP BY TABLE_SCHEMA UNION
		SELECT CONCAT("ALTER TABLE `",TABLE_SCHEMA,"`.`",table_name,"` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;") AS query
		FROM `TABLES` WHERE TABLE_SCHEMA LIKE "'.$dbConstant['name'].'" AND TABLE_TYPE=\'BASE TABLE\' GROUP BY TABLE_SCHEMA, table_name UNION
		SELECT CONCAT("ALTER TABLE `",`COLUMNS`.TABLE_SCHEMA,"`.`",`COLUMNS`.table_name, "` CHANGE `",column_name,"` `",column_name,"` ",data_type,"(",character_maximum_length,") CHARACTER SET utf8 COLLATE utf8_general_ci",IF(is_nullable="YES"," NULL"," NOT NULL"),";") AS query
		FROM `COLUMNS` INNER JOIN `TABLES` ON `TABLES`.table_name = `COLUMNS`.table_name WHERE `COLUMNS`.TABLE_SCHEMA like "'.$dbConstant['name'].'" and data_type in (\'varchar\',\'char\') AND TABLE_TYPE=\'BASE TABLE\' UNION
		SELECT CONCAT("ALTER TABLE `",`COLUMNS`.TABLE_SCHEMA,"`.`",`COLUMNS`.table_name, "` CHANGE `",column_name,"` `",column_name,"` ",data_type," CHARACTER SET utf8 COLLATE utf8_general_ci",IF(is_nullable="YES"," NULL"," NOT NULL"),";") AS query
		FROM `COLUMNS` INNER JOIN `TABLES` ON `TABLES`.table_name = `COLUMNS`.table_name WHERE `COLUMNS`.TABLE_SCHEMA like "'.$dbConstant['name'].'" and data_type in (\'text\',\'tinytext\',\'mediumtext\',\'longtext\') AND TABLE_TYPE=\'BASE TABLE\';';

	$result = array();
	$pdo = new PDO('mysql:host='.$dbConstant['host'].';dbname=information_schema', $dbConstant['login'], $dbConstant['password']);
	foreach($pdo->query($query)->fetchAll(PDO::FETCH_ASSOC) as $qry){
		preg_match("/ALTER TABLE `".$dbConstant['name']."`\.`(.*)`/iU", $qry['query'], $matches);

		if(!empty($matches)) $result[$matches[1]][] = $qry['query'];
		else $result['database'][] = $qry['query'];
	}

	info("<i><strong>Disclaimer (avant d'afficher toutes les requêtes) : c'est un peu long quand tu vas l'executer dans ton PMA :D</strong></i>");
	$allQueries = '';
	foreach ($result as $scope => $queries) {
		info('Requêtes pour <strong class="text-primary">'.$scope.'</strong> :');

		$currentQueries = '';
		foreach($queries as $qry)
			$currentQueries .= $qry.PHP_EOL;

		info('<br><code class="pointer" onclick="copy_string(\''.str_replace(PHP_EOL, '', $currentQueries).'\', this)">'.nl2br($currentQueries).'</code>');

		$allQueries .= $currentQueries;
	}
	info('<br><strong class="text-primary">Toutes les requêtes en UN</strong><br><code class="pointer" onclick="copy_string(\''.str_replace(PHP_EOL, '', $allQueries).'\', this)">'.nl2br($allQueries).'</code>');
});


addStep('Employee : Ajout colonne state.', function($mode){
	Plugin::need('employee/Employee');
	Employee::staticQuery('ALTER TABLE {{table}} ADD `state` VARCHAR(225) NULL AFTER `comment`;');
	Employee::staticQuery('UPDATE {{table}} SET state = "'.Employee::ACTIVE.'";');
});

addStep('Dictionary : Correctif de la faute historique', function($mode){
	Dictionary::staticQuery('RENAME TABLE `dictionnary` TO {{table}};');
});




addStep('Host : input client en dynamicForm', function($mode){
	Plugin::need('dynamicform/DynamicForm, dynamicform/DynamicField, dynamicform/DynamicValue, host/Machine, client/Client');

	$form = DynamicForm::load(array('slug'=>'host-sheet'));
	if($form)return;
	$form = new DynamicForm();
	$form->slug = 'host-sheet';
	$form->label = 'Fiche hébergement';
	$form->state = 'published';
	$form->creator = 'admin';
	$form->updater = 'admin';
	$form->firm = 1;
	$form->save();

	$field = DynamicField::load(array('slug'=>'host-sheet-client'));
	if($field)return;
	$clientField = new DynamicField();
	$clientField->slug = $form->slug . '-client';
	$clientField->type = 'client';
	$clientField->label = 'Client';
	$clientField->state = 'published';
	$clientField->creator = 'admin';
	$clientField->form = $form->id;
	$clientField->mandatory = 0;
	$clientField->readonly = 0;
	$clientField->row = 0;
	$clientField->sort = 0;
	$clientField->column = 0;
	$clientField->save();


	foreach(Machine::loadAll() as $machine)
	{
		if(empty($machine->client))continue;
		$client = Client::getById($machine->client);
		$clientName = $client ? $client->label : null;
		$clientValue = new DynamicValue();
		$clientValue->field = $clientField->id;
		$clientValue->value = $machine->client;
		$clientValue->firm = 1;
		$clientValue->scope = 'host';
		$clientValue->uid = $machine->id;
		$clientValue->creator = 'admin';
		$clientValue->save();

	}
});

addStep('Plugin : Migration enabled.json vers /file/core/plugin.json', function($mode){
	rename(__ROOT__.PLUGIN_PATH.'enabled.json',File::core().SLASH.'plugin.json');
});
/** FIN DU SCRIPT **/



/******************************************************/
/** NE PAS ALLER PLUS LOIN                          * */
/** Sauf pour modifier le script sandpiper lui même  **/
/******************************************************/
?>
<!DOCTYPE html>
<html lang="fr">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="description" content="">
	<meta name="author" content="">
	<link rel="icon" type="image/png" href="favicon.png" />
	<title>Sandpiper</title>
	<!-- Bootstrap core CSS -->
	<link href="../css/bootstrap.min.css" rel="stylesheet">
	<!-- Jquery ui -->
	<link rel="stylesheet" href="../css/jquery-ui.min.css">
	<!-- Font awesome -->
	<link rel="stylesheet" href="../css/fontawesome-all.min.css">
	<!-- Lato font-->
	<?php if(!$conf->get('offline_mode')): ?>
	<link href="https://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet">
	<?php endif; ?>
	<!-- Custom styles for this template -->
	<link href="../css/main.css" rel="stylesheet">
	<style>
		.logo path:nth-child(3){
			animation: fly2 linear 1s;
			  animation-iteration-count: infinite;
			  transform-origin: 50% 50%;
		}
		.logo path:nth-child(2){
			animation: fly1 linear 2.5s;
			  animation-iteration-count: infinite;
			  transform-origin: 50% 50%;
		}
		.logo path:nth-child(4){
			animation: fly1 linear 2s;
			animation-iteration-count: infinite;
			transform-origin: 50% 50%;
		}
		.logo path:nth-child(1){
			animation: fly2 linear 3s;
			  animation-iteration-count: infinite;
			  transform-origin: 50% 50%;
		}

		@keyframes fly1{
		  0% {
		    transform:  translate(0px,0px)  ;
		  }
		  50% {
		    transform:  translate(7px,-13px)  ;
		  }
		  100% {
		    transform:  translate(0px,0px)  ;
		  }
		}
		@keyframes fly2{
		  0% {
		    transform:  translate(0px,0px)  ;
		  }
		  50% {
		    transform:  translate(10px,13px)  ;
		  }
		  100% {
		    transform:  translate(0px,0px)  ;
		  }
		}
		.navbar-brand span{
			font-weight: bold;
		}

		.card-img-top{
			padding:15px;
			text-align: center;
		}
		.card-img-top svg{
			margin: auto;
		}

	</style>
</head>

<body>
	<nav class="navbar navbar-dark bg-primary">
		<a class="navbar-brand" href="migration.php">
	<svg  class="logo mr-3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 303.327 303.327" style="enable-background:new 0 0 303.327 303.327;" xml:space="preserve" width="52px" height="52px"><g><g>
		<path d="M172.631,211.084c-17.389-3.674-34.588-0.419-48.851,7.808c-9.732-13.297-24.135-23.235-41.523-26.908   c-37.423-7.912-74.2,16.02-82.111,53.458c-0.031,0.144-0.06,0.289-0.09,0.433c-0.259,1.244,0.397,2.503,1.563,3.015   c1.165,0.514,2.528,0.146,3.274-0.885c14.909-20.499,41.285-25.346,69.611-19.359c17.388,3.674,31.8,13.616,41.524,26.908   c14.263-8.221,31.472-11.48,48.859-7.809c28.326,5.982,50.472,21.086,55.826,45.858c0.269,1.245,1.363,2.13,2.638,2.135   c1.274,0.006,2.368-0.88,2.646-2.119c0.031-0.145,0.06-0.283,0.09-0.423C234.001,255.753,210.054,218.99,172.631,211.084z" data-original="#000000" class="active-path" data-old_color="#FCF6F6" fill="#FFFFFF"/>
		<path d="M269.374,142.83c-13.557-6.32-28.276-6.917-41.544-2.886c-5.453-12.75-15.368-23.639-28.924-29.959   c-29.191-13.605-63.897-0.97-77.504,28.222c0,0-0.009,0.009-0.009,0.02c-0.469,1-0.169,2.195,0.717,2.861   c0.875,0.667,2.109,0.632,2.945-0.085c16.103-13.755,38.538-12.675,60.523-2.429c13.557,6.321,23.479,17.209,28.924,29.96   c13.258-4.033,27.988-3.435,41.545,2.881c22.424,10.455,37.841,27.391,37.024,49.188c-0.029,0.971,0.616,1.831,1.553,2.075   c0.945,0.238,1.921-0.214,2.349-1.08c0.209-0.423,0.418-0.847,0.616-1.273C311.196,191.132,298.556,156.431,269.374,142.83z" data-original="#000000" class="active-path" data-old_color="#FCF6F6" fill="#FFFFFF"/>
		<path d="M94.51,37.677c0.606,0.254,1.313,0.05,1.702-0.492c7.256-10.366,20.402-13.103,34.655-10.466   c8.789,1.622,16.164,6.439,21.22,13.003c7.066-4.324,15.686-6.186,24.484-4.559c14.253,2.633,25.539,9.888,28.625,22.165   c0.159,0.643,0.747,1.086,1.403,1.06c0.657-0.019,1.215-0.497,1.334-1.149c3.503-18.931-9.008-37.12-27.939-40.618   c-8.798-1.623-17.407,0.233-24.475,4.558c-5.056-6.564-12.441-11.381-21.229-13.003c-18.941-3.499-37.125,9.012-40.629,27.948   C93.544,36.776,93.892,37.424,94.51,37.677z" data-original="#000000" class="active-path" data-old_color="#FCF6F6" fill="#FFFFFF"/>
		<path d="M258.933,35.328c5.025,4.519,7.872,10.541,8.54,16.771c6.259,0.005,12.559,2.215,17.596,6.739   c8.48,7.628,12.909,17.223,9.296,26.728c-0.139,0.354,0,0.752,0.309,0.956c0.319,0.204,0.737,0.159,1.006-0.11   c0.298-0.302,0.597-0.616,0.886-0.939c9.733-10.825,8.858-27.496-1.971-37.24c-5.027-4.523-11.316-6.728-17.577-6.733   c-0.666-6.225-3.533-12.251-8.55-16.776c-10.828-9.744-27.5-8.863-37.244,1.961c-0.338,0.383-0.367,0.936-0.069,1.343   c0.288,0.403,0.825,0.547,1.284,0.349C241.216,24.564,250.782,27.998,258.933,35.328z" data-original="#000000" class="active-path" data-old_color="#FCF6F6" fill="#FFFFFF"/>
	</g></g> </svg>

	  SAND<span>P|PE</span>R</a>
	</nav>

	<!-- Begin page content -->
	<div class="container-fluid pt-2">
		<?php
		try{
			if(isset($_['action'])){
				switch($_['action']){
					case 'restore':
						title("Restauration");
						$file = DUMP_DIRECTORY.$_['file'];
						info("Restauration du fichier <code>$file</code>");
						if(!file_exists($file)) throw new Exception("Le fichier n'existe pas");
						if(filesize($file)==0 || filesize($file)<900) throw new Exception("Le fichier est vide ou trop petit, annulation...");

						mysqlrestore(BASE_NAME,BASE_LOGIN,BASE_PASSWORD,$file);
						info("Restauration terminée");
						info("<a href='migration.php'>Revenir au menu</a>");
					break;
                    case 'download_restore':
                        title("Téléchargement");
                        $file = DUMP_DIRECTORY.$_['file'];
                        info("Téléchargement du fichier <code>$file</code>");
                        if(!file_exists($file)) throw new Exception("Le fichier n'existe pas");
                        if(filesize($file)==0 || filesize($file)<900) throw new Exception("Le fichier est vide ou trop petit, annulation...");

                        info("nope, ça download pas encore pour le moment ¯\_(ツ)_/¯");
                        // File::downloadFile($file);

                        info("Téléchargement terminé");
                        info("<a href='migration.php'>Revenir au menu</a>");
                    break;
					case 'delete_restore':
						title("Supression de point de restauration");
						$file = DUMP_DIRECTORY.$_['file'];
						info("Suppression de la restauration <code>$file</code>");
						if(!file_exists($file)) throw new Exception("Le fichier n'existe pas");


						unlink($file);
						info("Suppression terminée");
						info("<a href='migration.php'>Revenir au menu</a>");
					break;
					case 'migrate':
						if(!$myUser->superadmin) throw new Exception("Vous n'avez pas la permission de lancer cette action");
						if(!isset($_['steps']) || count($_['steps'])==0) throw new Exception("Aucune étape renseignée, impossible de lancer.");
						$time_start = microtime(true);

						title('Lancement de la migration');
						info("Mode : ".$_['mode']);

						foreach ($steps as $slug => $step) {
							if(!isset($_['steps'][$slug]) || $_['steps'][$slug]!='on' ) continue;
							title('> '.$step['label']);
							$callback = $step['callback'];
							$callback($_['mode']);
							execution_time($time_start);
						}

						title('Migration terminée');
						execution_time($time_start);

						info("<a href='migration.php'>Revenir au menu</a>");
					break;
					}
				}else{
				?>

				<div class="row justify-content-md-center">
					<div class="col-md-4">

						<div class="card w-100" >
						  <div class="card-img-top bg-danger" >
						  		<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="100px" height="100px" viewBox="0 0 531.921 531.921" style="enable-background:new 0 0 531.921 531.921;" xml:space="preserve" class=""><g><g>
								<path d="M13.01,253.731L158.187,6.44c2.32-3.972,6.797-6.44,11.694-6.44c4.885,0,9.363,2.468,11.683,6.434l98.629,167.989   l-13.645,7.105L188.42,43.737c-2.825-4.8-8.26-7.439-13.781-6.659c-5.509,0.769-10.025,4.788-11.423,10.181L109.24,265.813   c-1.052,3.623-0.567,7.524,1.339,10.775c1.912,3.263,5.071,5.598,8.745,6.466c17.389,4.067,35.334,6.136,53.347,6.136l0,0   c1.848,0,3.674-0.035,5.485-0.071l0.083,17.579c-3.877,0.142-7.788,0.236-11.76,0.236h-0.023   c-52.278,0-102.188-12.282-148.325-36.517c-3.147-1.655-5.382-4.339-6.301-7.589C10.953,259.754,11.381,256.521,13.01,253.731z    M200.567,251.409c0.012-2.506,1.431-4.803,3.662-5.926l152.438-79.467c1.75-0.877,3.783-0.943,5.586-0.186l154.218,74.688   c0.13,0.062,0.236,0.153,0.372,0.225c0.148,0.074,0.319,0.109,0.455,0.201c0.154,0.083,0.272,0.21,0.414,0.319   c0.225,0.151,0.426,0.31,0.627,0.497c0.248,0.225,0.461,0.461,0.674,0.721c0.165,0.198,0.319,0.399,0.461,0.63   c0.189,0.283,0.331,0.594,0.461,0.896c0.106,0.236,0.213,0.461,0.283,0.694c0.106,0.357,0.154,0.709,0.213,1.079   c0.024,0.189,0.095,0.37,0.106,0.556c0,0.05-0.023,0.098-0.012,0.142c0,0.059,0.012,0.118,0.012,0.174v197.443   c0,2.441-1.336,4.688-3.487,5.863l-149.654,81.161c-0.976,0.532-2.069,0.804-3.15,0.804c-1.183,0-2.364-0.319-3.417-0.945   c-0.603-0.367-1.123-0.84-1.572-1.359h-0.018c-1.094,0-2.175-0.272-3.15-0.793L204.51,449.449c-2.143-1.141-3.488-3.398-3.5-5.828   l-0.89-189.768c0-0.816,0.186-1.599,0.473-2.344C200.594,251.473,200.567,251.444,200.567,251.409z M370.895,514.107   l136.332-73.985V257.81l-136.332,76.195V514.107z M364.162,322.515l134.346-75.126l-138.59-68.092l-138.022,72.206L364.162,322.515   z M121.558,468.262c3.559,1.963,7.256,3.807,11.065,5.532l-6.218,1.797c-2.329,0.674-4.256,2.211-5.423,4.339   s-1.439,4.581-0.769,6.916c1.351,4.651,6.585,7.542,11.239,6.188l30.142-8.73c2.332-0.674,4.268-2.211,5.435-4.338   c1.159-2.129,1.431-4.581,0.757-6.904l-8.722-30.156c-1.348-4.658-6.584-7.543-11.239-6.195c-2.329,0.674-4.256,2.223-5.423,4.345   c-1.167,2.134-1.439,4.581-0.769,6.91l3.298,11.396c-5.095-2.074-9.998-4.403-14.611-6.939   C58.732,412.985,64.735,328.16,64.809,327.302c0.295-3.558-1.537-6.975-4.667-8.7c-1.126-0.627-2.355-0.993-3.632-1.1   c-4.962-0.413-9.375,3.304-9.788,8.287C46.633,326.759,39.848,423.246,121.558,468.262z" data-original="#000000" class="active-path" data-old_color="#F8F7F7" fill="#FFFFFF"/>
							</g></g> </svg>
						  </div>
						  <div class="card-body">
						  	<form action="migration.php" method="GET">
						    <h5 class="card-title">Migration</h5>
						    <p class="card-text">Lancer une migration complete avec les étapes :
						    	<ol>
						    		<?php foreach($steps as $slug=>$step): ?>
						    		<li><label><input data-type="checkbox" name="steps[<?php echo $slug ?>]"> <?php echo $step['label']; ?></label></li>
						    		<?php endforeach; ?>
						    	</ol>
						    </p>
						    <h5>Mode</h5>
						    <label><input data-type="radio" type="radio" name="mode" checked="checked" value="debug">Debug </label>
						    <label><input data-type="radio" type="radio" name="mode" value="production">Production</label>
						    <input type="hidden" name="action" value="migrate">
						    <div onclick="$(this).closest('form').submit()" class="btn btn-primary w-100">Go !</div>
							</form>
						  </div>
						</div>
					</div>
					<div class="col-md-4">

						<div class="card w-100" >
						  <div class="card-img-top bg-dark" >
						  		<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" width="100px" height="100px" viewBox="0 0 87.883 87.883" style="enable-background:new 0 0 87.883 87.883;" xml:space="preserve" class=""><g><g>
			<path d="M2.149,41.921L26.134,1.064C26.517,0.408,27.258,0,28.065,0s1.548,0.408,1.93,1.063l16.294,27.756l-2.253,1.174   L31.128,7.226c-0.467-0.793-1.365-1.229-2.276-1.1c-0.911,0.127-1.656,0.791-1.887,1.682l-8.917,36.109   c-0.174,0.599-0.094,1.243,0.221,1.78c0.315,0.539,0.837,0.925,1.445,1.068c2.873,0.672,5.839,1.014,8.814,1.014h0.001   c0.305,0,0.606-0.006,0.906-0.012l0.014,2.904c-0.641,0.023-1.287,0.039-1.944,0.039h-0.003c-8.638,0-16.882-2.029-24.507-6.033   c-0.518-0.273-0.888-0.717-1.04-1.254C1.808,42.916,1.878,42.382,2.149,41.921z M33.137,41.537   c0.002-0.414,0.235-0.793,0.605-0.979l25.186-13.129c0.289-0.145,0.625-0.156,0.923-0.031l25.48,12.34   c0.021,0.01,0.038,0.025,0.061,0.037c0.024,0.012,0.052,0.018,0.075,0.033c0.025,0.014,0.044,0.035,0.068,0.053   c0.037,0.025,0.071,0.051,0.104,0.082c0.041,0.037,0.077,0.076,0.111,0.119c0.027,0.033,0.054,0.066,0.078,0.104   c0.03,0.047,0.053,0.098,0.076,0.148c0.017,0.039,0.035,0.076,0.047,0.115c0.018,0.059,0.025,0.117,0.034,0.178   c0.004,0.031,0.016,0.061,0.017,0.092c0,0.008-0.002,0.016-0.002,0.023c0,0.01,0.003,0.02,0.003,0.029v32.621   c0,0.403-0.222,0.774-0.577,0.969L60.7,87.75c-0.163,0.088-0.343,0.133-0.523,0.133c-0.194,0-0.39-0.053-0.562-0.156   c-0.102-0.061-0.187-0.139-0.261-0.225c0,0-0.001,0-0.002,0c-0.18,0-0.358-0.045-0.521-0.131L33.787,74.257   c-0.354-0.188-0.576-0.562-0.579-0.963l-0.145-31.353c0-0.135,0.032-0.264,0.078-0.387C33.14,41.548,33.137,41.543,33.137,41.537z    M61.276,84.939l22.526-12.224V42.595L61.276,55.184V84.939z M60.164,53.285l22.197-12.412l-22.898-11.25l-22.804,11.93   L60.164,53.285z M47.608,12.025c0,0.4,0.156,0.777,0.438,1.061l3.667,3.667c0.566,0.566,1.556,0.566,2.121,0   c0.283-0.283,0.439-0.66,0.439-1.061s-0.156-0.777-0.439-1.061l-1.386-1.386c0.903-0.106,1.796-0.16,2.668-0.16   c13.504,0,19.396,12.754,19.454,12.883c0.241,0.539,0.779,0.888,1.37,0.888c0.213,0,0.419-0.044,0.611-0.131   c0.754-0.337,1.095-1.226,0.758-1.98c-0.066-0.148-6.776-14.652-22.19-14.652c-0.671,0-1.354,0.028-2.042,0.083l0.757-0.757   c0.283-0.283,0.439-0.66,0.439-1.061s-0.156-0.777-0.439-1.061c-0.565-0.566-1.555-0.566-2.121,0l-3.667,3.667   C47.765,11.248,47.608,11.625,47.608,12.025z" data-original="#000000" class="active-path" data-old_color="#000000" fill="#FFFFFF"/>
		</g></g> </svg>
						  </div>
						  <div class="card-body">
						    <h5 class="card-title">Restauration</h5>
						    <p class="card-text">
						    	<?php
						    	$dumps = glob(DUMP_DIRECTORY.'*.sql');
						    	if(count($dumps)==0): ?>
						    		<small class="text-muted"><i class="far fa-grimace"></i> Aucune restauration disponible, essayez de rafraichir la page</small>
						    	<?php else: ?>
						    	Restaurer une des sauvegardes suivantes :
						    	<ol>
						    		<?php foreach($dumps as $dump): ?>
						    		<li class="p-1">
                                        <span><?php echo str_replace(array('.sql','_'),array('',' '),basename($dump)); ?> <small class="text-muted">(<?php echo readable_size(filesize($dump)); ?>)</small></span>
                                        <a title="Restaurer" href="migration.php?action=restore&file=<?php echo basename($dump); ?>" class="btn btn-sm d-inline-block btn-success ml-2">
						    				<i class="fas fa-redo-alt"></i>
						    			</a>
						    			<a title="Télécharger" href="migration.php?action=download_restore&file=<?php echo basename($dump); ?>" class="btn btn-sm d-inline-block btn-primary ml-1">
                                            <i class="fas fa-download"></i>
                                        </a>
						    			<a title="Supprimer" href="migration.php?action=delete_restore&file=<?php echo basename($dump); ?>" class="btn btn-sm d-inline-block btn-danger ml-1">
						    				<i class="fas fa-trash-alt"></i>
						    			</a>
						    		</li>
						    		<?php endforeach; ?>
						    	</ol>
						    	<?php endif; ?>
						    </p>

						  </div>
						</div>
				</div>
			</div>
				<?php
				}


		}catch(PdoException $e){
			error($e->getMessage().' - L'.$e->getLine().' <a class="pointer" onclick="$(this).next(\'div\').toggle()"><i class="fas fa-search-plus"></i> StackTrace</a><div class="hide">'.$e->getTraceAsString ().'<code>'.$lastQuery.'</code></div>');
		}catch(Exception $e){
			error($e->getMessage().' - L'.$e->getLine().' <a class="pointer" onclick="$(this).next(\'div\').toggle()"><i class="fas fa-search-plus"></i> StackTrace</a><div class="hide">'.$e->getTraceAsString ().'</div>');
		}
		ob_end_flush();

		//Crée une colonne temporaire pour stocker des ids (INT only)
		function temp_db_column($class, $colName){
			if(!$class || !$colName) throw new Exception("Paramètre manquant (temp_db_column)");
			$result = $class::staticQuery('SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = "'.BASE_NAME.'" AND TABLE_NAME = "'.$class::tableName().'" AND COLUMN_NAME = ? ', array($colName))->fetch();
			if(!$result[0]) $class::staticQuery('ALTER TABLE '.$class::tableName().' ADD ? INT NULL', array($colName));
		}

		function execution_time($time_start){
			$time_end = microtime(true);
			$time = $time_end - $time_start;
			return info("Temps d'execution : ".round($time,4)." secondes");
		}

		//is not null or empty
		function inoe($column,$row){
			return (isset($row[$column]) && !empty(cleanChar($row[$column])));
		}

		//filter array with regex on key
		function preg_array_key_exists($pattern, $array) {
		    $keys = array_keys($array);
		    return (int) preg_grep($pattern,$keys);
		}

		function title($text){
			output('<hr/><h4>'.$text.'</h4>');
		}

		//Déplace une table
		function move_table($from,$to){
			User::staticQuery('DROP TABLE IF EXISTS '.$to.';');
			User::staticQuery('ALTER TABLE '.$from.' RENAME TO '.$to.';');
		}

		//Copie une table
		function copy_table($from,$to){
		  User::staticQuery('DROP TABLE IF EXISTS '.$to.';');
		  User::staticQuery('CREATE TABLE '.$to.' LIKE '.$from.'; INSERT '.$to.' SELECT * FROM '.$from.';');
		}


		//autoriser l'accès a la table pour un user spécifique
		function grant_table($base,$table,$user){
			User::staticQuery("GRANT SELECT,INSERT,UPDATE,REFERENCES ON `".$base."`.`".$table."` TO '".$user."'@'localhost';");
		}

		function info($text){
			output(date('H:i:s').' | '.$text.'</br>');
		}

		function error($text,$type="danger"){
			output('<div class="alert alert-'.$type.'"><button type="button" class="close" data-dismiss="alert" aria-label="Close">
			    <span aria-hidden="true">&times;</span>
			  </button>
				<strong>Erreur: </strong> '.date('H:i:s').' | '.$text.'

		     </div>');
		}

		function cleanChar($text){
			$text = utf8_encode($text);
			if(strlen($text)==1 && ord($text)==0) $text = '';
			return $text;
		}

		function output($text){
			echo $text;
			flush();
			ob_flush();
		}

		function addStep($label,$callback){
			global $steps;
			if(!isset($steps)) $steps = array();
			$slug = preg_replace('|[^a-z0-9]|i', '-', $label);
			$slug = mb_strtolower(preg_replace('|-{2,}|i', '-', $slug));
			$steps[$slug] =  array('label'=>$label,'callback'=>$callback);
		}

		function dbextract($sql){
			global $db,$lastQuery;
			$lastQuery = $sql;
			$query = $db->prepare($sql);
			$query->execute();
			$results = $query->fetchAll(PDO::FETCH_ASSOC);
			return $results;
		}

		function mysqldump($base,$user,$password){
			$command = '';
			if(PHP_OS =='WINNT'){
				if(MYSQL_DUMP_FILE==''){
					error("Le dump de la base est impossible sous windows, a moins de remplir la constante 'MYSQL_DUMP_FILE' avec le chemin vers l'executable mysqldump.exe, la migration se poursuit quand même...","warning");
				}else{
					$command .= '"'.MYSQL_DUMP_FILE.'" ';
				}
			}else{
				$command .= 'mysqldump ';
			}
			$dumpfile = DUMP_DIRECTORY.date('Y-m-d_h-i').".sql";
			$command .= "--routines -h ".BASE_HOST." --user=$user --password=$password $base > ".$dumpfile;
			echo $command;
			exec($command);
			if(!file_exists($dumpfile)) throw new Exception("Impossible de créer le backup");
			if(filesize($dumpfile)==0) throw new Exception("Le fichier de dump est vide");
		}

		function mysqlrestore($base,$user,$password,$dumpfile){
			$command = '';
			if(PHP_OS =='WINNT'){
				if(MYSQL_DUMP_FILE==''){
					error("Le dump de la base est impossible sous windows, a moins de remplir la constante 'MYSQL_DUMP_FILE' avec le chemin vers l'executable mysqldump.exe, la migration se poursuit quand même...","warning");
				}else{
					$command .= '"'.str_replace('dump.exe','.exe',MYSQL_DUMP_FILE).'" ';
				}
			}else{
				$command .= 'mysql ';
			}

			$command .= " -h ".BASE_HOST." -u {$user} -p{$password} {$base} < $dumpfile";
			exec($command);
		}
		?>
	</div>

		<?php if($conf->get('offline_mode')): ?>
			<script src="../js/vendor/jquery.min.js"></script>
		<?php else: ?>
			<script
		src="https://code.jquery.com/jquery-3.2.1.min.js"
		integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
		crossorigin="anonymous"></script>
			<script>window.jQuery || document.write('<script src="js/vendor/jquery.min.js"><\/script>')</script>
		<?php endif ?>

		<script src="../js/vendor/popper.min.js"></script>
		<script src="../js/bootstrap.min.js"></script>
		<script src="../js/vendor/jquery-ui.min.js"></script>
		<script src="../js/vendor/bootstrap3-typeahead.min.js"></script>
		<script src="../js/plugins.js"></script>
		<script src="../js/main.js"></script>
		<script src="../js/component.js"></script>
</body>

</html>
