Commit a0fc5643 authored by marin elie's avatar marin elie
Browse files

Update ai3.php

parents
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>ai, le retour</title>
</head>
<body>
<?php
$token=1;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$host = 'localhost';
$db = 'siba';
$user = 'marin';
$pass = 'mdp4kedesiklem';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
}
catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$default_envelop = [
'<table border=1>%s</table>',
'<tr>%s</tr>',
'<td>%s</td>',
'<th>%s</th>'
];
$form_envelop = [
'<form action="" method="post"><table border=1>%s</table><input type="submit" value="ok"></form>',
'<tr>%s</tr>',
'<td>%s</td>',
'<th>%s</th>'
];
$predefmask = [
"=" => '%s',
"lien" => '<a href="%s">%s</a>',
"i" => '<i>%s</i>',
"b" => '<b>%s</b>'
];
$mask = [
];
function error($s){
echo $s;exit;
}
function dump($var):void{
echo "<pre>";
var_dump($var);
echo "</pre>";
}
function show($var,$nom=''):void{
echo "<b>$nom</b><pre>";
print_r($var);
echo "</pre>";
}
function size_of_mask($s):int{ //CALCULE DU NOMBRE D'ARGUMENT NECESSAIRE A UN MASQUE
preg_match_all('/(?<!%)%(%%)*(\d+\$)/',$s,$m);
return preg_match_all('/(?<!%)%(%%)*[bcdeufFosxX]/',$s)+count(array_unique($m[0]));
//ATTENTION size_of_mask de "%s %1$s" renvoie 2 alors que le nombre d'argument requis est 1.
}
function automask($mod,$type,$f,$stock,&$ai_args_to_modify,$pointer,$table):string{ //GENERATION DES MASQUES AUTOMATIQUE
if (isset($pointer[$f])){
$name=$pointer[$f];
echo "f=$f name=$name<br/>";
preg_match('/^([^.]*)s\.(.*)$/',$name,$r);
}else{
$name=$f;
}
$s = "%s";
if($mod!="select"){
$stock +=1;
if (isset($pointer[$f])){
$ai_args_to_modify[] = $r[2];
$s = '%s'.
sql2html("select","SELECT id,$r[1] FROM $table",'v',
[
'<select name="'.$r[1].'[<AI_ID>][]">%s</select>',
'%s',
'%s',
''
],
[
'<option value = "%s">',
'%s</option>'
]);
}else{
$ai_args_to_modify[] = $name;
switch($type){
case "tinytext":
$s = '<input type="text" name="'.$name.'[<AI_ID>][]" value="%s"/>';
break;
case (preg_match('/^int\(.*\)$/', $type) ? true : false):
$s = '<input type="text" name="'.$name.'[<AI_ID>][]" size="5" value="%s"/>';
break;
case (preg_match('/^int\(.*\)$/', $type) ? true : false):
$s = "";
break;
case (preg_match('/^set\((.*)\)$/',$type,$options) ? true : false) :
$s = '%s';
foreach(explode(',',$options[1]) as $option){
$option = str_replace("'","",$option);
$s .= '<input type="checkbox" name="'.$name.'[<AI_ID>][]" value="'.$option.'">'.$option.'<br>';
}
break;
case (preg_match('/^enum\((.*)\)$/', $type,$options) ? true : false) :
$s = '%s';
foreach(explode(',',$options[1]) as $option){
$option = str_replace("'","",$option);
$s .= '<input type="radio" name="'.$name.'[<AI_ID>][]" value="'.$option.'">'.$option.'<br>';
}
break;
default : $s = '(default)%s'; break;
}
}
} else {
$s = '<u>%s</u>';
}
if (size_of_mask($s)>$stock){error("Too few data for the mask.");}
else
{
echo "<xmp>$s</xmp>";
return $s;
}
}
function cellule_check($cellule):string{
//echo "cellule : $cellule";
if(preg_match('/^([^<]*)(<input type="(?:checkbox|radio)".*)$/',$cellule,$a)){
//echo "avant : $cellule <br/>";
$os=explode(',',$a[1]);
$new_cell=$a[2];
foreach($os as $o){
$new_cell = str_replace('value="'.$o.'">','value="'.$o.'" checked>',$new_cell);
}
//echo "après : $cellule <br/>";
return $new_cell;
}
$cellule = preg_replace('/^([^<]*)(<select.*)>\1/','\2 selected >\1',$cellule);
echo "<xmp>$cellule</xmp>";
return $cellule;
}
function get_query_args($q,$steam):array{ //RECUPERATION DES INFORMATIONS RELATIVES AU TABLE APPELE PENDANT LA REQUETE SQL
$steam->query("DROP TEMPORARY TABLE IF EXISTS tempTable;");
$steam->query("CREATE TEMPORARY TABLE tempTable AS (SELECT * FROM ($q) subq LIMIT 0);");
$data=$steam->query("SHOW COLUMNS FROM tempTable;");
$result=[];
while ($line=$data->fetch()){
$result[]=$line;
}
return $result;
}
function flip($arr):array{ //INVERSION DES LIGNES ET COLONNES D'UN TABLEAU BIDIMENSIONNEL
$out = array();
foreach ($arr as $key => $subarr){
foreach ($subarr as $subkey => $subvalue){
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
function normalize_request($q){ //MISE EN MAJUSCULE DE SELECT ET FROM
return preg_replace('/^[Ss][Ee][Ll][Ee][Cc][Tt] (.*) [Ff][Rr][Oo][Mm]/',"SELECT $1 FROM",$q);
}
function request2ai(&$q,&$arg_field_arr,&$pointer,$mod){ //TRAITE LA REQUETE POUR UTILISER LES NORMES SPECIFIQUE A AI
// "duck.naissance>villes.fondateur>gugusse.nom" transformation en jointure
global $token;
$q=normalize_request($q);
preg_match_all('/^SELECT (.*) FROM ([^, ]*).*$/',$q,$arg_field_arr);
$t1=$arg_field_arr[2][0];
$arg_field_arr=explode(',',$arg_field_arr[1][0]);
foreach($arg_field_arr as &$arg){
// $arg_new = preg_replace('/^id_([^>.,]*)$/',$t1.'.id_$1>$1s.$1',$arg);
// if($arg_new!=null){
// $arg=$arg_new;}
$arg_arr = explode('>',$arg);
// A.B>C.D d(last) JOIN c ON a.b=c.id
$join = null;
if(count($arg_arr)!=1){
$queue=explode('.',end($arg_arr));
$queue=$queue[1];
// field to show
for($i=0;$i<count($arg_arr)-1;$i++){
$a=explode('.',$arg_arr[$i]);
$a1=explode('.',$arg_arr[$i+1]);
if($i == 0){
$aliasduck = $a[0];
}else{
$aliasduck = 'ALIAS'.($token-1);
}
$join .= ' JOIN '.$a1[0]." as ALIAS$token ON $aliasduck.$a[1] = ALIAS$token.id ";
$token++;
}
$arg="ALIAS".(count($arg_arr)-1).".$queue as $a[1] ";
if ($mod!='select'){
$pointer["ALIAS$token"]=$arg_arr[0];
}
}
$q=preg_replace('/(^SELECT ).*( FROM [^ ]* )(.*$)/','$1'.join(',',$arg_field_arr)."$2$join$3",$q);
//echo "REQUÊTE=$q<br/>";
}
}
function sql2html($mod,$q,$o,$e,$m=[]){ //FONCTION PRINCIPALE
global $predefmask,$pdo;
echo "<b>OLD</b> : $q<br/>";
request2ai($q,$field,$pointer,$mod);
echo "<b>NEW</b> : $q";
$table1 = preg_replace('/^SELECT(.*)FROM ([^, ]*)(.*)$/','$2',$q);
$query_arg = get_query_args($q,$pdo);
$arg_field = array_column($query_arg,"Field");
$arg_type = array_column($query_arg,"Type");
$arg_total = count($query_arg);
$arg_used = 0;
$m_size = [];
$data = $pdo->query($q);
if($mod=="update"){//Recuperation des ids
$qtmp = preg_replace('/^SELECT(.*)FROM ([^, ]*)(.*)$/','SELECT $2.id FROM $2$3',$q);
$ids = $pdo->query($qtmp);
while($idstmp = $ids->fetch()){
$data_ids[] = $idstmp;
}
}
$ai_args_to_modify = [];
foreach($m as &$mask){ //Traitement preliminaire des masques
$tmp = size_of_mask($mask);
if($arg_used==$arg_total){echo 'break';break;}
if ($tmp==0){
if($mask=='*'){
$mask = automask($mod,$arg_type[$arg_used],$arg_field[$arg_used],$arg_total-$arg_used,$ai_args_to_modify,$pointer,$table1);
}else{
$mask = $predefmask[$mask];
}
$tmp = size_of_mask($mask);
}
$m_size[]= $tmp;
$arg_used += $tmp;
}
$m = array_slice($m,0,count($m_size));
while($arg_used<$arg_total){ //Ajout des masques automatiques
$m[] = automask($mod,$arg_type[$arg_used],$arg_field[$arg_used],$arg_total-$arg_used,$ai_args_to_modify,$pointer,$table1);
$m_size[] = size_of_mask(end($m));
$arg_used += end($m_size);
}
foreach($arg_field as $t){ //Mise en place de l'entete
$s[] = sprintf($e[3],$t);
}
$flines[] = $s;
$n=0;
while ($line = $data->fetch()){ //Generation du resulat dans un tableau
$i=0;
$fcells = null;
foreach($m as $k=>$v){//Mise en place des cellules
$cell=vsprintf($v,array_slice($line,$i,$m_size[$k]));
if ($mod!='select'){
$cell=cellule_check(str_replace('<AI_ID>',$data_ids[$n]['id'],$cell));
}
$fcells[] = sprintf($e[2],$cell);
$i += $m_size[$k];
}
$flines[] = $fcells;
$n++;
//ajout de chaque lignes
}
if($o=='v'){//Rotation du tableau
$flines = flip($flines);
}
$ftable = null;
foreach($flines as $l){//Mise en forme du resultat
$ftable .= sprintf($e[1],join('',$l));
//ajout des balises de ligne
}
if($mod=='update'){//Installation des ids cachés
$hidden_data[] = '<input type="hidden" name="ai_table" value="'.$table1.'"/>';
foreach($ai_args_to_modify as &$arg){
echo "arg ancien=$arg<br/>";
if (isset($pointer[$arg])){
//echo "arg=$arg => ".$pointer[$arg]."<br/>";
$arg=$pointer[$arg];
echo "arg nouveau=$arg<br/>";
}
$hidden_data[] = "<input type='hidden' name='ai_args_to_modify[]' value='$arg'/>";
}
foreach($data_ids as $id){
$hidden_data[] = "<input type='hidden' name='ai_data_id[]' value='$id[id]'/>";
}
$ftable=join('',$hidden_data).$ftable;
}
return sprintf($e[0],$ftable);
//ajout des balises de tableau et retour du resultat
}
function update(){ //GENERATION ET EXECUTION DES REQUETES D'UPDATE (ZERO SECURITE)
global $pdo;
show($_POST,'post');
$pre_request = "UPDATE %s SET %s WHERE id = %s";
$new_data = flip(array_slice($_POST,3,count($_POST)-3)); // sauf ai_table, ai_args_to_modify et ai_data_id
//show($new_data,'newdata');
foreach ($_POST['ai_data_id'] as $id){
$modifs= [];
foreach ($_POST['ai_args_to_modify'] as $arg){
if (!isset($new_data[$id][$arg])){
$modifs[]= $arg.' = ""';
}else{
$modifs[] = $arg.' = "'.join(',',$new_data[$id][$arg]).'"';
}
}
$request = sprintf($pre_request,$_POST['ai_table'],join(' , ',$modifs),$id);
echo "$request <br>";
$pdo->query($request);
}
}
if(isset($_POST['ai_table'])){
update();
}
$q='SELECT duck,id_ville,ducks.id_ville>villes.id_fondateur>fondateurs.billy>architectes.architecte,ducks.naissance>villes.ville FROM ducks order by ducks.id LIMIT 10';
echo sql2html('update',$q,'v',$form_envelop);
?>
</body>
</html>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment