From 397e75005a17d995dfdbad0befd90d00b4d51e09 Mon Sep 17 00:00:00 2001 From: Metolius Research Date: Sat, 28 Feb 2026 09:43:59 -0800 Subject: [PATCH 1/7] Security hardening and Adminer upgrade - Upgrade bundled Adminer files to 5.4.2 (adminer.php, adminer-de.php, adminer-fr.php) - Harden shell command construction in config/play/species tools using escapeshellarg - Tighten path validation for delete/rename flows - Replace deprecated FILTER_SANITIZE_STRING usage with FILTER_SANITIZE_FULL_SPECIAL_CHARS - Make notifications resilient when apprise is unavailable and use context manager for body file reads - Fix get_wav_files path handling in helpers.py --- scripts/adminer-de.php | 2407 ++++++++++++++++++++++---------- scripts/adminer-fr.php | 2407 ++++++++++++++++++++++---------- scripts/adminer.php | 2407 ++++++++++++++++++++++---------- scripts/config.php | 13 +- scripts/history.php | 4 +- scripts/play.php | 30 +- scripts/species_tools.php | 26 +- scripts/stats.php | 4 +- scripts/todays_detections.php | 4 +- scripts/utils/helpers.py | 1 - scripts/utils/notifications.py | 11 +- 11 files changed, 4969 insertions(+), 2345 deletions(-) diff --git a/scripts/adminer-de.php b/scripts/adminer-de.php index 95471c73a8..52e2f24a74 100644 --- a/scripts/adminer-de.php +++ b/scripts/adminer-de.php @@ -5,300 +5,286 @@ * @copyright 2007 Jakub Vrana * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 * @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other) -* @version 4.8.1 -*/$_GET['sqlite']='';class -AdminerPlugin -extends -Adminer{var$plugins;function -_findRootClass($Ja){do$K=$Ja;while($Ja=get_parent_class($Ja));return$K;}function -__construct($Ge){if($Ge===null){$Ge=array();foreach(get_declared_classes()as$Ja){if(preg_match('~^Adminer.~i',$Ja)&&strcasecmp($this->_findRootClass($Ja),'Adminer'))$Ge[$Ja]=new$Ja;}}$this->plugins=$Ge;}function -_callParent($s,$c){return -call_user_func_array(array('parent',$s),$c);}function -_applyPlugin($s,$c){foreach($this->plugins -as$Fe){if(method_exists($Fe,$s)){switch(count($c)){case -0:$K=$Fe->$s();break;case -1:$K=$Fe->$s($c[0]);break;case -2:$K=$Fe->$s($c[0],$c[1]);break;case -3:$K=$Fe->$s($c[0],$c[1],$c[2]);break;case -4:$K=$Fe->$s($c[0],$c[1],$c[2],$c[3]);break;case -5:$K=$Fe->$s($c[0],$c[1],$c[2],$c[3],$c[4]);break;case -6:$K=$Fe->$s($c[0],$c[1],$c[2],$c[3],$c[4],$c[5]);break;default:trigger_error('Too many parameters.',E_USER_WARNING);}if($K!==null)return$K;}}return$this->_callParent($s,$c);}function -_appendPlugin($s,$c){$K=$this->_callParent($s,$c);foreach($this->plugins -as$Fe){if(method_exists($Fe,$s)){$Y=call_user_func_array(array($Fe,$s),$c);if($Y)$K+=$Y;}}return$K;}function -dumpFormat(){$c=func_get_args();return$this->_appendPlugin(__FUNCTION__,$c);}function -dumpOutput(){$c=func_get_args();return$this->_appendPlugin(__FUNCTION__,$c);}function -editRowPrint($R,$n,$L,$Kg){$c=func_get_args();return$this->_appendPlugin(__FUNCTION__,$c);}function -editFunctions($m){$c=func_get_args();return$this->_appendPlugin(__FUNCTION__,$c);}function -name(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -credentials(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -connectSsl(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -permanentLogin($h=false){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -bruteForceKey(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -serverName($O){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -database(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -schemas(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -databases($mc=true){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -queryTimeout(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -headers(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -csp(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -head(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -css(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -loginForm(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -loginFormField($F,$Ec,$Y){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -login($rd,$_e){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -tableName($Vf){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -fieldName($m,$fe=0){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLinks($Vf,$P=""){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -foreignKeys($R){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -backwardKeys($R,$Uf){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -backwardKeysPrint($va,$L){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectQuery($I,$Lf,$fc=false){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -sqlCommandQuery($I){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -rowDescription($R){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -rowDescriptions($M,$pc){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLink($X,$m){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectVal($X,$A,$m,$ne){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -editVal($X,$m){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -tableStructurePrint($n){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -tableIndexesPrint($x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectColumnsPrint($N,$e){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectSearchPrint($Z,$e,$x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectOrderPrint($fe,$e,$x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLimitPrint($_){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLengthPrint($ig){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectActionPrint($x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectCommandPrint(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectImportPrint(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectEmailPrint($Lb,$e){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectColumnsProcess($e,$x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectSearchProcess($n,$x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectOrderProcess($n,$x){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLimitProcess(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectLengthProcess(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectEmailProcess($Z,$pc){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -selectQueryBuild($N,$Z,$t,$fe,$_,$G){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -messageQuery($I,$jg,$fc=false){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -editInput($R,$m,$ra,$Y){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -editHint($R,$m,$Y){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -processInput($m,$Y,$s=""){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -dumpDatabase($j){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -dumpTable($R,$Pf,$Yc=0){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -dumpData($R,$Pf,$I){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -dumpFilename($Jc){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -dumpHeaders($Jc,$Id=false){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -importServerPath(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -homepage(){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -navigation($Hd){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -databasesPrint($Hd){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}function -tablesPrint($T){$c=func_get_args();return$this->_applyPlugin(__FUNCTION__,$c);}}class -FCSqliteConnectionWithoutCredentials{function -loginForm(){$b=adminer();echo'
'.'Warnung: Verwenden Sie es nicht in einer Produktionsumgebung!'.'
',"\n",'',$b->loginFormField('db','
'.'Datenbank'.'',''."\n"),"
\n","

\n";return -true;}function -login($rd,$_e){return -true;}}function -adminer_object(){$Ge=array(new -FCSqliteConnectionWithoutCredentials());return -new -AdminerPlugin($Ge);}function -adminer_errors($Rb,$Tb){return!!preg_match('~^(Trying to access array offset on value of type null|Undefined array key)~',$Tb);}error_reporting(6135);set_error_handler('adminer_errors',E_WARNING);$kc=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($kc||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$Hg=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($Hg)$$X=$Hg;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function -connection(){global$f;return$f;}function -adminer(){global$b;return$b;}function -version(){global$da;return$da;}function -idf_unescape($Kc){if(!preg_match('~^[`\'"]~',$Kc))return$Kc;$hd=substr($Kc,-1);return -str_replace($hd.$hd,$hd,substr($Kc,1,-1));}function +* @version 5.4.2 +*/namespace +Adminer;const +VERSION="5.4.2";error_reporting(24575);set_error_handler(function($Dc,$Fc){return!!preg_match('~^Undefined (array key|offset|index)~',$Fc);},E_WARNING|E_NOTICE);$bd=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($bd||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$xj=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($xj)$$X=$xj;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function +connection($h=null){return($h?:Db::$instance);}function +adminer(){return +Adminer::$instance;}function +driver(){return +Driver::$instance;}function +connect(){$Hb=adminer()->credentials();$J=Driver::connect($Hb[0],$Hb[1],$Hb[2]);return(is_object($J)?$J:null);}function +idf_unescape($v){if(!preg_match('~^[`\'"[]~',$v))return$v;$Le=substr($v,-1);return +str_replace($Le.$Le,$Le,substr($v,1,-1));}function +q($Q){return +connection()->quote($Q);}function escape_string($X){return substr(q($X),1,-1);}function +idx($xa,$y,$l=null){return($xa&&array_key_exists($y,$xa)?$xa[$y]:$l);}function number($X){return preg_replace('~[^0-9]+~','',$X);}function number_type(){return'((?$W){unset($Te[$z][$ad]);if(is_array($W)){$Te[$z][stripslashes($ad)]=$W;$Te[]=&$Te[$z][stripslashes($ad)];}else$Te[$z][stripslashes($ad)]=($kc?$W:stripslashes($W));}}}}function -bracket_escape($Kc,$ua=false){static$vg=array(':'=>':1',']'=>':2','['=>':3','"'=>':4');return -strtr($Kc,($ua?array_flip($vg):$vg));}function -min_version($Xg,$td="",$g=null){global$f;if(!$g)$g=$f;$yf=$g->server_info;if($td&&preg_match('~([\d.]+)-MariaDB~',$yf,$C)){$yf=$C[1];$Xg=$td;}return(version_compare($yf,$Xg)>=0);}function -charset($f){return(min_version("5.5.3",0,$f)?"utf8mb4":"utf8");}function -script($Ff,$ug="\n"){return"$Ff$ug";}function -script_src($Mg){return"\n";}function -nonce(){return' nonce="'.get_nonce().'"';}function -target_blank(){return' target="_blank" rel="noreferrer noopener"';}function -h($Q){return -str_replace("\0","�",htmlspecialchars($Q,ENT_QUOTES,'utf-8'));}function -nl_br($Q){return -str_replace("\n","
",$Q);}function -checkbox($F,$Y,$Fa,$ed="",$Yd="",$Ja="",$fd=""){$K="".($Yd?script("qsl('input').onclick = function () { $Yd };",""):"");return($ed!=""||$Ja?"$K".h($ed)."":$K);}function -optionlist($de,$tf=null,$Qg=false){$K="";foreach($de -as$ad=>$W){$ee=array($ad=>$W);if(is_array($W)){$K.='';$ee=$W;}foreach($ee -as$z=>$X)$K.=''.h($X);if(is_array($W))$K.='';}return$K;}function -html_select($F,$de,$Y="",$Xd=true,$fd=""){if($Xd)return"".(is_string($Xd)?script("qsl('select').onchange = function () { $Xd };",""):"");$K="";foreach($de -as$z=>$X)$K.="";return$K;}function -select_input($ra,$de,$Y="",$Xd="",$Ee=""){$cg=($de?"select":"input");return"<$cg$ra".($de?">

","$md",script("qsl('a').onclick = partial(toggle, 'fieldset-$v');",""),"","
\n";}function -selectOrderPrint($fe,$e,$x){print_fieldset("sort",'Ordnen',$fe);$u=0;foreach((array)$_GET["order"]as$z=>$X){if($X!=""){echo"
".select_input(" name='order[$u]'",$e,$X,"selectFieldChange"),checkbox("desc[$u]",1,isset($_GET["desc"][$z]),'absteigend')."
\n";$u++;}}echo"
".select_input(" name='order[$u]'",$e,"","selectAddRow"),checkbox("desc[$u]",1,false,'absteigend')."
\n","\n";}function -selectLimitPrint($_){echo"
".'Begrenzung'."
";echo"",script("qsl('input').oninput = selectFieldChange;",""),"
\n";}function -selectLengthPrint($ig){if($ig!==null){echo"
".'Textlänge'."
","","
\n";}}function -selectActionPrint($x){echo"
".'Aktion'."
",""," ","\n","var indexColumns = ";$e=array();foreach($x -as$w){$gb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$gb)$e[$gb]=1;}$e[""]=1;foreach($e -as$z=>$X)json_row($z);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
\n";}function +rowDescriptions(array$L,array$ld){return$L;}function +selectLink($X,array$n){}function +selectVal($X,$_,array$n,$sg){$J=($X===null?"NULL":(preg_match("~char|binary|boolean~",$n["type"])&&!preg_match("~var~",$n["type"])?"$X":(preg_match('~json~',$n["type"])?"$X":$X)));if(is_blob($n)&&!is_utf8($X))$J="".lang(48,strlen($sg))."";return($_?"$J":$J);}function +editVal($X,array$n){return$X;}function +config(){return +array();}function +tableStructurePrint(array$o,$Bi=null){echo"
\n","\n","\n";$vi=driver()->structuredTypes();foreach($o +as$n){echo"
".lang(49)."".lang(50).(support("comment")?"".lang(51):"")."
".h($n["field"]);$U=h($n["full_type"]);$c=h($n["collation"]);echo"".(in_array($U,(array)$vi[lang(6)])?"$U":$U.($c&&isset($Bi["Collation"])&&$c!=$Bi["Collation"]?" $c":""))."",($n["null"]?" NULL":""),($n["auto_increment"]?" ".lang(52)."":"");$l=h($n["default"]);echo(isset($n["default"])?" [".($n["generated"]?"$l":$l)."]":""),(support("comment")?"".h($n["comment"]):""),"\n";}echo"
\n","
\n";}function +tableIndexesPrint(array$x,array$Bi){$Cg=false;foreach($x +as$B=>$w)$Cg|=!!$w["partial"];echo"\n";$Ub=first(driver()->indexAlgorithms($Bi));foreach($x +as$B=>$w){ksort($w["columns"]);$bh=array();foreach($w["columns"]as$y=>$X)$bh[]="".h($X)."".($w["lengths"][$y]?"(".$w["lengths"][$y].")":"").($w["descs"][$y]?" DESC":"");echo"","
$w[type]".($Ub&&$w['algorithm']!=$Ub?" ($w[algorithm])":""),"".implode(", ",$bh);if($Cg)echo"".($w['partial']?"WHERE ".h($w['partial']):"");echo"\n";}echo"
\n";}function +selectColumnsPrint(array$M,array$e){print_fieldset("select",lang(54),$M);$t=0;$M[""]=array();foreach($M +as$y=>$X){$X=idx($_GET["columns"],$y,array());$d=select_input(" name='columns[$t][col]'",$e,$X["col"],($y!==""?"selectFieldChange":"selectAddRow"));echo"
".(driver()->functions||driver()->grouping?html_select("columns[$t][fun]",array(-1=>"")+array_filter(array(lang(55)=>driver()->functions,lang(56)=>driver()->grouping)),$X["fun"]).on_help("event.target.value && event.target.value.replace(/ |\$/, '(') + ')'",1).script("qsl('select').onchange = function () { helpClose();".($y!==""?"":" qsl('select, input', this.parentNode).onchange();")." };","")."($d)":$d)."
\n";$t++;}echo"\n";}function +selectSearchPrint(array$Z,array$e,array$x){print_fieldset("search",lang(57),$Z);foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT")echo"
(".implode(", ",array_map('Adminer\h',$w["columns"])).") AGAINST"," ",script("qsl('input').oninput = selectFieldChange;",""),(JUSH=='sql'?checkbox("boolean[$t]",1,isset($_GET["boolean"][$t]),"BOOL"):''),"
\n";}$Va="this.parentNode.firstChild.onchange();";foreach(array_merge((array)$_GET["where"],array(array()))as$t=>$X){if(!$X||("$X[col]$X[val]"!=""&&in_array($X["op"],adminer()->operators())))echo"
".select_input(" name='where[$t][col]'",$e,$X["col"],($X?"selectFieldChange":"selectAddRow"),"(".lang(58).")"),html_select("where[$t][op]",adminer()->operators(),$X["op"],$Va),"",script("mixin(qsl('input'), {oninput: function () { $Va }, onkeydown: selectSearchKeydown, onsearch: selectSearchSearch});",""),"
\n";}echo"\n";}function +selectOrderPrint(array$ig,array$e,array$x){print_fieldset("sort",lang(59),$ig);$t=0;foreach((array)$_GET["order"]as$y=>$X){if($X!=""){echo"
".select_input(" name='order[$t]'",$e,$X,"selectFieldChange"),checkbox("desc[$t]",1,isset($_GET["desc"][$y]),lang(60))."
\n";$t++;}}echo"
".select_input(" name='order[$t]'",$e,"","selectAddRow"),checkbox("desc[$t]",1,false,lang(60))."
\n","\n";}function +selectLimitPrint($z){echo"
".lang(61)."
","",script("qsl('input').oninput = selectFieldChange;",""),"
\n";}function +selectLengthPrint($Si){if($Si!==null)echo"
".lang(62)."
","","
\n";}function +selectActionPrint(array$x){echo"
".lang(63)."
",""," ","\n","const indexColumns = ";$e=array();foreach($x +as$w){$Lb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$Lb)$e[$Lb]=1;}$e[""]=1;foreach($e +as$y=>$X)json_row($y);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
\n";}function selectCommandPrint(){return!information_schema(DB);}function selectImportPrint(){return!information_schema(DB);}function -selectEmailPrint($Lb,$e){}function -selectColumnsProcess($e,$x){global$uc,$yc;$N=array();$t=array();foreach((array)$_GET["columns"]as$z=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],$uc)||in_array($X["fun"],$yc)))){$N[$z]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],$yc))$t[]=$N[$z];}}return -array($N,$t);}function -selectSearchProcess($n,$x){global$f,$k;$K=array();foreach($x -as$u=>$w){if($w["type"]=="FULLTEXT"&&$_GET["fulltext"][$u]!="")$K[]="MATCH (".implode(", ",array_map('idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$u]).(isset($_GET["boolean"][$u])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$z=>$X){if("$X[col]$X[val]"!=""&&in_array($X["op"],$this->operators)){$Me="";$Va=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Nc=process_length($X["val"]);$Va.=" ".($Nc!=""?$Nc:"(NULL)");}elseif($X["op"]=="SQL")$Va=" $X[val]";elseif($X["op"]=="LIKE %%")$Va=" LIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="ILIKE %%")$Va=" ILIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Me="$X[op](".q($X["val"]).", ";$Va=")";}elseif(!preg_match('~NULL$~',$X["op"]))$Va.=" ".$this->processInput($n[$X["col"]],$X["val"]);if($X["col"]!="")$K[]=$Me.$k->convertSearch(idf_escape($X["col"]),$X,$n[$X["col"]]).$Va;else{$Qa=array();foreach($n -as$F=>$m){if((preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$m["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$m["type"]))&&(!preg_match('~date|timestamp~',$m["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"])))$Qa[]=$Me.$k->convertSearch(idf_escape($F),$X,$m).$Va;}$K[]=($Qa?"(".implode(" OR ",$Qa).")":"1 = 0");}}}return$K;}function -selectOrderProcess($n,$x){$K=array();foreach((array)$_GET["order"]as$z=>$X){if($X!="")$K[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$z])?" DESC":"");}return$K;}function -selectLimitProcess(){return(isset($_GET["limit"])?$_GET["limit"]:"50");}function -selectLengthProcess(){return(isset($_GET["text_length"])?$_GET["text_length"]:"100");}function -selectEmailProcess($Z,$pc){return +selectEmailPrint(array$vc,array$e){}function +selectColumnsProcess(array$e,array$x){$M=array();$xd=array();foreach((array)$_GET["columns"]as$y=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],driver()->functions)||in_array($X["fun"],driver()->grouping)))){$M[$y]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],driver()->grouping))$xd[]=$M[$y];}}return +array($M,$xd);}function +selectSearchProcess(array$o,array$x){$J=array();foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT"&&idx($_GET["fulltext"],$t)!="")$J[]="MATCH (".implode(", ",array_map('Adminer\idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$t]).(isset($_GET["boolean"][$t])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$y=>$X){$jb=$X["col"];if("$jb$X[val]"!=""&&in_array($X["op"],adminer()->operators())){$ub=array();foreach(($jb!=""?array($jb=>$o[$jb]):$o)as$B=>$n){$Xg="";$tb=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Xd=process_length($X["val"]);$tb +.=" ".($Xd!=""?$Xd:"(NULL)");}elseif($X["op"]=="SQL")$tb=" $X[val]";elseif(preg_match('~^(I?LIKE) %%$~',$X["op"],$A))$tb=" $A[1] ".adminer()->processInput($n,"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Xg="$X[op](".q($X["val"]).", ";$tb=")";}elseif(!preg_match('~NULL$~',$X["op"]))$tb +.=" ".adminer()->processInput($n,$X["val"]);if($jb!=""||(isset($n["privileges"]["where"])&&(preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$n["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$n["type"]))&&(!preg_match('~date|timestamp~',$n["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"]))))$ub[]=$Xg.driver()->convertSearch(idf_escape($B),$X,$n).$tb;}$J[]=(count($ub)==1?$ub[0]:($ub?"(".implode(" OR ",$ub).")":"1 = 0"));}}return$J;}function +selectOrderProcess(array$o,array$x){$J=array();foreach((array)$_GET["order"]as$y=>$X){if($X!="")$J[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$y])?" DESC":"");}return$J;}function +selectLimitProcess(){return(isset($_GET["limit"])?intval($_GET["limit"]):50);}function +selectLengthProcess(){return(isset($_GET["text_length"])?"$_GET[text_length]":"100");}function +selectEmailProcess(array$Z,array$ld){return false;}function -selectQueryBuild($N,$Z,$t,$fe,$_,$G){return"";}function -messageQuery($I,$jg,$fc=false){global$y,$k;restart_session();$Fc=&get_session("queries");if(!$Fc[$_GET["db"]])$Fc[$_GET["db"]]=array();if(strlen($I)>1e6)$I=preg_replace('~[\x80-\xFF]+$~','',substr($I,0,1e6))."\n…";$Fc[$_GET["db"]][]=array($I,time(),$jg);$Jf="sql-".count($Fc[$_GET["db"]]);$K="".'SQL-Kommando'."\n";if(!$fc&&($ch=$k->warnings())){$v="warnings-".count($Fc[$_GET["db"]]);$K="".'Warnings'.", $K\n";}return" ".@date("H:i:s").""." $K';}function -editRowPrint($R,$n,$L,$Kg){}function -editFunctions($m){global$Gb;$K=($m["null"]?"NULL/":"");$Kg=isset($_GET["select"])||where($_GET);foreach($Gb -as$z=>$uc){if(!$z||(!isset($_GET["call"])&&$Kg)){foreach($uc -as$Be=>$X){if(!$Be||preg_match("~$Be~",$m["type"]))$K.="/$X";}}if($z&&!preg_match('~set|blob|bytea|raw|file|bool~',$m["type"]))$K.="/SQL";}if($m["auto_increment"]&&!$Kg)$K='Auto-Inkrement';return -explode("/",$K);}function -editInput($R,$m,$ra,$Y){if($m["type"]=="enum")return(isset($_GET["select"])?" ":"").($m["null"]?" ":"").enum_input("radio",$ra,$m,$Y,0);return"";}function -editHint($R,$m,$Y){return"";}function -processInput($m,$Y,$s=""){if($s=="SQL")return$Y;$F=$m["field"];$K=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$K="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$K=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$K=idf_escape($F)." $s $K";elseif(preg_match('~^[+-] interval$~',$s))$K=idf_escape($F)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)?$Y:$K);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$K="$s(".idf_escape($F).", $K)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$K="$s($K)";return -unconvert_field($m,$K);}function -dumpOutput(){$K=array('text'=>'anzeigen','file'=>'Datei');if(function_exists('gzencode'))$K['gz']='gzip';return$K;}function -dumpFormat(){return -array('sql'=>'SQL','csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function -dumpDatabase($j){}function -dumpTable($R,$Pf,$Yc=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($Pf)dump_csv(array_keys(fields($R)));}else{if($Yc==2){$n=array();foreach(fields($R)as$F=>$m)$n[]=idf_escape($F)." $m[full_type]";$h="CREATE TABLE ".table($R)." (".implode(", ",$n).")";}else$h=create_sql($R,$_POST["auto_increment"],$Pf);set_utf8mb4($h);if($Pf&&$h){if($Pf=="DROP+CREATE"||$Yc==1)echo"DROP ".($Yc==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($Yc==1)$h=remove_definer($h);echo"$h;\n\n";}}}function -dumpData($R,$Pf,$I){global$f,$y;$wd=($y=="sqlite"?0:1048576);if($Pf){if($_POST["format"]=="sql"){if($Pf=="TRUNCATE+INSERT")echo -truncate_sql($R).";\n";$n=fields($R);}$J=$f->query($I,1);if($J){$Sc="";$Ca="";$cd=array();$Rf="";$ic=($R!=''?'fetch_assoc':'fetch_row');while($L=$J->$ic()){if(!$cd){$Ug=array();foreach($L -as$X){$m=$J->fetch_field();$cd[]=$m->name;$z=idf_escape($m->name);$Ug[]="$z = VALUES($z)";}$Rf=($Pf=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Ug):"").";\n";}if($_POST["format"]!="sql"){if($Pf=="table"){dump_csv($cd);$Pf="INSERT";}dump_csv($L);}else{if(!$Sc)$Sc="INSERT INTO ".table($R)." (".implode(", ",array_map('idf_escape',$cd)).") VALUES";foreach($L -as$z=>$X){$m=$n[$z];$L[$z]=($X!==null?unconvert_field($m,preg_match(number_type(),$m["type"])&&!preg_match('~\[~',$m["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$pf=($wd?"\n":" ")."(".implode(",\t",$L).")";if(!$Ca)$Ca=$Sc.$pf;elseif(strlen($Ca)+4+strlen($pf)+strlen($Rf)<$wd)$Ca.=",$pf";else{echo$Ca.$Rf;$Ca=$Sc.$pf;}}}if($Ca)echo$Ca.$Rf;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",$f->error)."\n";}}function -dumpFilename($Jc){return -friendly_url($Jc!=""?$Jc:(SERVER!=""?SERVER:"localhost"));}function -dumpHeaders($Jc,$Id=false){$qe=$_POST["output"];$bc=(preg_match('~sql~',$_POST["format"])?"sql":($Id?"tar":"csv"));header("Content-Type: ".($qe=="gz"?"application/x-gzip":($bc=="tar"?"application/x-tar":($bc=="sql"||$qe!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($qe=="gz")ob_start('ob_gzencode',1e6);return$bc;}function +selectQueryBuild(array$M,array$Z,array$xd,array$ig,$z,$D){return"";}function +messageQuery($H,$Ti,$Tc=false){restart_session();$Kd=&get_session("queries");if(!idx($Kd,$_GET["db"]))$Kd[$_GET["db"]]=array();if(strlen($H)>1e6)$H=preg_replace('~[\x80-\xFF]+$~','',substr($H,0,1e6))."\n…";$Kd[$_GET["db"]][]=array($H,time(),$Ti);$oi="sql-".count($Kd[$_GET["db"]]);$J="".lang(65)." �\n";if(!$Tc&&($Vj=driver()->warnings())){$u="warnings-".count($Kd[$_GET["db"]]);$J="".lang(47).", $J\n";}return" ".@date("H:i:s").""." $J';}function +editRowPrint($R,array$o,$K,$_j){}function +editFunctions(array$n){$J=($n["null"]?"NULL/":"");$_j=isset($_GET["select"])||where($_GET);foreach(array(driver()->insertFunctions,driver()->editFunctions)as$y=>$sd){if(!$y||(!isset($_GET["call"])&&$_j)){foreach($sd +as$Lg=>$X){if(!$Lg||preg_match("~$Lg~",$n["type"]))$J +.="/$X";}}if($y&&$sd&&!preg_match('~set|bool~',$n["type"])&&!is_blob($n))$J +.="/SQL";}if($n["auto_increment"]&&!$_j)$J=lang(52);return +explode("/",$J);}function +editInput($R,array$n,$_a,$Y){if($n["type"]=="enum")return(isset($_GET["select"])?" ":"").enum_input("radio",$_a,$n,$Y,"NULL");return"";}function +editHint($R,array$n,$Y){return"";}function +processInput(array$n,$Y,$s=""){if($s=="SQL")return$Y;$B=$n["field"];$J=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$J="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$J=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$J=idf_escape($B)." $s $J";elseif(preg_match('~^[+-] interval$~',$s))$J=idf_escape($B)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)&&JUSH!="pgsql"?$Y:$J);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$J="$s(".idf_escape($B).", $J)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$J="$s($J)";return +unconvert_field($n,$J);}function +dumpOutput(){$J=array('text'=>lang(66),'file'=>lang(67));if(function_exists('gzencode'))$J['gz']='gzip';return$J;}function +dumpFormat(){return(support("dump")?array('sql'=>'SQL'):array())+array('csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function +dumpDatabase($k){}function +dumpTable($R,$wi,$ze=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($wi)dump_csv(array_keys(fields($R)));}else{if($ze==2){$o=array();foreach(fields($R)as$B=>$n)$o[]=idf_escape($B)." $n[full_type]";$i="CREATE TABLE ".table($R)." (".implode(", ",$o).")";}else$i=create_sql($R,$_POST["auto_increment"],$wi);set_utf8mb4($i);if($wi&&$i){if($wi=="DROP+CREATE"||$ze==1)echo"DROP ".($ze==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($ze==1)$i=remove_definer($i);echo"$i;\n\n";}}}function +dumpData($R,$wi,$H){if($wi){$hf=(JUSH=="sqlite"?0:1048576);$o=array();$Td=false;if($_POST["format"]=="sql"){if($wi=="TRUNCATE+INSERT")echo +truncate_sql($R).";\n";$o=fields($R);if(JUSH=="mssql"){foreach($o +as$n){if($n["auto_increment"]){echo"SET IDENTITY_INSERT ".table($R)." ON;\n";$Td=true;break;}}}}$I=connection()->query($H,1);if($I){$oe="";$Pa="";$Ee=array();$td=array();$yi="";$Wc=($R!=''?'fetch_assoc':'fetch_row');$Eb=0;while($K=$I->$Wc()){if(!$Ee){$Nj=array();foreach($K +as$X){$n=$I->fetch_field();if(idx($o[$n->name],'generated')){$td[$n->name]=true;continue;}$Ee[]=$n->name;$y=idf_escape($n->name);$Nj[]="$y = VALUES($y)";}$yi=($wi=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj):"").";\n";}if($_POST["format"]!="sql"){if($wi=="table"){dump_csv($Ee);$wi="INSERT";}dump_csv($K);}else{if(!$oe)$oe="INSERT INTO ".table($R)." (".implode(", ",array_map('Adminer\idf_escape',$Ee)).") VALUES";foreach($K +as$y=>$X){if($td[$y]){unset($K[$y]);continue;}$n=$o[$y];$K[$y]=($X!==null?unconvert_field($n,preg_match(number_type(),$n["type"])&&!preg_match('~\[~',$n["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$Hh=($hf?"\n":" ")."(".implode(",\t",$K).")";if(!$Pa)$Pa=$oe.$Hh;elseif(JUSH=='mssql'?$Eb%1000!=0:strlen($Pa)+4+strlen($Hh)+strlen($yi)<$hf)$Pa +.=",$Hh";else{echo$Pa.$yi;$Pa=$oe.$Hh;}}$Eb++;}if($Pa)echo$Pa.$yi;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",connection()->error)."\n";if($Td)echo"SET IDENTITY_INSERT ".table($R)." OFF;\n";}}function +dumpFilename($Rd){return +friendly_url($Rd!=""?$Rd:(SERVER?:"localhost"));}function +dumpHeaders($Rd,$Af=false){$vg=$_POST["output"];$Oc=(preg_match('~sql~',$_POST["format"])?"sql":($Af?"tar":"csv"));header("Content-Type: ".($vg=="gz"?"application/x-gzip":($Oc=="tar"?"application/x-tar":($Oc=="sql"||$vg!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($vg=="gz"){ob_start(function($Q){return +gzencode($Q);},1e6);}return$Oc;}function +dumpFooter(){if($_POST["format"]=="sql")echo"-- ".gmdate("Y-m-d H:i:s e")."\n";}function importServerPath(){return"adminer.sql";}function -homepage(){echo'

-',$this->name(),' ',$da,' -',(version_compare($da,$_COOKIE["adminer_version"])<0?h($_COOKIE["adminer_version"]):""),' -

-';if($Hd=="auth"){$qe="";foreach((array)$_SESSION["pwds"]as$Wg=>$zf){foreach($zf -as$O=>$Sg){foreach($Sg -as$Rg=>$_e){if($_e!==null){$mb=$_SESSION["db"][$Wg][$O][$Rg];foreach(($mb?array_keys($mb):array(""))as$j)$qe.="
  • ($zb[$Wg]) ".h($Rg.($O!=""?"@".$this->serverName($O):"").($j!=""?" - $j":""))."\n";}}}}if($qe)echo"\n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$Hd&&DB!=""){$f->select_db(DB);$T=table_status('',true);}echo -script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=4.8.1");if(support("sql")){echo' -';if($T){$qd=array();foreach($T -as$R=>$V)$qd[]=preg_quote($R,'/');echo"var jushLinks = { $y: [ '".js_escape(ME).(support("table")?"table=":"select=")."\$&', /\\b(".implode("|",$qd).")\\b/g ] };\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.$y;\n";}$yf=$f->server_info;echo'bodyLoad(\'',(is_object($f)?preg_replace('~^(\d\.?\d).*~s','\1',$yf):""),'\'',(preg_match('~MariaDB~',$yf)?", true":""),'); - -';}$this->databasesPrint($Hd);if(DB==""||!$Hd){echo"

    ".'Keine Tabellen.'."\n";else$this->tablesPrint($T);}}}function -databasesPrint($Hd){global$b,$f;$i=$this->databases();if(DB&&$i&&!in_array(DB,$i))array_unshift($i,DB);echo'

    -

    -';hidden_fields_get();$kb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"".'DB'.": ".($i?"$kb":"\n"),"\n";foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo"";break;}}echo"

    \n";}function -tablesPrint($T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T -as$R=>$Mf){$F=$this->tableName($Mf);if($F!=""){echo'
    • ".'zeigen'." ",(support("table")||support("indexes")?'$F":"$F")."\n";}}echo"
    \n";}}$b=(function_exists('adminer_object')?adminer_object():new -Adminer);$Wa=driver_config();$Le=$Wa['possible_drivers'];$y=$Wa['jush'];$Cg=$Wa['types'];$Of=$Wa['structured_types'];$Jg=$Wa['unsigned'];$ae=$Wa['operators'];$uc=$Wa['functions'];$yc=$Wa['grouping'];$Gb=$Wa['edit_functions'];if($b->operators===null)$b->operators=$ae;define("SERVER",$_GET[DRIVER]);define("DB",$_GET["db"]);define("ME",preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));$da="4.8.1";function -page_header($mg,$l="",$Ba=array(),$ng=""){global$ba,$da,$b,$zb,$y;page_headers();if(is_ajax()&&$l){page_messages($l);exit;}$og=$mg.($ng!=""?": $ng":"");$pg=strip_tags($og.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".$b->name());echo' - +navigation($xf){echo"

    ".adminer()->name()." ".VERSION;$If=$_COOKIE["adminer_version"];echo" ".(version_compare(VERSION,$If)<0?h($If):"")."","

    \n";switch_lang();if($xf=="auth"){$vg="";foreach((array)$_SESSION["pwds"]as$Pj=>$ai){foreach($ai +as$N=>$Jj){$B=h(get_setting("vendor-$Pj-$N")?:get_driver($Pj));foreach($Jj +as$V=>$F){if($F!==null){$Sb=$_SESSION["db"][$Pj][$N][$V];foreach(($Sb?array_keys($Sb):array(""))as$k)$vg +.="
  • ($B) ".h("$V@".($N!=""?adminer()->serverName($N):"").($k!=""?" - $k":""))."\n";}}}}if($vg)echo"\n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$xf&&DB!=""){connection()->select_db(DB);$T=table_status('',true);}adminer()->syntaxHighlighting($T);adminer()->databasesPrint($xf);$ka=array();if(DB==""||!$xf){if(support("sql")){$ka[]="".lang(65)."";$ka[]="".lang(76)."";}$ka[]="".lang(77)."";}$Yd=$_GET["ns"]!==""&&!$xf&&DB!="";if($Yd&&function_exists('Adminer\alter_table'))$ka[]='".lang(78)."";echo($ka?"

    ".lang(11)."

    \n";}}}function +syntaxHighlighting(array$T){echo +script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=5.4.2",true);if(support("sql")){echo"\n";if($T){$Ve=array();foreach($T +as$R=>$U)$Ve[]=preg_quote($R,'/');echo"var jushLinks = { ".JUSH.":";json_row(js_escape(ME).(support("table")?"table":"select").'=$&','/\b('.implode('|',$Ve).')\b/g',false);if(support('routine')){foreach(routines()as$K)json_row(js_escape(ME).'function='.urlencode($K["SPECIFIC_NAME"]).'&name=$&','/\b'.preg_quote($K["ROUTINE_NAME"],'/').'(?=["`]?\()/g',false);}json_row('');echo"};\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.".JUSH.";\n";if(isset($_GET["sql"])||isset($_GET["trigger"])||isset($_GET["check"])){$Ii=array_fill_keys(array_keys($T),array());foreach(driver()->allFields()as$R=>$o){foreach($o +as$n)$Ii[$R][]=$n["field"];}echo"addEventListener('DOMContentLoaded', () => { autocompleter = jush.autocompleteSql('".idf_escape("")."', ".json_encode($Ii)."); });\n";}}echo"\n";}echo +script("syntaxHighlighting('".preg_replace('~^(\d\.?\d).*~s','\1',connection()->server_info)."', '".connection()->flavor."');");}function +databasesPrint($xf){$j=adminer()->databases();if(DB&&$j&&!in_array(DB,$j))array_unshift($j,DB);echo"
    \n

    \n";hidden_fields_get();$Qb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"","\n";if(support("scheme")){if($xf!="db"&&DB!=""&&connection()->select_db(DB)){echo"
    ";if($_GET["ns"]!="")set_schema($_GET["ns"]);}}foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo +input_hidden($X);break;}}echo"

    \n";}function +tablesPrint(array$T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T +as$R=>$P){$R="$R";$B=adminer()->tableName($P);if($B!=""&&!$P["partition"])echo'
    • ".lang(81)." ",(support("table")||support("indexes")?'$B":"$B")."\n";}echo"
    \n";}function +showVariables(){return +show_variables();}function +showStatus(){return +show_status();}function +processList(){return +process_list();}function +killProcess($u){return +kill_process($u);}}class +Plugins{private +static$append=array('dumpFormat'=>true,'dumpOutput'=>true,'editRowPrint'=>true,'editFunctions'=>true,'config'=>true);var$plugins;var$error='';private$hooks=array();function +__construct($Qg){if($Qg===null){$Qg=array();$Ja="adminer-plugins";if(is_dir($Ja)){foreach(glob("$Ja/*.php")as$p)$this->includeOnce($p);}$Jd=" href='https://www.adminer.org/plugins/#use'".target_blank();if(file_exists("$Ja.php")){$Zd=$this->includeOnce("$Ja.php");if(is_array($Zd)){foreach($Zd +as$Pg)$Qg[get_class($Pg)]=$Pg;}else$this->error +.=lang(82,"$Ja.php",$Jd)."
    ";}foreach(get_declared_classes()as$fb){if(!$Qg[$fb]&&(preg_match('~^Adminer\w~i',$fb)||is_subclass_of($fb,'Adminer\Plugin'))){$sh=new +\ReflectionClass($fb);$zb=$sh->getConstructor();if($zb&&$zb->getNumberOfRequiredParameters())$this->error +.=lang(83,$Jd,"$fb","$Ja.php")."
    ";else$Qg[$fb]=new$fb;}}}$this->plugins=$Qg;$na=new +Adminer;$Qg[]=$na;$sh=new +\ReflectionObject($na);foreach($sh->getMethods()as$vf){foreach($Qg +as$Pg){$B=$vf->getName();if(method_exists($Pg,$B))$this->hooks[$B][]=$Pg;}}}function +includeOnce($p){return +include_once"./$p";}function +__call($B,array$_g){$wa=array();foreach($_g +as$y=>$X)$wa[]=&$_g[$y];$J=null;foreach($this->hooks[$B]as$Pg){$Y=call_user_func_array(array($Pg,$B),$wa);if($Y!==null){if(!self::$append[$B])return$Y;$J=$Y+(array)$J;}}return$J;}}abstract +class +Plugin{protected$translations=array();function +description(){return$this->lang('');}function +screenshot(){return"";}protected +function +lang($v,$Of=null){$wa=func_get_args();$wa[0]=idx($this->translations[LANG],$v)?:$v;return +call_user_func_array('Adminer\lang_format',$wa);}}Adminer::$instance=(function_exists('adminer_object')?adminer_object():(is_dir("adminer-plugins")||file_exists("adminer-plugins.php")?new +Plugins(null):new +Adminer));SqlDriver::$drivers=array("server"=>"MySQL / MariaDB")+SqlDriver::$drivers;if(!defined('Adminer\DRIVER')){define('Adminer\DRIVER',"server");if(extension_loaded("mysqli")&&$_GET["ext"]!="pdo"){class +Db +extends +\MySQLi{static$instance;var$extension="MySQLi",$flavor='';function +__construct(){parent::init();}function +attach($N,$V,$F){mysqli_report(MYSQLI_REPORT_OFF);list($Nd,$Rg)=host_port($N);$ri=adminer()->connectSsl();if($ri)$this->ssl_set($ri['key'],$ri['cert'],$ri['ca'],'','');$J=@$this->real_connect(($N!=""?$Nd:ini_get("mysqli.default_host")),($N.$V!=""?$V:ini_get("mysqli.default_user")),($N.$V.$F!=""?$F:ini_get("mysqli.default_pw")),null,(is_numeric($Rg)?intval($Rg):ini_get("mysqli.default_port")),(is_numeric($Rg)?null:$Rg),($ri?($ri['verify']!==false?2048:64):0));$this->options(MYSQLI_OPT_LOCAL_INFILE,0);return($J?'':$this->error);}function +set_charset($Xa){if(parent::set_charset($Xa))return +true;parent::set_charset('utf8');return$this->query("SET NAMES $Xa");}function +next_result(){return +self::more_results()&&parent::next_result();}function +quote($Q){return"'".$this->escape_string($Q)."'";}}}elseif(extension_loaded("mysql")&&!((ini_bool("sql.safe_mode")||ini_bool("mysql.allow_local_infile"))&&extension_loaded("pdo_mysql"))){class +Db +extends +SqlDb{private$link;function +attach($N,$V,$F){if(ini_bool("mysql.allow_local_infile"))return +lang(84,"'mysql.allow_local_infile'","MySQLi","PDO_MySQL");$this->link=@mysql_connect(($N!=""?$N:ini_get("mysql.default_host")),($N.$V!=""?$V:ini_get("mysql.default_user")),($N.$V.$F!=""?$F:ini_get("mysql.default_password")),true,131072);if(!$this->link)return +mysql_error();$this->server_info=mysql_get_server_info($this->link);return'';}function +set_charset($Xa){if(function_exists('mysql_set_charset')){if(mysql_set_charset($Xa,$this->link))return +true;mysql_set_charset('utf8',$this->link);}return$this->query("SET NAMES $Xa");}function +quote($Q){return"'".mysql_real_escape_string($Q,$this->link)."'";}function +select_db($Pb){return +mysql_select_db($Pb,$this->link);}function +query($H,$sj=false){$I=@($sj?mysql_unbuffered_query($H,$this->link):mysql_query($H,$this->link));$this->error="";if(!$I){$this->errno=mysql_errno($this->link);$this->error=mysql_error($this->link);return +false;}if($I===true){$this->affected_rows=mysql_affected_rows($this->link);$this->info=mysql_info($this->link);return +true;}return +new +Result($I);}}class +Result{var$num_rows;private$result;private$offset=0;function +__construct($I){$this->result=$I;$this->num_rows=mysql_num_rows($I);}function +fetch_assoc(){return +mysql_fetch_assoc($this->result);}function +fetch_row(){return +mysql_fetch_row($this->result);}function +fetch_field(){$J=mysql_fetch_field($this->result,$this->offset++);$J->orgtable=$J->table;$J->charsetnr=($J->blob?63:0);return$J;}function +__destruct(){mysql_free_result($this->result);}}}elseif(extension_loaded("pdo_mysql")){class +Db +extends +PdoDb{var$extension="PDO_MySQL";function +attach($N,$V,$F){$gg=array(\PDO::MYSQL_ATTR_LOCAL_INFILE=>false);$ri=adminer()->connectSsl();if($ri){if($ri['key'])$gg[\PDO::MYSQL_ATTR_SSL_KEY]=$ri['key'];if($ri['cert'])$gg[\PDO::MYSQL_ATTR_SSL_CERT]=$ri['cert'];if($ri['ca'])$gg[\PDO::MYSQL_ATTR_SSL_CA]=$ri['ca'];if(isset($ri['verify']))$gg[\PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT]=$ri['verify'];}list($Nd,$Rg)=host_port($N);return$this->dsn("mysql:charset=utf8;host=$Nd".($Rg?(is_numeric($Rg)?";port=":";unix_socket=").$Rg:""),$V,$F,$gg);}function +set_charset($Xa){return$this->query("SET NAMES $Xa");}function +select_db($Pb){return$this->query("USE ".idf_escape($Pb));}function +query($H,$sj=false){$this->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,!$sj);return +parent::query($H,$sj);}}}class +Driver +extends +SqlDriver{static$extensions=array("MySQLi","MySQL","PDO_MySQL");static$jush="sql";var$unsigned=array("unsigned","zerofill","unsigned zerofill");var$operators=array("=","<",">","<=",">=","!=","LIKE","LIKE %%","REGEXP","IN","FIND_IN_SET","IS NULL","NOT LIKE","NOT REGEXP","NOT IN","IS NOT NULL","SQL");var$functions=array("char_length","date","from_unixtime","lower","round","floor","ceil","sec_to_time","time_to_sec","upper");var$grouping=array("avg","count","count distinct","group_concat","max","min","sum");static +function +connect($N,$V,$F){$g=parent::connect($N,$V,$F);if(is_string($g)){if(function_exists('iconv')&&!is_utf8($g)&&strlen($Hh=iconv("windows-1250","utf-8",$g))>strlen($g))$g=$Hh;return$g;}$g->set_charset(charset($g));$g->query("SET sql_quote_show_create = 1, autocommit = 1");$g->flavor=(preg_match('~MariaDB~',$g->server_info)?'maria':'mysql');add_driver(DRIVER,($g->flavor=='maria'?"MariaDB":"MySQL"));return$g;}function +__construct(Db$g){parent::__construct($g);$this->types=array(lang(27)=>array("tinyint"=>3,"smallint"=>5,"mediumint"=>8,"int"=>10,"bigint"=>20,"decimal"=>66,"float"=>12,"double"=>21),lang(28)=>array("date"=>10,"datetime"=>19,"timestamp"=>19,"time"=>10,"year"=>4),lang(29)=>array("char"=>255,"varchar"=>65535,"tinytext"=>255,"text"=>65535,"mediumtext"=>16777215,"longtext"=>4294967295),lang(85)=>array("enum"=>65535,"set"=>64),lang(30)=>array("bit"=>20,"binary"=>255,"varbinary"=>65535,"tinyblob"=>255,"blob"=>65535,"mediumblob"=>16777215,"longblob"=>4294967295),lang(32)=>array("geometry"=>0,"point"=>0,"linestring"=>0,"polygon"=>0,"multipoint"=>0,"multilinestring"=>0,"multipolygon"=>0,"geometrycollection"=>0),);$this->insertFunctions=array("char"=>"md5/sha1/password/encrypt/uuid","binary"=>"md5/sha1","date|time"=>"now",);$this->editFunctions=array(number_type()=>"+/-","date"=>"+ interval/- interval","time"=>"addtime/subtime","char|text"=>"concat",);if(min_version('5.7.8',10.2,$g))$this->types[lang(29)]["json"]=4294967295;if(min_version('',10.7,$g)){$this->types[lang(29)]["uuid"]=128;$this->insertFunctions['uuid']='uuid';}if(min_version(9,'',$g)){$this->types[lang(27)]["vector"]=16383;$this->insertFunctions['vector']='string_to_vector';}if(min_version(5.1,'',$g))$this->partitionBy=array("HASH","LINEAR HASH","KEY","LINEAR KEY","RANGE","LIST");if(min_version(5.7,10.2,$g))$this->generated=array("STORED","VIRTUAL");}function +unconvertFunction(array$n){return(preg_match("~binary~",$n["type"])?"UNHEX":($n["type"]=="bit"?doc_link(array('sql'=>'bit-value-literals.html'),"b''"):(preg_match("~geometry|point|linestring|polygon~",$n["type"])?"GeomFromText":"")));}function +insert($R,array$O){return($O?parent::insert($R,$O):queries("INSERT INTO ".table($R)." ()\nVALUES ()"));}function +insertUpdate($R,array$L,array$G){$e=array_keys(reset($L));$Xg="INSERT INTO ".table($R)." (".implode(", ",$e).") VALUES\n";$Nj=array();foreach($e +as$y)$Nj[$y]="$y = VALUES($y)";$yi="\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj);$Nj=array();$Re=0;foreach($L +as$O){$Y="(".implode(", ",$O).")";if($Nj&&(strlen($Xg)+$Re+strlen($Y)+strlen($yi)>1e6)){if(!queries($Xg.implode(",\n",$Nj).$yi))return +false;$Nj=array();$Re=0;}$Nj[]=$Y;$Re+=strlen($Y)+2;}return +queries($Xg.implode(",\n",$Nj).$yi);}function +slowQuery($H,$Ui){if(min_version('5.7.8','10.1.2')){if($this->conn->flavor=='maria')return"SET STATEMENT max_statement_time=$Ui FOR $H";elseif(preg_match('~^(SELECT\b)(.+)~is',$H,$A))return"$A[1] /*+ MAX_EXECUTION_TIME(".($Ui*1000).") */ $A[2]";}}function +convertSearch($v,array$X,array$n){return(preg_match('~char|text|enum|set~',$n["type"])&&!preg_match("~^utf8~",$n["collation"])&&preg_match('~[\x80-\xFF]~',$X['val'])?"CONVERT($v USING ".charset($this->conn).")":$v);}function +warnings(){$I=$this->conn->query("SHOW WARNINGS");if($I&&$I->num_rows){ob_start();print_select_result($I);return +ob_get_clean();}}function +tableHelp($B,$ze=false){$Ze=($this->conn->flavor=='maria');if(information_schema(DB))return +strtolower("information-schema-".($Ze?"$B-table/":str_replace("_","-",$B)."-table.html"));if(DB=="mysql")return($Ze?"mysql$B-table/":"system-schema.html");}function +partitionsInfo($R){$qd="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($R);$I=$this->conn->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $qd ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");$J=array();list($J["partition_by"],$J["partition"],$J["partitions"])=$I->fetch_row();$Hg=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $qd AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$J["partition_names"]=array_keys($Hg);$J["partition_values"]=array_values($Hg);return$J;}function +hasCStyleEscapes(){static$Sa;if($Sa===null){$pi=get_val("SHOW VARIABLES LIKE 'sql_mode'",1,$this->conn);$Sa=(strpos($pi,'NO_BACKSLASH_ESCAPES')===false);}return$Sa;}function +engines(){$J=array();foreach(get_rows("SHOW ENGINES")as$K){if(preg_match("~YES|DEFAULT~",$K["Support"]))$J[]=$K["Engine"];}return$J;}function +indexAlgorithms(array$Bi){return(preg_match('~^(MEMORY|NDB)$~',$Bi["Engine"])?array("HASH","BTREE"):array());}}function +idf_escape($v){return"`".str_replace("`","``",$v)."`";}function +table($v){return +idf_escape($v);}function +get_databases($id){$J=get_session("dbs");if($J===null){$H="SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";$J=($id?slow_query($H):get_vals($H));restart_session();set_session("dbs",$J);stop_session();}return$J;}function +limit($H,$Z,$z,$C=0,$Vh=" "){return" $H$Z".($z?$Vh."LIMIT $z".($C?" OFFSET $C":""):"");}function +limit1($R,$H,$Z,$Vh="\n"){return +limit($H,$Z,1,0,$Vh);}function +db_collation($k,array$lb){$J=null;$i=get_val("SHOW CREATE DATABASE ".idf_escape($k),1);if(preg_match('~ COLLATE ([^ ]+)~',$i,$A))$J=$A[1];elseif(preg_match('~ CHARACTER SET ([^ ]+)~',$i,$A))$J=$lb[$A[1]][-1];return$J;}function +logged_user(){return +get_val("SELECT USER()");}function +tables_list(){return +get_key_vals("SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME");}function +count_tables(array$j){$J=array();foreach($j +as$k)$J[$k]=count(get_vals("SHOW TABLES IN ".idf_escape($k)));return$J;}function +table_status($B="",$Uc=false){$J=array();foreach(get_rows($Uc?"SELECT TABLE_NAME AS Name, ENGINE AS Engine, TABLE_COMMENT AS Comment FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ".($B!=""?"AND TABLE_NAME = ".q($B):"ORDER BY Name"):"SHOW TABLE STATUS".($B!=""?" LIKE ".q(addcslashes($B,"%_\\")):""))as$K){if($K["Engine"]=="InnoDB")$K["Comment"]=preg_replace('~(?:(.+); )?InnoDB free: .*~','\1',$K["Comment"]);if(!isset($K["Engine"]))$K["Comment"]="";if($B!="")$K["Name"]=$B;$J[$K["Name"]]=$K;}return$J;}function +is_view(array$S){return$S["Engine"]===null;}function +fk_support(array$S){return +preg_match('~InnoDB|IBMDB2I'.(min_version(5.6)?'|NDB':'').'~i',$S["Engine"]);}function +fields($R){$Ze=(connection()->flavor=='maria');$J=array();foreach(get_rows("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ".q($R)." ORDER BY ORDINAL_POSITION")as$K){$n=$K["COLUMN_NAME"];$U=$K["COLUMN_TYPE"];$ud=$K["GENERATION_EXPRESSION"];$Rc=$K["EXTRA"];preg_match('~^(VIRTUAL|PERSISTENT|STORED)~',$Rc,$td);preg_match('~^([^( ]+)(?:\((.+)\))?( unsigned)?( zerofill)?$~',$U,$cf);$l=$K["COLUMN_DEFAULT"];if($l!=""){$ye=preg_match('~text|json~',$cf[1]);if(!$Ze&&$ye)$l=preg_replace("~^(_\w+)?('.*')$~",'\2',stripslashes($l));if($Ze||$ye){$l=($l=="NULL"?null:preg_replace_callback("~^'(.*)'$~",function($A){return +stripslashes(str_replace("''","'",$A[1]));},$l));}if(!$Ze&&preg_match('~binary~',$cf[1])&&preg_match('~^0x(\w*)$~',$l,$A))$l=pack("H*",$A[1]);}$J[$n]=array("field"=>$n,"full_type"=>$U,"type"=>$cf[1],"length"=>$cf[2],"unsigned"=>ltrim($cf[3].$cf[4]),"default"=>($td?($Ze?$ud:stripslashes($ud)):$l),"null"=>($K["IS_NULLABLE"]=="YES"),"auto_increment"=>($Rc=="auto_increment"),"on_update"=>(preg_match('~\bon update (\w+)~i',$Rc,$A)?$A[1]:""),"collation"=>$K["COLLATION_NAME"],"privileges"=>array_flip(explode(",","$K[PRIVILEGES],where,order")),"comment"=>$K["COLUMN_COMMENT"],"primary"=>($K["COLUMN_KEY"]=="PRI"),"generated"=>($td[1]=="PERSISTENT"?"STORED":$td[1]),);}return$J;}function +indexes($R,$h=null){$J=array();foreach(get_rows("SHOW INDEX FROM ".table($R),$h)as$K){$B=$K["Key_name"];$J[$B]["type"]=($B=="PRIMARY"?"PRIMARY":($K["Index_type"]=="FULLTEXT"?"FULLTEXT":($K["Non_unique"]?($K["Index_type"]=="SPATIAL"?"SPATIAL":"INDEX"):"UNIQUE")));$J[$B]["columns"][]=$K["Column_name"];$J[$B]["lengths"][]=($K["Index_type"]=="SPATIAL"?null:$K["Sub_part"]);$J[$B]["descs"][]=null;$J[$B]["algorithm"]=$K["Index_type"];}return$J;}function +foreign_keys($R){static$Lg='(?:`(?:[^`]|``)+`|"(?:[^"]|"")+")';$J=array();$Fb=get_val("SHOW CREATE TABLE ".table($R),1);if($Fb){preg_match_all("~CONSTRAINT ($Lg) FOREIGN KEY ?\\(((?:$Lg,? ?)+)\\) REFERENCES ($Lg)(?:\\.($Lg))? \\(((?:$Lg,? ?)+)\\)(?: ON DELETE (".driver()->onActions."))?(?: ON UPDATE (".driver()->onActions."))?~",$Fb,$df,PREG_SET_ORDER);foreach($df +as$A){preg_match_all("~$Lg~",$A[2],$ji);preg_match_all("~$Lg~",$A[5],$Mi);$J[idf_unescape($A[1])]=array("db"=>idf_unescape($A[4]!=""?$A[3]:$A[4]),"table"=>idf_unescape($A[4]!=""?$A[4]:$A[3]),"source"=>array_map('Adminer\idf_unescape',$ji[0]),"target"=>array_map('Adminer\idf_unescape',$Mi[0]),"on_delete"=>($A[6]?:"RESTRICT"),"on_update"=>($A[7]?:"RESTRICT"),);}}return$J;}function +view($B){return +array("select"=>preg_replace('~^(?:[^`]|`[^`]*`)*\s+AS\s+~isU','',get_val("SHOW CREATE VIEW ".table($B),1)));}function +collations(){$J=array();foreach(get_rows("SHOW COLLATION")as$K){if($K["Default"])$J[$K["Charset"]][-1]=$K["Collation"];else$J[$K["Charset"]][]=$K["Collation"];}ksort($J);foreach($J +as$y=>$X)sort($J[$y]);return$J;}function +information_schema($k){return($k=="information_schema")||(min_version(5.5)&&$k=="performance_schema");}function +error(){return +h(preg_replace('~^You have an error.*syntax to use~U',"Syntax error",connection()->error));}function +create_database($k,$c){return +queries("CREATE DATABASE ".idf_escape($k).($c?" COLLATE ".q($c):""));}function +drop_databases(array$j){$J=apply_queries("DROP DATABASE",$j,'Adminer\idf_escape');restart_session();set_session("dbs",null);return$J;}function +rename_database($B,$c){$J=false;if(create_database($B,$c)){$T=array();$Sj=array();foreach(tables_list()as$R=>$U){if($U=='VIEW')$Sj[]=$R;else$T[]=$R;}$J=(!$T&&!$Sj)||move_tables($T,$Sj,$B);drop_databases($J?array(DB):array());}return$J;}function +auto_increment(){$Ca=" PRIMARY KEY";if($_GET["create"]!=""&&$_POST["auto_increment_col"]){foreach(indexes($_GET["create"])as$w){if(in_array($_POST["fields"][$_POST["auto_increment_col"]]["orig"],$w["columns"],true)){$Ca="";break;}if($w["type"]=="PRIMARY")$Ca=" UNIQUE";}}return" AUTO_INCREMENT$Ca";}function +alter_table($R,$B,array$o,array$kd,$qb,$yc,$c,$Ba,$E){$b=array();foreach($o +as$n){if($n[1]){$l=$n[1][3];if(preg_match('~ GENERATED~',$l)){$n[1][3]=(connection()->flavor=='maria'?"":$n[1][2]);$n[1][2]=$l;}$b[]=($R!=""?($n[0]!=""?"CHANGE ".idf_escape($n[0]):"ADD"):" ")." ".implode($n[1]).($R!=""?$n[2]:"");}else$b[]="DROP ".idf_escape($n[0]);}$b=array_merge($b,$kd);$P=($qb!==null?" COMMENT=".q($qb):"").($yc?" ENGINE=".q($yc):"").($c?" COLLATE ".q($c):"").($Ba!=""?" AUTO_INCREMENT=$Ba":"");if($E){$Hg=array();if($E["partition_by"]=='RANGE'||$E["partition_by"]=='LIST'){foreach($E["partition_names"]as$y=>$X){$Y=$E["partition_values"][$y];$Hg[]="\n PARTITION ".idf_escape($X)." VALUES ".($E["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$P +.="\nPARTITION BY $E[partition_by]($E[partition])";if($Hg)$P +.=" (".implode(",",$Hg)."\n)";elseif($E["partitions"])$P +.=" PARTITIONS ".(+$E["partitions"]);}elseif($E===null)$P +.="\nREMOVE PARTITIONING";if($R=="")return +queries("CREATE TABLE ".table($B)." (\n".implode(",\n",$b)."\n)$P");if($R!=$B)$b[]="RENAME TO ".table($B);if($P)$b[]=ltrim($P);return($b?queries("ALTER TABLE ".table($R)."\n".implode(",\n",$b)):true);}function +alter_indexes($R,$b){$Wa=array();foreach($b +as$X)$Wa[]=($X[2]=="DROP"?"\nDROP INDEX ".idf_escape($X[1]):"\nADD $X[0] ".($X[0]=="PRIMARY"?"KEY ":"").($X[1]!=""?idf_escape($X[1])." ":"")."(".implode(", ",$X[2]).")");return +queries("ALTER TABLE ".table($R).implode(",",$Wa));}function +truncate_tables(array$T){return +apply_queries("TRUNCATE TABLE",$T);}function +drop_views(array$Sj){return +queries("DROP VIEW ".implode(", ",array_map('Adminer\table',$Sj)));}function +drop_tables(array$T){return +queries("DROP TABLE ".implode(", ",array_map('Adminer\table',$T)));}function +move_tables(array$T,array$Sj,$Mi){$wh=array();foreach($T +as$R)$wh[]=table($R)." TO ".idf_escape($Mi).".".table($R);if(!$wh||queries("RENAME TABLE ".implode(", ",$wh))){$Yb=array();foreach($Sj +as$R)$Yb[table($R)]=view($R);connection()->select_db($Mi);$k=idf_escape(DB);foreach($Yb +as$B=>$Rj){if(!queries("CREATE VIEW $B AS ".str_replace(" $k."," ",$Rj["select"]))||!queries("DROP VIEW $k.$B"))return +false;}return +true;}return +false;}function +copy_tables(array$T,array$Sj,$Mi){queries("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'");foreach($T +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));if(($_POST["overwrite"]&&!queries("\nDROP TABLE IF EXISTS $B"))||!queries("CREATE TABLE $B LIKE ".table($R))||!queries("INSERT INTO $B SELECT * FROM ".table($R)))return +false;foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K){$lj=$K["Trigger"];if(!queries("CREATE TRIGGER ".($Mi==DB?idf_escape("copy_$lj"):idf_escape($Mi).".".idf_escape($lj))." $K[Timing] $K[Event] ON $B FOR EACH ROW\n$K[Statement];"))return +false;}}foreach($Sj +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));$Rj=view($R);if(($_POST["overwrite"]&&!queries("DROP VIEW IF EXISTS $B"))||!queries("CREATE VIEW $B AS $Rj[select]"))return +false;}return +true;}function +trigger($B,$R){if($B=="")return +array();$L=get_rows("SHOW TRIGGERS WHERE `Trigger` = ".q($B));return +reset($L);}function +triggers($R){$J=array();foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K)$J[$K["Trigger"]]=array($K["Timing"],$K["Event"]);return$J;}function +trigger_options(){return +array("Timing"=>array("BEFORE","AFTER"),"Event"=>array("INSERT","UPDATE","DELETE"),"Type"=>array("FOR EACH ROW"),);}function +routine($B,$U){$o=get_rows("SELECT + PARAMETER_NAME field, + DATA_TYPE type, + CHARACTER_MAXIMUM_LENGTH length, + REGEXP_REPLACE(DTD_IDENTIFIER, '^[^ ]+ ', '') `unsigned`, + 1 `null`, + DTD_IDENTIFIER full_type, + PARAMETER_MODE `inout`, + CHARACTER_SET_NAME collation +FROM information_schema.PARAMETERS +WHERE SPECIFIC_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND SPECIFIC_NAME = ".q($B)." +ORDER BY ORDINAL_POSITION");$J=connection()->query("SELECT ROUTINE_COMMENT comment, ROUTINE_DEFINITION definition, 'SQL' language +FROM information_schema.ROUTINES +WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND ROUTINE_NAME = ".q($B))->fetch_assoc();if($o&&$o[0]['field']=='')$J['returns']=array_shift($o);$J['fields']=$o;return$J;}function +routines(){return +get_rows("SELECT SPECIFIC_NAME, ROUTINE_NAME, ROUTINE_TYPE, DTD_IDENTIFIER FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE()");}function +routine_languages(){return +array();}function +routine_id($B,array$K){return +idf_escape($B);}function +last_id($I){return +get_val("SELECT LAST_INSERT_ID()");}function +explain(Db$g,$H){return$g->query("EXPLAIN ".(min_version(5.1)&&!min_version(5.7)?"PARTITIONS ":"").$H);}function +found_rows(array$S,array$Z){return($Z||$S["Engine"]!="InnoDB"?null:$S["Rows"]);}function +create_sql($R,$Ba,$wi){$J=get_val("SHOW CREATE TABLE ".table($R),1);if(!$Ba)$J=preg_replace('~ AUTO_INCREMENT=\d+~','',$J);return$J;}function +truncate_sql($R){return"TRUNCATE ".table($R);}function +use_sql($Pb,$wi=""){$B=idf_escape($Pb);$J="";if(preg_match('~CREATE~',$wi)&&($i=get_val("SHOW CREATE DATABASE $B",1))){set_utf8mb4($i);if($wi=="DROP+CREATE")$J="DROP DATABASE IF EXISTS $B;\n";$J +.="$i;\n";}return$J."USE $B";}function +trigger_sql($R){$J="";foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")),null,"-- ")as$K)$J +.="\nCREATE TRIGGER ".idf_escape($K["Trigger"])." $K[Timing] $K[Event] ON ".table($K["Table"])." FOR EACH ROW\n$K[Statement];;\n";return$J;}function +show_variables(){return +get_rows("SHOW VARIABLES");}function +show_status(){return +get_rows("SHOW STATUS");}function +process_list(){return +get_rows("SHOW FULL PROCESSLIST");}function +convert_field(array$n){if(preg_match("~binary~",$n["type"]))return"HEX(".idf_escape($n["field"]).")";if($n["type"]=="bit")return"BIN(".idf_escape($n["field"])." + 0)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"]))return(min_version(8)?"ST_":"")."AsWKT(".idf_escape($n["field"]).")";}function +unconvert_field(array$n,$J){if(preg_match("~binary~",$n["type"]))$J="UNHEX($J)";if($n["type"]=="bit")$J="CONVERT(b$J, UNSIGNED)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"])){$Xg=(min_version(8)?"ST_":"");$J=$Xg."GeomFromText($J, $Xg"."SRID($n[field]))";}return$J;}function +support($Vc){return +preg_match('~^(comment|columns|copy|database|drop_col|dump|indexes|kill|privileges|move_col|procedure|processlist|routine|sql|status|table|trigger|variables|view'.(min_version(5.1)?'|event':'').(min_version(8)?'|descidx':'').(min_version('8.0.16','10.2.1')?'|check':'').')$~',$Vc);}function +kill_process($u){return +queries("KILL ".number($u));}function +connection_id(){return"SELECT CONNECTION_ID()";}function +max_connections(){return +get_val("SELECT @@max_connections");}function +types(){return +array();}function +type_values($u){return"";}function +schemas(){return +array();}function +get_schema(){return"";}function +set_schema($Jh,$h=null){return +true;}}define('Adminer\JUSH',Driver::$jush);define('Adminer\SERVER',"".$_GET[DRIVER]);define('Adminer\DB',"$_GET[db]");define('Adminer\ME',preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').($_GET["ext"]?"ext=".urlencode($_GET["ext"]).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));function +page_header($Wi,$m="",$Oa=array(),$Xi=""){page_headers();if(is_ajax()&&$m){page_messages($m);exit;}if(!ob_get_level())ob_start('ob_gzhandler',4096);$Yi=$Wi.($Xi!=""?": $Xi":"");$Zi=strip_tags($Yi.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".adminer()->name());echo' + -',$pg,' - -',script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=4.8.1");if($b->head()){echo' - -';foreach($b->css()as$eb){echo' -';}}echo' - -';$o=get_temp_dir()."/adminer.version";if(!$_COOKIE["adminer_version"]&&function_exists('openssl_verify')&&file_exists($o)&&filemtime($o)+86400>time()){$Xg=unserialize(file_get_contents($o));$Ve="-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwqWOVuF5uw7/+Z70djoK -RlHIZFZPO0uYRezq90+7Amk+FDNd7KkL5eDve+vHRJBLAszF/7XKXe11xwliIsFs -DFWQlsABVZB3oisKCBEuI71J4kPH8dKGEWR9jDHFw3cWmoH3PmqImX6FISWbG3B8 -h7FIx3jEaw5ckVPVTeo5JRm/1DZzJxjyDenXvBQ/6o9DgZKeNDgxwKzH+sw9/YCO -jHnq1cFpOIISzARlrHMa/43YfeNRAm/tsBXjSxembBPo7aQZLAWHmaj5+K19H10B -nCpz9Y++cipkVEiKRGih4ZEvjoFysEOdRLj6WiD/uUNky4xGeA6LaJqh5XpkFkcQ -fQIDAQAB ------END PUBLIC KEY----- -";if(openssl_verify($Xg["version"],base64_decode($Xg["signature"]),$Ve)==1)$_COOKIE["adminer_version"]=$Xg["version"];}echo' -mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick',(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '$da', '".js_escape(ME)."', '".get_token()."')");?>}); -document.body.className = document.body.className.replace(/ nojs/, ' js'); -var offlineMessage = ' - - -',script("mixin(qs('#help'), {onmouseover: function () { helpOpen = 1; }, onmouseout: helpMouseout});"),' -
    -';if($Ba!==null){$A=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $og

    \n","\n";restart_session();page_messages($l);$i=&get_session("dbs");if(DB!=""&&$i&&!in_array(DB,$i,true))$i=null;stop_session();define("PAGE_HEADER",1);}function -page_headers(){global$b;header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: SAMEORIGIN");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach($b->csp()as$db){$Dc=array();foreach($db -as$z=>$X)$Dc[]="$z $X";header("Content-Security-Policy: ".implode("; ",$Dc));}$b->headers();}function + +',$Zi,' + +';$Jb=adminer()->css();if(is_int(key($Jb)))$Jb=array_fill_keys($Jb,'light');$Fd=in_array('light',$Jb)||in_array('',$Jb);$Dd=in_array('dark',$Jb)||in_array('',$Jb);$Mb=($Fd?($Dd?null:false):($Dd?:null));$nf=" media='(prefers-color-scheme: dark)'";if($Mb!==false)echo"\n";echo"\n",script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=5.4.2");if(adminer()->head($Mb))echo"\n","\n";foreach($Jb +as$Dj=>$yf){$_a=($yf=='dark'&&!$Mb?$nf:($yf=='light'&&$Dd?" media='(prefers-color-scheme: light)'":""));echo"\n";}echo"\n\n";$p=get_temp_dir()."/adminer.version";echo +script("mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick".(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '".VERSION."')")."}); +document.body.classList.replace('nojs', 'js'); +const offlineMessage = '".js_escape(lang(87))."'; +const thousandsSeparator = '".js_escape(lang(4))."';"),"\n",script("mixin(qs('#help'), {onmouseover: () => { helpOpen = 1; }, onmouseout: helpMouseout});"),"
    \n","".icon("move","","menu","")."".script("qs('#menuopen').onclick = event => { qs('#foot').classList.toggle('foot'); event.stopPropagation(); }");if($Oa!==null){$_=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $Yi

    \n","\n";restart_session();page_messages($m);$j=&get_session("dbs");if(DB!=""&&$j&&!in_array(DB,$j,true))$j=null;stop_session();define('Adminer\PAGE_HEADER',1);}function +page_headers(){header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: deny");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach(adminer()->csp(csp())as$Ib){$Hd=array();foreach($Ib +as$y=>$X)$Hd[]="$y $X";header("Content-Security-Policy: ".implode("; ",$Hd));}adminer()->headers();}function csp(){return -array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self'","frame-src"=>"https://www.adminer.org","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function -get_nonce(){static$Nd;if(!$Nd)$Nd=base64_encode(rand_string());return$Nd;}function -page_messages($l){$Lg=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$Ed=$_SESSION["messages"][$Lg];if($Ed){echo"
    ".implode("
    \n
    ",$Ed)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Lg]);}if($l)echo"
    $l
    \n";}function -page_footer($Hd=""){global$b,$U;echo'
    - -';if($Hd!="auth"){echo'
    +array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self' https://www.adminer.org","frame-src"=>"'none'","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function +get_nonce(){static$Kf;if(!$Kf)$Kf=base64_encode(rand_string());return$Kf;}function +page_messages($m){$Cj=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$uf=idx($_SESSION["messages"],$Cj);if($uf){echo"
    ".implode("
    \n
    ",$uf)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Cj]);}if($m)echo"
    $m
    \n";if(adminer()->error)echo"
    ".adminer()->error."
    \n";}function +page_footer($xf=""){echo"
    \n\n\n\n",script("setupSubmitHighlight(document);");}function +int32($Cf){while($Cf>=2147483648)$Cf-=4294967296;while($Cf<=-2147483649)$Cf+=4294967296;return(int)$Cf;}function +long2str(array$W,$Uj){$Hh='';foreach($W +as$X)$Hh +.=pack('V',$X);if($Uj)return +substr($Hh,0,end($W));return$Hh;}function +str2long($Hh,$Uj){$W=array_values(unpack('V*',str_pad($Hh,4*ceil(strlen($Hh)/4),"\0")));if($Uj)$W[]=strlen($Hh);return$W;}function +xxtea_mx($bk,$ak,$zi,$Ce){return +int32((($bk>>5&0x7FFFFFF)^$ak<<2)+(($ak>>3&0x1FFFFFFF)^$bk<<4))^int32(($zi^$ak)+($Ce^$bk));}function +encrypt_string($ui,$y){if($ui=="")return"";$y=array_values(unpack("V*",pack("H*",md5($y))));$W=str2long($ui,true);$Cf=count($W)-1;$bk=$W[$Cf];$ak=$W[0];$hh=floor(6+52/($Cf+1));$zi=0;while($hh-->0){$zi=int32($zi+0x9E3779B9);$pc=$zi>>2&3;for($xg=0;$xg<$Cf;$xg++){$ak=$W[$xg+1];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$xg]+$Bf);$W[$xg]=$bk;}$ak=$W[0];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$Cf]+$Bf);$W[$Cf]=$bk;}return long2str($W,false);}function -decrypt_string($Nf,$z){if($Nf=="")return"";if(!$z)return -false;$z=array_values(unpack("V*",pack("H*",md5($z))));$W=str2long($Nf,false);$E=count($W)-1;$ih=$W[$E];$hh=$W[0];$H=floor(6+52/($E+1));$Sf=int32($H*0x9E3779B9);while($Sf){$Fb=$Sf>>2&3;for($re=$E;$re>0;$re--){$ih=$W[$re-1];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[$re]-$Jd);$W[$re]=$hh;}$ih=$W[$E];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[0]-$Jd);$W[0]=$hh;$Sf=int32($Sf-0x9E3779B9);}return -long2str($W,true);}$f='';$Cc=$_SESSION["token"];if(!$Cc)$_SESSION["token"]=rand(1,1e6);$U=get_token();$De=array();if($_COOKIE["adminer_permanent"]){foreach(explode(" ",$_COOKIE["adminer_permanent"])as$X){list($z)=explode(":",$X);$De[$z]=$X;}}function -add_invalid_login(){global$b;$r=file_open_lock(get_temp_dir()."/adminer.invalid");if(!$r)return;$Uc=unserialize(stream_get_contents($r));$jg=time();if($Uc){foreach($Uc -as$Vc=>$X){if($X[0]<$jg)unset($Uc[$Vc]);}}$Tc=&$Uc[$b->bruteForceKey()];if(!$Tc)$Tc=array($jg+30*60,0);$Tc[1]++;file_write_unlock($r,serialize($Uc));}function -check_invalid_login(){global$b;$Uc=unserialize(@file_get_contents(get_temp_dir()."/adminer.invalid"));$Tc=($Uc?$Uc[$b->bruteForceKey()]:array());$Md=($Tc[1]>29?$Tc[0]-time():0);if($Md>0)auth_error(lang(array('Zu viele erfolglose Login-Versuche. Bitte probieren Sie es in %d Minute noch einmal.','Zu viele erfolglose Login-Versuche. Bitte probieren Sie es in %d Minuten noch einmal.'),ceil($Md/60)));}$sa=$_POST["auth"];if($sa){session_regenerate_id();$Wg=$sa["driver"];$O=$sa["server"];$Rg=$sa["username"];$_e=(string)$sa["password"];$j=$sa["db"];set_password($Wg,$O,$Rg,$_e);$_SESSION["db"][$Wg][$O][$Rg][$j]=true;if($sa["permanent"]){$z=base64_encode($Wg)."-".base64_encode($O)."-".base64_encode($Rg)."-".base64_encode($j);$Re=$b->permanentLogin(true);$De[$z]="$z:".base64_encode($Re?encrypt_string($_e,$Re):"");cookie("adminer_permanent",implode(" ",$De));}if(count($_POST)==1||DRIVER!=$Wg||SERVER!=$O||$_GET["username"]!==$Rg||DB!=$j)redirect(auth_url($Wg,$O,$Rg,$j));}elseif($_POST["logout"]&&(!$Cc||verify_token())){foreach(array("pwds","db","dbs","queries")as$z)set_session($z,null);unset_permanent();redirect(substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1),'Abmeldung erfolgreich.'.' '.'Danke, dass Sie Adminer genutzt haben. Spenden willkommen!');}elseif($De&&!$_SESSION["pwds"]){session_regenerate_id();$Re=$b->permanentLogin();foreach($De -as$z=>$X){list(,$Ia)=explode(":",$X);list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));set_password($Wg,$O,$Rg,decrypt_string(base64_decode($Ia),$Re));$_SESSION["db"][$Wg][$O][$Rg][$j]=true;}}function -unset_permanent(){global$De;foreach($De -as$z=>$X){list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));if($Wg==DRIVER&&$O==SERVER&&$Rg==$_GET["username"]&&$j==DB)unset($De[$z]);}cookie("adminer_permanent",implode(" ",$De));}function -auth_error($l){global$b,$Cc;$_f=session_name();if(isset($_GET["username"])){header("HTTP/1.1 403 Forbidden");if(($_COOKIE[$_f]||$_GET[$_f])&&!$Cc)$l='Sitzungsdauer abgelaufen, bitte erneut anmelden.';else{restart_session();add_invalid_login();$_e=get_password();if($_e!==null){if($_e===false)$l.=($l?'
    ':'').sprintf('Das Master-Passwort ist abgelaufen. Implementieren Sie die %s Methode, um es permanent zu machen.',target_blank(),'permanentLogin()');set_password(DRIVER,SERVER,$_GET["username"],null);}unset_permanent();}}if(!$_COOKIE[$_f]&&$_GET[$_f]&&ini_bool("session.use_only_cookies"))$l='Unterstüzung für PHP-Sessions muss aktiviert sein.';$ue=session_get_cookie_params();cookie("adminer_key",($_COOKIE["adminer_key"]?$_COOKIE["adminer_key"]:rand_string()),$ue["lifetime"]);page_header('Login',$l,null);echo"
    \n","
    ";if(hidden_fields($_POST,array("auth")))echo"

    ".'The action will be performed after successful login with the same credentials.'."\n";echo"

    \n";$b->loginForm();echo"
    \n";page_footer("auth");exit;}if(isset($_GET["username"])&&!class_exists("Min_DB")){unset($_SESSION["pwds"][DRIVER]);unset_permanent();page_header('Keine Erweiterungen installiert',sprintf('Keine der unterstützten PHP-Erweiterungen (%s) ist vorhanden.',implode(", ",$Le)),false);page_footer("auth");exit;}stop_session(true);if(isset($_GET["username"])&&is_string(get_password())){list($Hc,$He)=explode(":",SERVER,2);if(preg_match('~^\s*([-+]?\d+)~',$He,$C)&&($C[1]<1024||$C[1]>65535))auth_error('Connecting to privileged ports is not allowed.');check_invalid_login();$f=connect();$k=new -Min_Driver($f);}$rd=null;if(!is_object($f)||($rd=$b->login($_GET["username"],get_password()))!==true){$l=(is_string($f)?h($f):(is_string($rd)?$rd:'Ungültige Anmelde-Informationen.'));auth_error($l.(preg_match('~^ | $~',get_password())?'
    '.'There is a space in the input password which might be the cause.':''));}if($_POST["logout"]&&$Cc&&!verify_token()){page_header('Abmelden','CSRF Token ungültig. Bitte die Formulardaten erneut abschicken.');page_footer("db");exit;}if($sa&&$_POST["token"])$_POST["token"]=$U;$l='';if($_POST){if(!verify_token()){$Pc="max_input_vars";$_d=ini_get($Pc);if(extension_loaded("suhosin")){foreach(array("suhosin.request.max_vars","suhosin.post.max_vars")as$z){$X=ini_get($z);if($X&&(!$_d||$X<$_d)){$Pc=$z;$_d=$X;}}}$l=(!$_POST["token"]&&$_d?sprintf('Die maximal erlaubte Anzahl der Felder ist überschritten. Bitte %s erhöhen.',"'$Pc'"):'CSRF Token ungültig. Bitte die Formulardaten erneut abschicken.'.' '.'Wenn Sie diese Anfrage nicht von Adminer gesendet haben, schließen Sie diese Seite.');}}elseif($_SERVER["REQUEST_METHOD"]=="POST"){$l=sprintf('POST-Daten sind zu groß. Reduzieren Sie die Größe oder vergrößern Sie den Wert %s in der Konfiguration.',"'post_max_size'");if(isset($_GET["sql"]))$l.=' '.'Sie können eine große SQL-Datei per FTP hochladen und dann vom Server importieren.';}function -select($J,$g=null,$ie=array(),$_=0){global$y;$qd=array();$x=array();$e=array();$_a=array();$Cg=array();$K=array();odd('');for($u=0;(!$_||$u<$_)&&($L=$J->fetch_row());$u++){if(!$u){echo"
    \n","\n","";for($Zc=0;$Zcfetch_field();$F=$m->name;$he=$m->orgtable;$ge=$m->orgname;$K[$m->table]=$he;if($ie&&$y=="sql")$qd[$Zc]=($F=="table"?"table=":($F=="possible_keys"?"indexes=":null));elseif($he!=""){if(!isset($x[$he])){$x[$he]=array();foreach(indexes($he,$g)as$w){if($w["type"]=="PRIMARY"){$x[$he]=array_flip($w["columns"]);break;}}$e[$he]=$x[$he];}if(isset($e[$he][$ge])){unset($e[$he][$ge]);$x[$he][$ge]=$Zc;$qd[$Zc]=$he;}}if($m->charsetnr==63)$_a[$Zc]=true;$Cg[$Zc]=$m->type;echo"name!=$ge?" title='".h(($he!=""?"$he.":"").$ge)."'":"").">".h($F).($ie?'':"");}echo"\n";}echo"";foreach($L -as$z=>$X){$A="";if(isset($qd[$z])&&!$e[$qd[$z]]){if($ie&&$y=="sql"){$R=$L[array_search("table=",$qd)];$A=ME.$qd[$z].urlencode($ie[$R]!=""?$ie[$R]:$R);}else{$A=ME."edit=".urlencode($qd[$z]);foreach($x[$qd[$z]]as$Ma=>$Zc)$A.="&where".urlencode("[".bracket_escape($Ma)."]")."=".urlencode($L[$Zc]);}}elseif(is_url($X))$A=$X;if($X===null)$X="NULL";elseif($_a[$z]&&!is_utf8($X))$X="".lang(array('%d Byte','%d Bytes'),strlen($X))."";else{$X=h($X);if($Cg[$z]==254)$X="$X";}if($A)$X="$X";echo"
    $X";}}echo($u?"
    \n
    ":"

    ".'Keine Datensätze.')."\n";return$K;}function -referencable_primary($vf){$K=array();foreach(table_status('',true)as$Wf=>$R){if($Wf!=$vf&&fk_support($R)){foreach(fields($Wf)as$m){if($m["primary"]){if($K[$Wf]){unset($K[$Wf]);break;}$K[$Wf]=$m;}}}}return$K;}function -adminer_settings(){parse_str($_COOKIE["adminer_settings"],$Bf);return$Bf;}function -adminer_setting($z){$Bf=adminer_settings();return$Bf[$z];}function -set_adminer_settings($Bf){return -cookie("adminer_settings",http_build_query($Bf+adminer_settings()));}function -textarea($F,$Y,$M=10,$Qa=80){global$y;echo"";}function -edit_type($z,$m,$Pa,$q=array(),$ec=array()){global$Of,$Cg,$Jg,$Wd;$V=$m["type"];echo'',"',($Jg?"':''),(isset($m['on_update'])?"':''),($q?" ":" ");}function -process_length($nd){global$Qb;return(preg_match("~^\\s*\\(?\\s*$Qb(?:\\s*,\\s*$Qb)*+\\s*\\)?\\s*\$~",$nd)&&preg_match_all("~$Qb~",$nd,$ud)?"(".implode(",",$ud[0]).")":preg_replace('~^[0-9].*~','(\0)',preg_replace('~[^-0-9,+()[\]]~','',$nd)));}function -process_type($m,$Na="COLLATE"){global$Jg;return" $m[type]".process_length($m["length"]).(preg_match(number_type(),$m["type"])&&in_array($m["unsigned"],$Jg)?" $m[unsigned]":"").(preg_match('~char|text|enum|set~',$m["type"])&&$m["collation"]?" $Na ".q($m["collation"]):"");}function -process_field($m,$Bg){return -array(idf_escape(trim($m["field"])),process_type($Bg),($m["null"]?" NULL":" NOT NULL"),default_value($m),(preg_match('~timestamp|datetime~',$m["type"])&&$m["on_update"]?" ON UPDATE $m[on_update]":""),(support("comment")&&$m["comment"]!=""?" COMMENT ".q($m["comment"]):""),($m["auto_increment"]?auto_increment():null),);}function -default_value($m){$ob=$m["default"];return($ob===null?"":" DEFAULT ".(preg_match('~char|binary|text|enum|set~',$m["type"])||preg_match('~^(?![a-z])~i',$ob)?q($ob):$ob));}function -type_class($V){foreach(array('char'=>'text','date'=>'time|year','binary'=>'blob','enum'=>'set',)as$z=>$X){if(preg_match("~$z|$X~",$V))return" class='$z'";}}function -edit_fields($n,$Pa,$V="TABLE",$q=array()){global$Qc;$n=array_values($n);$pb=(($_POST?$_POST["defaults"]:adminer_setting("defaults"))?"":" class='hidden'");$Ua=(($_POST?$_POST["comments"]:adminer_setting("comments"))?"":" class='hidden'");echo' -';if($V=="PROCEDURE"){echo'';}echo'',($V=="TABLE"?'Spaltenname':'Name des Parameters'),'Typ',script("qs('#enum-edit').onblur = editingLengthBlur;"),'Länge -','Optionen';if($V=="TABLE"){echo'NULL -AI',doc_link(array('sqlite'=>"autoinc.html",)),'Vorgabewert festlegen -',(support("comment")?"".'Kommentar':"");}echo'',"".script("row_count = ".count($n).";"),' - -',script("mixin(qsl('tbody'), {onclick: editingClick, onkeydown: editingKeydown, oninput: editingInput});");foreach($n -as$u=>$m){$u++;$je=$m[($_POST?"orig":"field")];$wb=(isset($_POST["add"][$u-1])||(isset($m["field"])&&!$_POST["drop_col"][$u]))&&(support("drop_col")||$je=="");echo' -',($V=="PROCEDURE"?"".html_select("fields[$u][inout]",explode("|",$Qc),$m["inout"]):""),'';if($wb){echo'';}echo'';edit_type("fields[$u]",$m,$Pa,$q);if($V=="TABLE"){echo'',checkbox("fields[$u][null]",1,$m["null"],"","","block","label-null"),'',checkbox("fields[$u][has_default]",1,$m["has_default"],"","","","label-default"),'',(support("comment")?"":"");}echo"",(support("move_col")?" "." "." ":""),($je==""||support("drop_col")?"":"");}}function -process_fields(&$n){$Sd=0;if($_POST["up"]){$hd=0;foreach($n -as$z=>$m){if(key($_POST["up"])==$z){unset($n[$z]);array_splice($n,$hd,0,array($m));break;}if(isset($m["field"]))$hd=$Sd;$Sd++;}}elseif($_POST["down"]){$rc=false;foreach($n -as$z=>$m){if(isset($m["field"])&&$rc){unset($n[key($_POST["down"])]);array_splice($n,$Sd,0,array($rc));break;}if(key($_POST["down"])==$z)$rc=$m;$Sd++;}}elseif($_POST["add"]){$n=array_values($n);array_splice($n,key($_POST["add"]),0,array(array()));}elseif(!$_POST["drop_col"])return +select_input($_a,array$gg,$Y="",$ag="",$Og=""){$Li=($gg?"select":"input");return"<$Li$_a".($gg?">

    ".sprintf('Version %s: %s mit PHP-Erweiterung %s',$zb[DRIVER],"".h($f->server_info)."","$f->extension")."\n","

    ".sprintf('Angemeldet als: %s',"".h(logged_user())."")."\n";$i=$b->databases();if($i){$rf=support("scheme");$Pa=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$i=($_GET["dbsize"]?count_tables($i):array_flip($i));foreach($i -as$j=>$T){$mf=h(ME)."db=".urlencode($j);$v=h("Db-".$j);echo"".(support("database")?"
    ":"")."".'Datenbank'." - ".'Aktualisieren'.""."".'Kollation'."".'Tabellen'."".'Größe'." - ".'kalkulieren'."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$j,in_array($j,(array)$_POST["db"]),"","","",$v):""),"".h($j)."";$Oa=h(db_collation($j,$Pa));echo"".(support("database")?"$Oa":$Oa),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($j):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),"\n","
    \n",script("tableCheck();");}}page_footer("db");}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?$f->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}connect_error();exit;}$Wd="RESTRICT|NO ACTION|CASCADE|SET NULL|SET DEFAULT";class -TmpFile{var$handler;var$size;function +normalize_enum(array$A){$X=$A[0];return"'".str_replace("'","''",addcslashes(stripcslashes(str_replace($X[0].$X[0],$X[0],substr($X,1,-1))),'\\'))."'";}function +grant($vd,array$eh,$e,$Xf){if(!$eh)return +true;if($eh==array("ALL PRIVILEGES","GRANT OPTION"))return($vd=="GRANT"?queries("$vd ALL PRIVILEGES$Xf WITH GRANT OPTION"):queries("$vd ALL PRIVILEGES$Xf")&&queries("$vd GRANT OPTION$Xf"));return +queries("$vd ".preg_replace('~(GRANT OPTION)\([^)]*\)~','\1',implode("$e, ",$eh).$e).$Xf);}function +drop_create($jc,$i,$lc,$Pi,$nc,$We,$tf,$rf,$sf,$Uf,$Gf){if($_POST["drop"])query_redirect($jc,$We,$tf);elseif($Uf=="")query_redirect($i,$We,$sf);elseif($Uf!=$Gf){$Gb=queries($i);queries_redirect($We,$rf,$Gb&&queries($jc));if($Gb)queries($lc);}else +queries_redirect($We,$rf,queries($Pi)&&queries($nc)&&queries($jc)&&queries($i));}function +create_trigger($Xf,array$K){$Vi=" $K[Timing] $K[Event]".(preg_match('~ OF~',$K["Event"])?" $K[Of]":"");return"CREATE TRIGGER ".idf_escape($K["Trigger"]).(JUSH=="mssql"?$Xf.$Vi:$Vi.$Xf).rtrim(" $K[Type]\n$K[Statement]",";").";";}function +create_routine($Dh,array$K){$O=array();$o=(array)$K["fields"];ksort($o);foreach($o +as$n){if($n["field"]!="")$O[]=(preg_match("~^(".driver()->inout.")\$~",$n["inout"])?"$n[inout] ":"").idf_escape($n["field"]).process_type($n,"CHARACTER SET");}$Xb=rtrim($K["definition"],";");return"CREATE $Dh ".idf_escape(trim($K["name"]))." (".implode(", ",$O).")".($Dh=="FUNCTION"?" RETURNS".process_type($K["returns"],"CHARACTER SET"):"").($K["language"]?" LANGUAGE $K[language]":"").(JUSH=="pgsql"?" AS ".q($Xb):"\n$Xb;");}function +remove_definer($H){return +preg_replace('~^([A-Z =]+) DEFINER=`'.preg_replace('~@(.*)~','`@`(%|\1)',logged_user()).'`~','\1',$H);}function +format_foreign_key(array$q){$k=$q["db"];$Lf=$q["ns"];return" FOREIGN KEY (".implode(", ",array_map('Adminer\idf_escape',$q["source"])).") REFERENCES ".($k!=""&&$k!=$_GET["db"]?idf_escape($k).".":"").($Lf!=""&&$Lf!=$_GET["ns"]?idf_escape($Lf).".":"").idf_escape($q["table"])." (".implode(", ",array_map('Adminer\idf_escape',$q["target"])).")".(preg_match("~^(".driver()->onActions.")\$~",$q["on_delete"])?" ON DELETE $q[on_delete]":"").(preg_match("~^(".driver()->onActions.")\$~",$q["on_update"])?" ON UPDATE $q[on_update]":"").($q["deferrable"]?" $q[deferrable]":"");}function +tar_file($p,$aj){$J=pack("a100a8a8a8a12a12",$p,644,0,0,decoct($aj->size),decoct(time()));$db=8*32;for($t=0;$tsend();echo +str_repeat("\0",511-($aj->size+511)%512);}function +doc_link(array$Kg,$Qi="?"){$Zh=connection()->server_info;$Qj=preg_replace('~^(\d\.?\d).*~s','\1',$Zh);$Ej=array('sql'=>"https://dev.mysql.com/doc/refman/$Qj/en/",'sqlite'=>"https://www.sqlite.org/",'pgsql'=>"https://www.postgresql.org/docs/".(connection()->flavor=='cockroach'?"current":$Qj)."/",'mssql'=>"https://learn.microsoft.com/en-us/sql/",'oracle'=>"https://www.oracle.com/pls/topic/lookup?ctx=db".preg_replace('~^.* (\d+)\.(\d+)\.\d+\.\d+\.\d+.*~s','\1\2',$Zh)."&id=",);if(connection()->flavor=='maria'){$Ej['sql']="https://mariadb.com/kb/en/";$Kg['sql']=(isset($Kg['mariadb'])?$Kg['mariadb']:str_replace(".html","/",$Kg['sql']));}return($Kg[JUSH]?"$Qi":"");}function +db_size($k){if(!connection()->select_db($k))return"?";$J=0;foreach(table_status()as$S)$J+=$S["Data_length"]+$S["Index_length"];return +format_number($J);}function +set_utf8mb4($i){static$O=false;if(!$O&&preg_match('~\butf8mb4~i',$i)){$O=true;echo"SET NAMES ".charset(connection()).";\n\n";}}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?connection()->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}if(DB!=""){header("HTTP/1.1 404 Not Found");page_header(lang(38).": ".h(DB),lang(118),true);}else{if($_POST["db"]&&!$m)queries_redirect(substr(ME,0,-1),lang(119),drop_databases($_POST["db"]));page_header(lang(120),$m,false);echo"

    ".lang(125,get_driver(DRIVER),"".h(connection()->server_info)."","".connection()->extension."")."\n","

    ".lang(126,"".h(logged_user())."")."\n";$j=adminer()->databases();if($j){$Lh=support("scheme");$lb=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$j=($_GET["dbsize"]?count_tables($j):array_flip($j));foreach($j +as$k=>$T){$Ch=h(ME)."db=".urlencode($k);$u=h("Db-".$k);echo"".(support("database")?"
    ":"")."".lang(38).(get_session("dbs")!==null?" - ".lang(127)."":"")."".lang(128)."".lang(129)."".lang(130)." - ".lang(131)."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$k,in_array($k,(array)$_POST["db"]),"","","",$u):""),"".h($k)."";$c=h(db_collation($k,$lb));echo"".(support("database")?"$c":$c),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($k):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),input_token(),"
    \n",script("tableCheck();");}if(!empty(adminer()->plugins)){echo"
    \n","

    ".lang(134)."

    \n
      \n";foreach(adminer()->plugins +as$Pg){$bc=(method_exists($Pg,'description')?$Pg->description():"");if(!$bc){$sh=new +\ReflectionObject($Pg);if(preg_match('~^/[\s*]+(.+)~',$sh->getDocComment(),$A))$bc=$A[1];}$Mh=(method_exists($Pg,'screenshot')?$Pg->screenshot():"");echo"
    • ".get_class($Pg)."".h($bc?": $bc":"").($Mh?" (".lang(135).")":"")."\n";}echo"
    \n";adminer()->pluginsLinks();echo"
    \n";}}page_footer("db");exit;}if(support("scheme")){if(DB!=""&&$_GET["ns"]!==""){if(!isset($_GET["ns"]))redirect(preg_replace('~ns=[^&]*&~','',ME)."ns=".get_schema());if(!set_schema($_GET["ns"])){header("HTTP/1.1 404 Not Found");page_header(lang(80).": ".h($_GET["ns"]),lang(136),true);page_footer("ns");exit;}}}adminer()->afterConnect();class +TmpFile{private$handler;var$size;function __construct(){$this->handler=tmpfile();}function -write($Za){$this->size+=strlen($Za);fwrite($this->handler,$Za);}function -send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}$Qb="'(?:''|[^'\\\\]|\\\\.)*'";$Qc="IN|OUT|INOUT";if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["download"])){$a=$_GET["download"];$n=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$N=array(idf_escape($_GET["field"]));$J=$k->select($a,$N,array(where($_GET,$n)),$N);$L=($J?$J->fetch_row():array());echo$k->value($L[0],$n[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$n=fields($a);if(!$n)$l=error();$S=table_status1($a,true);$F=$b->tableName($S);page_header(($n&&is_view($S)?$S['Engine']=='materialized view'?'Materialized view':'View':'Tabelle').": ".($F!=""?$F:h($a)),$l);$b->selectLinks($S);$Ta=$S["Comment"];if($Ta!="")echo"

    ".'Kommentar'.": ".h($Ta)."\n";if($n)$b->tableStructurePrint($n);if(!is_view($S)){if(support("indexes")){echo"

    ".'Indizes'."

    \n";$x=indexes($a);if($x)$b->tableIndexesPrint($x);echo'

    ".'Fremdschlüssel'."

    \n";$q=foreign_keys($a);if($q){echo"\n","\n";foreach($q -as$F=>$p){echo"","
    ".'Ursprung'."".'Ziel'."".'ON DELETE'."".'ON UPDATE'."
    ".implode(", ",array_map('h',$p["source"]))."","".($p["db"]!=""?"".h($p["db"]).".":"").($p["ns"]!=""?"".h($p["ns"]).".":"").h($p["table"])."","(".implode(", ",array_map('h',$p["target"])).")","".h($p["on_delete"])."\n","".h($p["on_update"])."\n",''.'Ändern'.'';}echo"
    \n";}echo'

    ".'Trigger'."

    \n";$Ag=triggers($a);if($Ag){echo"\n";foreach($Ag -as$z=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($z)."".'Ändern'."\n";echo"
    \n";}echo'
    +write($Ab){$this->size+=strlen($Ab);fwrite($this->handler,$Ab);}function +send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["callf"]))$_GET["call"]=$_GET["callf"];if(isset($_GET["function"]))$_GET["procedure"]=$_GET["function"];if(isset($_GET["download"])){$a=$_GET["download"];$o=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$M=array(idf_escape($_GET["field"]));$I=driver()->select($a,$M,array(where($_GET,$o)),$M);$K=($I?$I->fetch_row():array());echo +driver()->value($K[0],$o[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$o=fields($a);if(!$o)$m=error()?:lang(11);$S=table_status1($a);$B=adminer()->tableName($S);page_header(($o&&is_view($S)?$S['Engine']=='materialized view'?lang(137):lang(138):lang(139)).": ".($B!=""?$B:h($a)),$m);$Bh=array();foreach($o +as$y=>$n)$Bh+=$n["privileges"];adminer()->selectLinks($S,(isset($Bh["insert"])||!support("table")?"":null));$qb=$S["Comment"];if($qb!="")echo"

    ".lang(51).": ".h($qb)."\n";if($o)adminer()->tableStructurePrint($o,$S);function +tables_links(array$T){echo"

    \n";}$ke=driver()->inheritsFrom($a);if($ke){echo"

    ".lang(140)."

    \n";tables_links($ke);}if(support("indexes")&&driver()->supportsIndex($S)){echo"

    ".lang(141)."

    \n";$x=indexes($a);if($x)adminer()->tableIndexesPrint($x,$S);echo'

    ".lang(106)."

    \n";$md=foreign_keys($a);if($md){echo"\n","\n";foreach($md +as$B=>$q){echo"","
    ".lang(143)."".lang(144)."".lang(109)."".lang(108)."
    ".implode(", ",array_map('Adminer\h',$q["source"]))."";$_=($q["db"]!=""?preg_replace('~db=[^&]*~',"db=".urlencode($q["db"]),ME):($q["ns"]!=""?preg_replace('~ns=[^&]*~',"ns=".urlencode($q["ns"]),ME):ME));echo"".($q["db"]!=""&&$q["db"]!=DB?"".h($q["db"]).".":"").($q["ns"]!=""&&$q["ns"]!=$_GET["ns"]?"".h($q["ns"]).".":"").h($q["table"])."","(".implode(", ",array_map('Adminer\h',$q["target"])).")","".h($q["on_delete"]),"".h($q["on_update"]),''.lang(145).'',"\n";}echo"
    \n";}echo'

    ".lang(147)."

    \n";$Za=driver()->checkConstraints($a);if($Za){echo"\n";foreach($Za +as$y=>$X)echo"","
    ".h($X),"".lang(145)."","\n";echo"
    \n";}echo'

    ".lang(149)."

    \n";$oj=triggers($a);if($oj){echo"\n";foreach($oj +as$y=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($y)."".lang(145)."\n";echo"
    \n";}echo'

    ".lang(151)."

    \n";$Dg=driver()->partitionsInfo($a);if($Dg)echo"

    BY ".h("$Dg[partition_by]($Dg[partition])")."\n";tables_links($je);}}elseif(isset($_GET["schema"])){page_header(lang(71),"",array(),h(DB.($_GET["ns"]?".$_GET[ns]":"")));$Fi=array();$Gi=array();$da=($_GET["schema"]?:$_COOKIE["adminer_schema-".str_replace(".","_",DB)]);preg_match_all('~([^:]+):([-0-9.]+)x([-0-9.]+)(_|$)~',$da,$df,PREG_SET_ORDER);foreach($df +as$t=>$A){$Fi[$A[1]]=array($A[2],$A[3]);$Gi[]="\n\t'".js_escape($A[1])."': [ $A[2], $A[3] ]";}$dj=0;$Ia=-1;$Jh=array();$rh=array();$Pe=array();$ua=driver()->allFields();foreach(table_status('',true)as$R=>$S){if(is_view($S))continue;$Sg=0;$Jh[$R]["fields"]=array();foreach($ua[$R]as$n){$Sg+=1.25;$n["pos"]=$Sg;$Jh[$R]["fields"][$n["field"]]=$n;}$Jh[$R]["pos"]=($Fi[$R]?:array($dj,0));foreach(adminer()->foreignKeys($R)as$X){if(!$X["db"]){$Ne=$Ia;if(idx($Fi[$R],1)||idx($Fi[$X["table"]],1))$Ne=min(idx($Fi[$R],1,0),idx($Fi[$X["table"]],1,0))-1;else$Ia-=.1;while($Pe[(string)$Ne])$Ne-=.0001;$Jh[$R]["references"][$X["table"]][(string)$Ne]=array($X["source"],$X["target"]);$rh[$X["table"]][$R][(string)$Ne]=$X["target"];$Pe[(string)$Ne]=true;}}$dj=max($dj,$Jh[$R]["pos"][0]+2.5+$Sg);}echo'

    -qs(\'#schema\').onselectstart = function () { return false; }; -var tablePos = {',implode(",",$Yf)."\n",'}; -var em = qs(\'#schema\').offsetHeight / ',$sg,'; +qs(\'#schema\').onselectstart = () => false; +const tablePos = {',implode(",",$Gi)."\n",'}; +const em = qs(\'#schema\').offsetHeight / ',$dj,'; document.onmousemove = schemaMousemove; document.onmouseup = partialArg(schemaMouseup, \'',js_escape(DB),'\'); -';foreach($qf -as$F=>$R){echo"
    ",''.h($F)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$m){$X=''.h($m["field"]).'';echo"
    ".($m["primary"]?"$X":$X);}foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$kd=$jd-$Xf[$F][1];$u=0;foreach($cf[0]as$Ff)echo"\n
    ";}}foreach((array)$ff[$F]as$eg=>$gf){foreach($gf -as$jd=>$e){$kd=$jd-$Xf[$F][1];$u=0;foreach($e -as$dg)echo"\n
    ";}}echo"\n
    \n";}foreach($qf -as$F=>$R){foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$Gd=$sg;$yd=-10;foreach($cf[0]as$z=>$Ff){$Je=$R["pos"][0]+$R["fields"][$Ff]["pos"];$Ke=$qf[$eg]["pos"][0]+$qf[$eg]["fields"][$cf[1][$z]]["pos"];$Gd=min($Gd,$Je,$Ke);$yd=max($yd,$Je,$Ke);}echo"
    \n";}}}echo'
    -
    ",''.h($B)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$n){$X=''.h($n["field"]).'';echo"
    ".($n["primary"]?"$X":$X);}foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($oh[0]as$ji)echo"\n
    "."
    ";}}foreach((array)$rh[$B]as$Ni=>$th){foreach($th +as$Ne=>$e){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($e +as$Mi)echo"\n
    "."
    "."
    ";}}echo"\n
    \n";}foreach($Jh +as$B=>$R){foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$wf=$dj;$jf=-10;foreach($oh[0]as$y=>$ji){$Tg=$R["pos"][0]+$R["fields"][$ji]["pos"];$Ug=$Jh[$Ni]["pos"][0]+$Jh[$Ni]["fields"][$oh[1][$y]]["pos"];$wf=min($wf,$Tg,$Ug);$jf=max($jf,$Tg,$Ug);}echo"
    \n";}}}echo'
    +
    - -';$lb=array('','USE','DROP+CREATE','CREATE');$Zf=array('','DROP+CREATE','CREATE');$ib=array('','TRUNCATE+INSERT','INSERT');if($y=="sql")$ib[]='INSERT+UPDATE';parse_str($_COOKIE["adminer_export"],$L);if(!$L)$L=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($L["events"])){$L["routines"]=$L["events"]=($_GET["dump"]=="");$L["triggers"]=$L["table_style"];}echo"
    ".'Ergebnis'."".html_select("output",$b->dumpOutput(),$L["output"],0)."\n";echo"
    ".'Format'."".html_select("format",$b->dumpFormat(),$L["format"],0)."\n";echo($y=="sqlite"?"":"
    ".'Datenbank'."".html_select('db_style',$lb,$L["db_style"]).(support("routine")?checkbox("routines",1,$L["routines"],'Routinen'):"").(support("event")?checkbox("events",1,$L["events"],'Ereignisse'):"")),"
    ".'Tabellen'."".html_select('table_style',$Zf,$L["table_style"]).checkbox("auto_increment",1,$L["auto_increment"],'Auto-Inkrement').(support("trigger")?checkbox("triggers",1,$L["triggers"],'Trigger'):""),"
    ".'Daten'."".html_select('data_style',$ib,$L["data_style"]),'
    -

    - - - -',script("qsl('table').onclick = dumpClick;");$Ne=array();if(DB!=""){$Fa=($a!=""?"":" checked");echo"","\n";$Zg="";$ag=tables_list();foreach($ag -as$F=>$V){$Me=preg_replace('~_.*~','',$F);$Fa=($a==""||$a==(substr($a,-1)=="%"?"$Me%":$F));$Qe="\n";$i=$b->databases();if($i){foreach($i -as$j){if(!information_schema($j)){$Me=preg_replace('~_.*~','',$j);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$F,$Fa,$F,"","block");if($V!==null&&!preg_match('~table~i',$V))$Zg.="$Qe\n";else -echo"$Qe\n";$Ne[$Me]++;}echo$Zg;if($ag)echo -script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$j,$a==""||$a=="$Me%",$j,"","block")."\n";$Ne[$Me]++;}}}else + +';$Rb=array('','USE','DROP+CREATE','CREATE');$Hi=array('','DROP+CREATE','CREATE');$Ob=array('','TRUNCATE+INSERT','INSERT');if(JUSH=="sql")$Ob[]='INSERT+UPDATE';$K=get_settings("adminer_export");if(!$K)$K=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($K["events"])){$K["routines"]=$K["events"]=($_GET["dump"]=="");$K["triggers"]=$K["table_style"];}echo"
    ".lang(153)."".html_radios("output",adminer()->dumpOutput(),$K["output"])."\n","
    ".lang(154)."".html_radios("format",adminer()->dumpFormat(),$K["format"])."\n",(JUSH=="sqlite"?"":"
    ".lang(38)."".html_select('db_style',$Rb,$K["db_style"]).(support("type")?checkbox("types",1,$K["types"],lang(6)):"").(support("routine")?checkbox("routines",1,$K["routines"],lang(73)):"").(support("event")?checkbox("events",1,$K["events"],lang(75)):"")),"
    ".lang(129)."".html_select('table_style',$Hi,$K["table_style"]).checkbox("auto_increment",1,$K["auto_increment"],lang(52)).(support("trigger")?checkbox("triggers",1,$K["triggers"],lang(149)):""),"
    ".lang(155)."".html_select('data_style',$Ob,$K["data_style"]),'
    +

    +',input_token(),' + +',script("qsl('table').onclick = dumpClick;");$Yg=array();if(DB!=""){$bb=($a!=""?"":" checked");echo"","\n";$Sj="";$Ji=tables_list();foreach($Ji +as$B=>$U){$Xg=preg_replace('~_.*~','',$B);$bb=($a==""||$a==(substr($a,-1)=="%"?"$Xg%":$B));$bh="\n";$j=adminer()->databases();if($j){foreach($j +as$k){if(!information_schema($k)){$Xg=preg_replace('~_.*~','',$k);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$B,$bb,$B,"","block");if($U!==null&&!preg_match('~table~i',$U))$Sj +.="$bh\n";else +echo"$bh\n";$Yg[$Xg]++;}echo$Sj;if($Ji)echo +script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$k,$a==""||$a=="$Xg%",$k,"","block")."\n";$Yg[$Xg]++;}}}else echo"
    ";}echo'
    -';$lc=true;foreach($Ne -as$z=>$X){if($z!=""&&$X>1){echo($lc?"

    ":" ")."".h($z)."";$lc=false;}}}elseif(isset($_GET["sql"])){if(!$l&&$_POST["export"]){dump_headers("sql");$b->dumpTable("","");$b->dumpData("","table",$_POST["query"]);exit;}restart_session();$Gc=&get_session("queries");$Fc=&$Gc[DB];if(!$l&&$_POST["clear"]){$Fc=array();redirect(remove_from_uri("history"));}page_header((isset($_GET["import"])?'Importieren':'SQL-Kommando'),$l);if(!$l&&$_POST){$r=false;if(!isset($_GET["import"]))$I=$_POST["query"];elseif($_POST["webfile"]){$If=$b->importServerPath();$r=@fopen((file_exists($If)?$If:"compress.zlib://$If.gz"),"rb");$I=($r?fread($r,1e6):false);}else$I=get_file("sql_file",true);if(is_string($I)){if(function_exists('memory_get_usage'))@ini_set("memory_limit",max(ini_bytes("memory_limit"),2*strlen($I)+memory_get_usage()+8e6));if($I!=""&&strlen($I)<1e6){$H=$I.(preg_match("~;[ \t\r\n]*\$~",$I)?"":";");if(!$Fc||reset(end($Fc))!=$H){restart_session();$Fc[]=array($H,time());set_session("queries",$Gc);stop_session();}}$Gf="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|-- )[^\n]*\n?|--\r?\n)";$rb=";";$Sd=0;$Nb=true;$g=connect();if(is_object($g)&&DB!=""){$g->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$g);}$Sa=0;$Sb=array();$ve='[\'"'.($y=="sql"?'`#':($y=="sqlite"?'`[':($y=="mssql"?'[':''))).']|/\*|-- |$'.($y=="pgsql"?'|\$[^$]*\$':'');$tg=microtime(true);parse_str($_COOKIE["adminer_export"],$ia);$Eb=$b->dumpFormat();unset($Eb["sql"]);while($I!=""){if(!$Sd&&preg_match("~^$Gf*+DELIMITER\\s+(\\S+)~i",$I,$C)){$rb=$C[1];$I=substr($I,strlen($C[0]));}else{preg_match('('.preg_quote($rb)."\\s*|$ve)",$I,$C,PREG_OFFSET_CAPTURE,$Sd);list($rc,$Ie)=$C[0];if(!$rc&&$r&&!feof($r))$I.=fread($r,1e5);else{if(!$rc&&rtrim($I)=="")break;$Sd=$Ie+strlen($rc);if($rc&&rtrim($rc)!=$rb){while(preg_match('('.($rc=='/*'?'\*/':($rc=='['?']':(preg_match('~^-- |^#~',$rc)?"\n":preg_quote($rc)."|\\\\."))).'|$)s',$I,$C,PREG_OFFSET_CAPTURE,$Sd)){$pf=$C[0][0];if(!$pf&&$r&&!feof($r))$I.=fread($r,1e5);else{$Sd=$C[0][1]+strlen($pf);if($pf[0]!="\\")break;}}}else{$Nb=false;$H=substr($I,0,$Ie);$Sa++;$Qe="

    ".$b->sqlCommandQuery($H)."
    \n";if($y=="sqlite"&&preg_match("~^$Gf*+ATTACH\\b~i",$H,$C)){echo$Qe,"

    ".'ATTACH queries are not supported.'."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$Qe;ob_flush();flush();}$Lf=microtime(true);if($f->multi_query($H)&&is_object($g)&&preg_match("~^$Gf*+USE\\b~i",$H))$g->query($H);do{$J=$f->store_result();if($f->error){echo($_POST["only_errors"]?$Qe:""),"

    ".'Fehler in der SQL-Abfrage'.($f->errno?" ($f->errno)":"").": ".error()."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break -2;}else{$jg=" (".format_time($Lf).")".(strlen($H)<1000?" ".'Bearbeiten'."":"");$ka=$f->affected_rows;$ch=($_POST["only_errors"]?"":$k->warnings());$dh="warnings-$Sa";if($ch)$jg.=", ".'Warnings'."".script("qsl('a').onclick = partial(toggle, '$dh');","");$Zb=null;$ac="explain-$Sa";if(is_object($J)){$_=$_POST["limit"];$ie=select($J,$g,array(),$_);if(!$_POST["only_errors"]){echo"

    \n";$Pd=$J->num_rows;echo"

    ".($Pd?($_&&$Pd>$_?sprintf('%d / ',$_):"").lang(array('%d Datensatz','%d Datensätze'),$Pd):""),$jg;if($g&&preg_match("~^($Gf|\\()*+SELECT\\b~i",$H)&&($Zb=explain($g,$H)))echo", Explain".script("qsl('a').onclick = partial(toggle, '$ac');","");$v="export-$Sa";echo", ".'Exportieren'."".script("qsl('a').onclick = partial(toggle, '$v');","")."\n"."

    \n";}}else{if(preg_match("~^$Gf*+(CREATE|DROP|ALTER)$Gf++(DATABASE|SCHEMA)\\b~i",$H)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(array('Abfrage ausgeführt, %d Datensatz betroffen.','Abfrage ausgeführt, %d Datensätze betroffen.'),$ka)."$jg\n";}echo($ch?"

    \n":"");if($Zb){echo"\n";}}$Lf=microtime(true);}while($f->next_result());}$I=substr($I,$Sd);$Sd=0;}}}}if($Nb)echo"

    ".'Kein Kommando vorhanden.'."\n";elseif($_POST["only_errors"]){echo"

    ".lang(array('SQL-Abfrage erfolgreich ausgeführt.','%d SQL-Abfragen erfolgreich ausgeführt.'),$Sa-count($Sb))," (".format_time($tg).")\n";}elseif($Sb&&$Sa>1)echo"

    ".'Fehler in der SQL-Abfrage'.": ".implode("",$Sb)."\n";}else -echo"

    ".upload_error($I)."\n";}echo' +';$cd=true;foreach($Yg +as$y=>$X){if($y!=""&&$X>1){echo($cd?"

    ":" ")."".h($y)."";$cd=false;}}}elseif(isset($_GET["privileges"])){page_header(lang(72));echo'

    \n";hidden_fields_get();echo +input_hidden("db",DB),($vd?"":input_hidden("grant")),"\n","\n";while($K=$I->fetch_assoc())echo'
    ".lang(36)."".lang(34)."
    '.h($K["User"])."".h($K["Host"]).''.lang(12)."\n";if(!$vd||DB!="")echo"
    \n";echo"
    \n","

    \n";}elseif(isset($_GET["sql"])){if(!$m&&$_POST["export"]){save_settings(array("output"=>$_POST["output"],"format"=>$_POST["format"]),"adminer_import");dump_headers("sql");if($_POST["format"]=="sql")echo"$_POST[query]\n";else{adminer()->dumpTable("","");adminer()->dumpData("","table",$_POST["query"]);adminer()->dumpFooter();}exit;}restart_session();$Ld=&get_session("queries");$Kd=&$Ld[DB];if(!$m&&$_POST["clear"]){$Kd=array();redirect(remove_from_uri("history"));}stop_session();page_header((isset($_GET["import"])?lang(76):lang(65)),$m);$Ue='--'.(JUSH=='sql'?' ':'');if(!$m&&$_POST){$r=false;if(!isset($_GET["import"]))$H=$_POST["query"];elseif($_POST["webfile"]){$ni=adminer()->importServerPath();$r=@fopen((file_exists($ni)?$ni:"compress.zlib://$ni.gz"),"rb");$H=($r?fread($r,1e6):false);}else$H=get_file("sql_file",true,";");if(is_string($H)){if(function_exists('memory_get_usage')&&($of=ini_bytes("memory_limit"))!="-1")@ini_set("memory_limit",max($of,strval(2*strlen($H)+memory_get_usage()+8e6)));if($H!=""&&strlen($H)<1e6){$hh=$H.(preg_match("~;[ \t\r\n]*\$~",$H)?"":";");if(!$Kd||first(end($Kd))!=$hh){restart_session();$Kd[]=array($hh,time());set_session("queries",$Ld);stop_session();}}$ki="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|$Ue)[^\n]*\n?|--\r?\n)";$Zb=driver()->delimiter;$C=0;$xc=true;$h=connect();if($h&&DB!=""){$h->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$h);}$pb=0;$Ec=array();$Ag='[\'"'.(JUSH=="sql"?'`#':(JUSH=="sqlite"?'`[':(JUSH=="mssql"?'[':''))).']|/\*|'.$Ue.'|$'.(JUSH=="pgsql"?'|\$([a-zA-Z]\w*)?\$':'');$ej=microtime(true);$oa=get_settings("adminer_import");while($H!=""){if(!$C&&preg_match("~^$ki*+DELIMITER\\s+(\\S+)~i",$H,$A)){$Zb=preg_quote($A[1]);$H=substr($H,strlen($A[0]));}elseif(!$C&&JUSH=='pgsql'&&preg_match("~^($ki*+COPY\\s+)[^;]+\\s+FROM\\s+stdin;~i",$H,$A)){$Zb="\n\\\\\\.\r?\n";$C=strlen($A[0]);}else{preg_match("($Zb\\s*|$Ag)",$H,$A,PREG_OFFSET_CAPTURE,$C);list($od,$Sg)=$A[0];if(!$od&&$r&&!feof($r))$H +.=fread($r,1e5);else{if(!$od&&rtrim($H)=="")break;$C=$Sg+strlen($od);if($od&&!preg_match("(^$Zb)",$od)){$Ta=driver()->hasCStyleEscapes()||(JUSH=="pgsql"&&($Sg>0&&strtolower($H[$Sg-1])=="e"));$Lg=($od=='/*'?'\*/':($od=='['?']':(preg_match("~^$Ue|^#~",$od)?"\n":preg_quote($od).($Ta?'|\\\\.':''))));while(preg_match("($Lg|\$)s",$H,$A,PREG_OFFSET_CAPTURE,$C)){$Hh=$A[0][0];if(!$Hh&&$r&&!feof($r))$H +.=fread($r,1e5);else{$C=$A[0][1]+strlen($Hh);if(!$Hh||$Hh[0]!="\\")break;}}}else{$xc=false;$hh=substr($H,0,$Sg+($Zb[0]=="\n"?3:0));$pb++;$bh="
    ".adminer()->sqlCommandQuery($hh)."
    \n";if(JUSH=="sqlite"&&preg_match("~^$ki*+ATTACH\\b~i",$hh,$A)){echo$bh,"

    ".lang(157)."\n";$Ec[]=" $pb";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$bh;ob_flush();flush();}$si=microtime(true);if(connection()->multi_query($hh)&&$h&&preg_match("~^$ki*+USE\\b~i",$hh))$h->query($hh);do{$I=connection()->store_result();if(connection()->error){echo($_POST["only_errors"]?$bh:""),"

    ".lang(158).(connection()->errno?" (".connection()->errno.")":"").": ".error()."\n";$Ec[]=" $pb";if($_POST["error_stops"])break +2;}else{$Ti=" (".format_time($si).")".(strlen($hh)<1000?" ".lang(12)."":"");$qa=connection()->affected_rows;$Vj=($_POST["only_errors"]?"":driver()->warnings());$Wj="warnings-$pb";if($Vj)$Ti +.=", ".lang(47)."".script("qsl('a').onclick = partial(toggle, '$Wj');","");$Mc=null;$mg=null;$Nc="explain-$pb";if(is_object($I)){$z=$_POST["limit"];$mg=print_select_result($I,$h,array(),$z);if(!$_POST["only_errors"]){echo"

    \n";$Nf=$I->num_rows;echo"
    \n";}}else{if(preg_match("~^$ki*+(CREATE|DROP|ALTER)$ki++(DATABASE|SCHEMA)\\b~i",$hh)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(161,$qa)."$Ti\n";}echo($Vj?"

    \n":"");if($Mc){echo"\n";}}$si=microtime(true);}while(connection()->next_result());}$H=substr($H,$C);$C=0;}}}}if($xc)echo"

    ".lang(162)."\n";elseif($_POST["only_errors"])echo"

    ".lang(163,$pb-count($Ec))," (".format_time($ej).")\n";elseif($Ec&&$pb>1)echo"

    ".lang(158).": ".implode("",$Ec)."\n";}else +echo"

    ".upload_error($H)."\n";}echo'

    -';$Xb="";if(!isset($_GET["import"])){$H=$_GET["sql"];if($_POST)$H=$_POST["query"];elseif($_GET["history"]=="all")$H=$Fc;elseif($_GET["history"]!="")$H=$Fc[$_GET["history"]][0];echo"

    ";textarea("query",$H,20);echo -script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    $Xb\n",'Datensätze begrenzen'.": \n";}else{echo"

    ".'Datei importieren'."
    ";$zc=(extension_loaded("zlib")?"[.gz]":"");echo(ini_bool("file_uploads")?"SQL$zc (< ".ini_get("upload_max_filesize")."B): \n$Xb":'Importieren von Dateien abgeschaltet.'),"
    \n";$Mc=$b->importServerPath();if($Mc){echo"
    ".'Vom Server'."
    ",sprintf('Webserver Datei %s',"".h($Mc)."$zc"),' ',"
    \n";}echo"

    ";}echo -checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),'Bei Fehler anhalten')."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),'Nur Fehler anzeigen')."\n","\n";if(!isset($_GET["import"])&&$Fc){print_fieldset("history",'History',$_GET["history"]!="");for($X=end($Fc);$X;$X=prev($Fc)){$z=key($Fc);list($H,$jg,$Ib)=$X;echo''.'Bearbeiten'.""." ".@date("H:i:s",$jg).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace('~^(#|-- ).*~m','',$H)))),80,"").($Ib?" ($Ib)":"")."
    \n";}echo"\n","".'Alle bearbeiten'."\n","\n";}echo'

    -';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$n=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$n):""):where($_GET,$n));$Kg=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($n -as$F=>$m){if(!isset($m["privileges"][$Kg?"update":"insert"])||$b->fieldName($m)==""||$m["generated"])unset($n[$F]);}if($_POST&&!$l&&!isset($_GET["select"])){$B=$_POST["referer"];if($_POST["insert"])$B=($Kg?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$B))$B=ME."select=".urlencode($a);$x=indexes($a);$Fg=unique_array($_GET["where"],$x);$Ye="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($B,'Datensatz wurde gelöscht.',$k->delete($a,$Ye,!$Fg));else{$P=array();foreach($n -as$F=>$m){$X=process_input($m);if($X!==false&&$X!==null)$P[idf_escape($F)]=$X;}if($Kg){if(!$P)redirect($B);queries_redirect($B,'Datensatz wurde geändert.',$k->update($a,$P,$Ye,!$Fg));if(is_ajax()){page_headers();page_messages($l);exit;}}else{$J=$k->insert($a,$P);$id=($J?last_id():0);queries_redirect($B,sprintf('Datensatz%s wurde eingefügt.',($id?" $id":"")),$J);}}}$L=null;if($_POST["save"])$L=(array)$_POST["fields"];elseif($Z){$N=array();foreach($n -as$F=>$m){if(isset($m["privileges"]["select"])){$pa=convert_field($m);if($_POST["clone"]&&$m["auto_increment"])$pa="''";if($y=="sql"&&preg_match("~enum|set~",$m["type"]))$pa="1*".idf_escape($F);$N[]=($pa?"$pa AS ":"").idf_escape($F);}}$L=array();if(!support("table"))$N=array("*");if($N){$J=$k->select($a,$N,array($Z),$N,array(),(isset($_GET["select"])?2:1));if(!$J)$l=error();else{$L=$J->fetch_assoc();if(!$L)$L=false;}if(isset($_GET["select"])&&(!$L||$J->fetch_assoc()))$L=null;}}if(!support("table")&&!$n){if(!$Z){$J=$k->select($a,array("*"),$Z,array("*"));$L=($J?$J->fetch_assoc():false);if(!$L)$L=array($k->primary=>"");}if($L){foreach($L -as$z=>$X){if(!$Z)$L[$z]=null;$n[$z]=array("field"=>$z,"null"=>($z!=$k->primary),"auto_increment"=>($z==$k->primary));}}}edit_form($a,$n,$L,$Kg);}elseif(isset($_GET["create"])){$a=$_GET["create"];$we=array();foreach(array('HASH','LINEAR HASH','KEY','LINEAR KEY','RANGE','LIST')as$z)$we[$z]=$z;$ef=referencable_primary($a);$q=array();foreach($ef -as$Wf=>$m)$q[str_replace("`","``",$Wf)."`".str_replace("`","``",$m["field"])]=$Wf;$le=array();$S=array();if($a!=""){$le=fields($a);$S=table_status($a);if(!$S)$l='Keine Tabellen.';}$L=$_POST;$L["fields"]=(array)$L["fields"];if($L["auto_increment_col"])$L["fields"][$L["auto_increment_col"]]["auto_increment"]=true;if($_POST)set_adminer_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($L["fields"])&&!$l){if($_POST["drop"])queries_redirect(substr(ME,0,-1),'Tabelle wurde entfernt.',drop_tables(array($a)));else{$n=array();$na=array();$Og=false;$oc=array();$ke=reset($le);$ma=" FIRST";foreach($L["fields"]as$z=>$m){$p=$q[$m["type"]];$Bg=($p!==null?$ef[$p]:$m);if($m["field"]!=""){if(!$m["has_default"])$m["default"]=null;if($z==$L["auto_increment_col"])$m["auto_increment"]=true;$Ue=process_field($m,$Bg);$na[]=array($m["orig"],$Ue,$ma);if(!$ke||$Ue!=process_field($ke,$ke)){$n[]=array($m["orig"],$Ue,$ma);if($m["orig"]!=""||$ma)$Og=true;}if($p!==null)$oc[idf_escape($m["field"])]=($a!=""&&$y!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$q[$m["type"]],'source'=>array($m["field"]),'target'=>array($Bg["field"]),'on_delete'=>$m["on_delete"],));$ma=" AFTER ".idf_escape($m["field"]);}elseif($m["orig"]!=""){$Og=true;$n[]=array($m["orig"]);}if($m["orig"]!=""){$ke=next($le);if(!$ke)$ma="";}}$ye="";if($we[$L["partition_by"]]){$ze=array();if($L["partition_by"]=='RANGE'||$L["partition_by"]=='LIST'){foreach(array_filter($L["partition_names"])as$z=>$X){$Y=$L["partition_values"][$z];$ze[]="\n PARTITION ".idf_escape($X)." VALUES ".($L["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$ye.="\nPARTITION BY $L[partition_by]($L[partition])".($ze?" (".implode(",",$ze)."\n)":($L["partitions"]?" PARTITIONS ".(+$L["partitions"]):""));}elseif(support("partitioning")&&preg_match("~partitioned~",$S["Create_options"]))$ye.="\nREMOVE PARTITIONING";$D='Tabelle wurde geändert.';if($a==""){cookie("adminer_engine",$L["Engine"]);$D='Tabelle wurde erstellt.';}$F=trim($L["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($F),$D,alter_table($a,$F,($y=="sqlite"&&($Og||$oc)?$na:$n),$oc,($L["Comment"]!=$S["Comment"]?$L["Comment"]:null),($L["Engine"]&&$L["Engine"]!=$S["Engine"]?$L["Engine"]:""),($L["Collation"]&&$L["Collation"]!=$S["Collation"]?$L["Collation"]:""),($L["Auto_increment"]!=""?number($L["Auto_increment"]):""),$ye));}}page_header(($a!=""?'Tabelle ändern':'Tabelle erstellen'),$l,array("table"=>$a),h($a));if(!$_POST){$L=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($Cg["int"])?"int":(isset($Cg["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$L=$S;$L["name"]=$a;$L["fields"]=array();if(!$_GET["auto_increment"])$L["Auto_increment"]="";foreach($le -as$m){$m["has_default"]=isset($m["default"]);$L["fields"][]=$m;}if(support("partitioning")){$tc="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($a);$J=$f->query("SELECT PARTITION_METHOD, PARTITION_ORDINAL_POSITION, PARTITION_EXPRESSION $tc ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");list($L["partition_by"],$L["partitions"],$L["partition"])=$J->fetch_row();$ze=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $tc AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$ze[""]="";$L["partition_names"]=array_keys($ze);$L["partition_values"]=array_values($ze);}}}$Pa=collations();$Pb=engines();foreach($Pb -as$Ob){if(!strcasecmp($Ob,$L["Engine"])){$L["Engine"]=$Ob;break;}}echo' +';$Kc="";if(!isset($_GET["import"])){$hh=$_GET["sql"];if($_POST)$hh=$_POST["query"];elseif($_GET["history"]=="all")$hh=$Kd;elseif($_GET["history"]!="")$hh=idx($Kd[$_GET["history"]],0);echo"

    ";textarea("query",$hh,20);echo +script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    ";adminer()->sqlPrintAfter();echo"$Kc\n",lang(165).": \n";}else{$Ad=(extension_loaded("zlib")?"[.gz]":"");echo"

    ".lang(166)."
    ",file_input("SQL$Ad: \n$Kc"),"
    \n";$Wd=adminer()->importServerPath();if($Wd)echo"
    ".lang(167)."
    ",lang(168,"".h($Wd)."$Ad"),' ',"
    \n";echo"

    ";}echo +checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),lang(170))."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),lang(171))."\n",input_token();if(!isset($_GET["import"])&&$Kd){print_fieldset("history",lang(172),$_GET["history"]!="");for($X=end($Kd);$X;$X=prev($Kd)){$y=key($Kd);list($hh,$Ti,$sc)=$X;echo''.lang(12).""." ".@date("H:i:s",$Ti).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace("~^(#|$Ue).*~m",'',$hh)))),80,"").($sc?" ($sc)":"")."
    \n";}echo"\n","".lang(174)."\n","\n";}echo' +';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$o=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$o):""):where($_GET,$o));$_j=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($o +as$B=>$n){if((!$_j&&!isset($n["privileges"]["insert"]))||adminer()->fieldName($n)=="")unset($o[$B]);}if($_POST&&!$m&&!isset($_GET["select"])){$We=$_POST["referer"];if($_POST["insert"])$We=($_j?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$We))$We=ME."select=".urlencode($a);$x=indexes($a);$vj=unique_array($_GET["where"],$x);$kh="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($We,lang(175),driver()->delete($a,$kh,$vj?0:1));else{$O=array();foreach($o +as$B=>$n){$X=process_input($n);if($X!==false&&$X!==null)$O[idf_escape($B)]=$X;}if($_j){if(!$O)redirect($We);queries_redirect($We,lang(176),driver()->update($a,$O,$kh,$vj?0:1));if(is_ajax()){page_headers();page_messages($m);exit;}}else{$I=driver()->insert($a,$O);$Me=($I?last_id($I):0);queries_redirect($We,lang(177,($Me?" $Me":"")),$I);}}}$K=null;if($Z){$M=array();foreach($o +as$B=>$n){if(isset($n["privileges"]["select"])){$ya=($_POST["clone"]&&$n["auto_increment"]?"''":convert_field($n));$M[]=($ya?"$ya AS ":"").idf_escape($B);}}$K=array();if(!support("table"))$M=array("*");if($M){$I=driver()->select($a,$M,array($Z),$M,array(),(isset($_GET["select"])?2:1));if(!$I)$m=error();else{$K=$I->fetch_assoc();if(!$K)$K=false;}if(isset($_GET["select"])&&(!$K||$I->fetch_assoc()))$K=null;}}if(!support("table")&&!$o){if(!$Z){$I=driver()->select($a,array("*"),array(),array("*"));$K=($I?$I->fetch_assoc():false);if(!$K)$K=array(driver()->primary=>"");}if($K){foreach($K +as$y=>$X){if(!$Z)$K[$y]=null;$o[$y]=array("field"=>$y,"null"=>($y!=driver()->primary),"auto_increment"=>($y==driver()->primary));}}}if($_POST["save"])$K=(array)$_POST["fields"]+($K?$K:array());edit_form($a,$o,$K,$_j,$m);}elseif(isset($_GET["create"])){$a=$_GET["create"];$Fg=driver()->partitionBy;$Ig=($Fg?driver()->partitionsInfo($a):array());$qh=referencable_primary($a);$md=array();foreach($qh +as$Di=>$n)$md[str_replace("`","``",$Di)."`".str_replace("`","``",$n["field"])]=$Di;$pg=array();$S=array();if($a!=""){$pg=fields($a);$S=table_status1($a);if(count($S)<2)$m=lang(11);}$K=$_POST;$K["fields"]=(array)$K["fields"];if($K["auto_increment_col"])$K["fields"][$K["auto_increment_col"]]["auto_increment"]=true;if($_POST)save_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($K["fields"])&&!$m){if($_POST["drop"])queries_redirect(substr(ME,0,-1),lang(178),drop_tables(array($a)));else{$o=array();$ua=array();$Fj=false;$kd=array();$og=reset($pg);$sa=" FIRST";foreach($K["fields"]as$y=>$n){$q=$md[$n["type"]];$qj=($q!==null?$qh[$q]:$n);if($n["field"]!=""){if(!$n["generated"])$n["default"]=null;$gh=process_field($n,$qj);$ua[]=array($n["orig"],$gh,$sa);if(!$og||$gh!==process_field($og,$og)){$o[]=array($n["orig"],$gh,$sa);if($n["orig"]!=""||$sa)$Fj=true;}if($q!==null)$kd[idf_escape($n["field"])]=($a!=""&&JUSH!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$md[$n["type"]],'source'=>array($n["field"]),'target'=>array($qj["field"]),'on_delete'=>$n["on_delete"],));$sa=" AFTER ".idf_escape($n["field"]);}elseif($n["orig"]!=""){$Fj=true;$o[]=array($n["orig"]);}if($n["orig"]!=""){$og=next($pg);if(!$og)$sa="";}}$E=array();if(in_array($K["partition_by"],$Fg)){foreach($K +as$y=>$X){if(preg_match('~^partition~',$y))$E[$y]=$X;}foreach($E["partition_names"]as$y=>$B){if($B==""){unset($E["partition_names"][$y]);unset($E["partition_values"][$y]);}}$E["partition_names"]=array_values($E["partition_names"]);$E["partition_values"]=array_values($E["partition_values"]);if($E==$Ig)$E=array();}elseif(preg_match("~partitioned~",$S["Create_options"]))$E=null;$qf=lang(179);if($a==""){cookie("adminer_engine",$K["Engine"]);$qf=lang(180);}$B=trim($K["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($B),$qf,alter_table($a,$B,(JUSH=="sqlite"&&($Fj||$kd)?$ua:$o),$kd,($K["Comment"]!=$S["Comment"]?$K["Comment"]:null),($K["Engine"]&&$K["Engine"]!=$S["Engine"]?$K["Engine"]:""),($K["Collation"]&&$K["Collation"]!=$S["Collation"]?$K["Collation"]:""),($K["Auto_increment"]!=""?number($K["Auto_increment"]):""),$E));}}page_header(($a!=""?lang(45):lang(78)),$m,array("table"=>$a),h($a));if(!$_POST){$rj=driver()->types();$K=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($rj["int"])?"int":(isset($rj["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$K=$S;$K["name"]=$a;$K["fields"]=array();if(!$_GET["auto_increment"])$K["Auto_increment"]="";foreach($pg +as$n){$n["generated"]=$n["generated"]?:(isset($n["default"])?"DEFAULT":"");$K["fields"][]=$n;}if($Fg){$K+=$Ig;$K["partition_names"][]="";$K["partition_values"][]="";}}}$lb=collations();if(is_array(reset($lb)))$lb=call_user_func_array('array_merge',array_values($lb));$zc=driver()->engines();foreach($zc +as$yc){if(!strcasecmp($yc,$K["Engine"])){$K["Engine"]=$yc;break;}}echo'

    -';if(support("columns")||$a==""){echo'Name der Tabelle: -';if($a==""&&!$_POST)echo -script("focus(qs('#form')['name']);");echo($Pb?"".on_help("getTarget(event).value",1).script("qsl('select').onchange = helpClose;"):""),' ',($Pa&&!preg_match("~sqlite|mssql~",$y)?html_select("Collation",array(""=>"(".'Kollation'.")")+$Pa,$L["Collation"]):""),' -';}echo' -';if(support("columns")){echo'

    - -';edit_fields($L["fields"],$Pa,"TABLE",$q);echo'
    -',script("editFields();"),'
    -

    -Auto-Inkrement: -',checkbox("defaults",1,($_POST?$_POST["defaults"]:adminer_setting("defaults")),'Vorgabewerte festlegen',"columnShow(this.checked, 5)","jsonly"),(support("comment")?checkbox("comments",1,($_POST?$_POST["comments"]:adminer_setting("comments")),'Kommentar',"editingCommentsClick(this, true);","jsonly").' ':''),'

    - +';if(support("columns")||$a==""){echo +lang(181).": \n",($zc?html_select("Engine",array(""=>"(".lang(182).")")+$zc,$K["Engine"]).on_help("event.target.value",1).script("qsl('select').onchange = helpClose;")."\n":"");if($lb)echo"".optionlist($lb)."\n",(preg_match("~sqlite|mssql~",JUSH)?"":"\n");echo"\n";}if(support("columns")){echo"

    \n","\n";edit_fields($K["fields"],$lb,"TABLE",$md);echo"
    \n",script("editFields();"),"
    \n

    \n",lang(52).": \n",checkbox("defaults",1,($_POST?$_POST["defaults"]:get_setting("defaults")),lang(183),"columnShow(this.checked, 5)","jsonly");$sb=($_POST?$_POST["comments"]:get_setting("comments"));echo(support("comment")?checkbox("comments",1,$sb,lang(51),"editingCommentsClick(this, true);","jsonly").' '.(preg_match('~\n~',$K["Comment"])?"":''):''),'

    + ';}echo' -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}if(support("partitioning")){$xe=preg_match('~RANGE|LIST~',$L["partition_by"]);print_fieldset("partition",'Partitionieren um',$L["partition_by"]);echo'

    -',"".on_help("getTarget(event).value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),'() -Partitionen: - - -';foreach($L["partition_names"]as$z=>$X){echo'',' - -';}echo' -

    -';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$Oc=array("PRIMARY","UNIQUE","INDEX");$S=table_status($a,true);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="SPATIAL";$x=indexes($a);$Oe=array();if($y=="mongo"){$Oe=$x["_id_"];unset($Oc[0]);unset($x["_id_"]);}$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["drop_col"]){$oa=array();foreach($L["indexes"]as$w){$F=$w["name"];if(in_array($w["type"],$Oc)){$e=array();$od=array();$tb=array();$P=array();ksort($w["columns"]);foreach($w["columns"]as$z=>$d){if($d!=""){$nd=$w["lengths"][$z];$sb=$w["descs"][$z];$P[]=idf_escape($d).($nd?"(".(+$nd).")":"").($sb?" DESC":"");$e[]=$d;$od[]=($nd?$nd:null);$tb[]=$sb;}}if($e){$Yb=$x[$F];if($Yb){ksort($Yb["columns"]);ksort($Yb["lengths"]);ksort($Yb["descs"]);if($w["type"]==$Yb["type"]&&array_values($Yb["columns"])===$e&&(!$Yb["lengths"]||array_values($Yb["lengths"])===$od)&&array_values($Yb["descs"])===$tb){unset($x[$F]);continue;}}$oa[]=array($w["type"],$F,$P);}}}foreach($x -as$F=>$Yb)$oa[]=array($Yb["type"],$F,"DROP");if(!$oa)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),'Indizes geändert.',alter_indexes($a,$oa));}page_header('Indizes',$l,array("table"=>$a),h($a));$n=array_keys(fields($a));if($_POST["add"]){foreach($L["indexes"]as$z=>$w){if($w["columns"][count($w["columns"])]!="")$L["indexes"][$z]["columns"][]="";}$w=end($L["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$L["indexes"][]=array("columns"=>array(1=>""));}if(!$L){foreach($x -as$z=>$w){$x[$z]["name"]=$z;$x[$z]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$L["indexes"]=$x;}echo' +';if($a!="")echo'',confirm(lang(184,$a));if($Fg&&(JUSH=='sql'||$a=="")){$Gg=preg_match('~RANGE|LIST~',$K["partition_by"]);print_fieldset("partition",lang(185),$K["partition_by"]);echo"

    ".html_select("partition_by",array_merge(array(""),$Fg),$K["partition_by"]).on_help("event.target.value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),"()\n",lang(186).": \n","\n","\n";foreach($K["partition_names"]as$y=>$X)echo'','\n\n";}echo +input_token(),' +';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$ee=array("PRIMARY","UNIQUE","INDEX");$S=table_status1($a,true);$be=driver()->indexAlgorithms($S);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="SPATIAL";$x=indexes($a);$o=fields($a);$G=array();if(JUSH=="mongo"){$G=$x["_id_"];unset($ee[0]);unset($x["_id_"]);}$K=$_POST;if($K)save_settings(array("index_options"=>$K["options"]));if($_POST&&!$m&&!$_POST["add"]&&!$_POST["drop_col"]){$b=array();foreach($K["indexes"]as$w){$B=$w["name"];if(in_array($w["type"],$ee)){$e=array();$Se=array();$cc=array();$ce=(support("partial_indexes")?$w["partial"]:"");$ae=(in_array($w["algorithm"],$be)?$w["algorithm"]:"");$O=array();ksort($w["columns"]);foreach($w["columns"]as$y=>$d){if($d!=""){$Re=idx($w["lengths"],$y);$ac=idx($w["descs"],$y);$O[]=($o[$d]?idf_escape($d):$d).($Re?"(".(+$Re).")":"").($ac?" DESC":"");$e[]=$d;$Se[]=($Re?:null);$cc[]=$ac;}}$Lc=$x[$B];if($Lc){ksort($Lc["columns"]);ksort($Lc["lengths"]);ksort($Lc["descs"]);if($w["type"]==$Lc["type"]&&array_values($Lc["columns"])===$e&&(!$Lc["lengths"]||array_values($Lc["lengths"])===$Se)&&array_values($Lc["descs"])===$cc&&$Lc["partial"]==$ce&&(!$be||$Lc["algorithm"]==$ae)){unset($x[$B]);continue;}}if($e)$b[]=array($w["type"],$B,$O,$ae,$ce);}}foreach($x +as$B=>$Lc)$b[]=array($Lc["type"],$B,"DROP");if(!$b)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),lang(189),alter_indexes($a,$b));}page_header(lang(141),$m,array("table"=>$a),h($a));$Zc=array_keys($o);if($_POST["add"]){foreach($K["indexes"]as$y=>$w){if($w["columns"][count($w["columns"])]!="")$K["indexes"][$y]["columns"][]="";}$w=end($K["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$K["indexes"][]=array("columns"=>array(1=>""));}if(!$K){foreach($x +as$y=>$w){$x[$y]["name"]=$y;$x[$y]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$K["indexes"]=$x;}$Se=(JUSH=="sql"||JUSH=="mssql");$ei=($_POST?$_POST["options"]:get_setting("index_options"));echo'

    - +
    - -';if($Oe){echo"
    Index-Typ -Spalte (Länge) -Name - +',lang(190);$Ud=" class='idxopts".($ei?"":" hidden")."'";if($be)echo"".lang(191).doc_link(array('sql'=>'create-index.html#create-index-storage-engine-index-types','mariadb'=>'storage-engine-index-types/','pgsql'=>'indexes-types.html',));echo'',lang(192).($Se?" (".lang(193).")":"");if($Se||support("descidx"))echo +checkbox("options",1,$ei,lang(113),"indexOptionsShow(this.checked)","jsonly")."\n";echo'',lang(194);if(support("partial_indexes"))echo"".lang(195);echo'
    PRIMARY";foreach($Oe["columns"]as$z=>$d){echo -select_input(" disabled",$n,$d)," ";}echo"\n";}$Zc=1;foreach($L["indexes"]as$w){if(!$_POST["drop_col"]||$Zc!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$Zc][type]",array(-1=>"")+$Oc,$w["type"],($Zc==count($L["indexes"])?"indexesAddRow.call(this);":1),"label-type"),"";ksort($w["columns"]);$u=1;foreach($w["columns"]as$z=>$d){echo"".select_input(" name='indexes[$Zc][columns][$u]' title='".'Spalte'."'",($n?array_combine($n,$n):$n),$d,"partial(".($u==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape($y=="sql"?"":$_GET["indexes"]."_")."')"),($y=="sql"||$y=="mssql"?"":""),(support("descidx")?checkbox("indexes[$Zc][descs][$u]",1,$w["descs"][$z],'absteigend'):"")," ";$u++;}echo"\n","".script("qsl('input').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$Zc++;}echo'
    +';if($G){echo"
    PRIMARY";foreach($G["columns"]as$y=>$d)echo +select_input(" disabled",$Zc,$d)," ";echo"\n";}$_e=1;foreach($K["indexes"]as$w){if(!$_POST["drop_col"]||$_e!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$_e][type]",array(-1=>"")+$ee,$w["type"],($_e==count($K["indexes"])?"indexesAddRow.call(this);":""),"label-type");if($be)echo"".html_select("indexes[$_e][algorithm]",array_merge(array(""),$be),$w['algorithm'],"label-algorithm");echo"";ksort($w["columns"]);$t=1;foreach($w["columns"]as$y=>$d){echo"".select_input(" name='indexes[$_e][columns][$t]' title='".lang(49)."'",($o&&($d==""||$o[$d])?array_combine($Zc,$Zc):array()),$d,"partial(".($t==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape(JUSH=="sql"?"":$_GET["indexes"]."_")."')"),"",($Se?"":""),(support("descidx")?checkbox("indexes[$_e][descs][$t]",1,idx($w["descs"],$y),lang(60)):"")," ";$t++;}echo"\n";if(support("partial_indexes"))echo"\n";echo"".icon("cross","drop_col[$_e]","x",lang(117)).script("qsl('button').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$_e++;}echo'

    - - - -';}elseif(isset($_GET["database"])){$L=$_POST;if($_POST&&!$l&&!isset($_POST["add_x"])){$F=trim($L["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),'Datenbank wurde entfernt.',drop_databases(array(DB)));}elseif(DB!==$F){if(DB!=""){$_GET["db"]=$F;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($F),'Datenbank wurde umbenannt.',rename_database($F,$L["collation"]));}else{$i=explode("\n",str_replace("\r","",$F));$Qf=true;$hd="";foreach($i -as$j){if(count($i)==1||$j!=""){if(!create_database($j,$L["collation"]))$Qf=false;$hd=$j;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($hd),'Datenbank wurde erstellt.',$Qf);}}else{if(!$L["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($F).(preg_match('~^[a-z0-9_]+$~i',$L["collation"])?" COLLATE $L[collation]":""),substr(ME,0,-1),'Datenbank wurde geändert.');}}page_header(DB!=""?'Datenbank ändern':'Datenbank erstellen',$l,array(),h(DB));$Pa=collations();$F=DB;if($_POST)$F=$L["name"];elseif(DB!="")$L["collation"]=db_collation(DB,$Pa);elseif($y=="sql"){foreach(get_vals("SHOW GRANTS")as$vc){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vc,$C)&&$C[1]){$F=stripcslashes(idf_unescape("`$C[2]`"));break;}}}echo' + +',input_token(),' +';}elseif(isset($_GET["database"])){$K=$_POST;if($_POST&&!$m&&!$_POST["add"]){$B=trim($K["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),lang(196),drop_databases(array(DB)));}elseif(DB!==$B){if(DB!=""){$_GET["db"]=$B;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($B),lang(197),rename_database($B,$K["collation"]));}else{$j=explode("\n",str_replace("\r","",$B));$xi=true;$Le="";foreach($j +as$k){if(count($j)==1||$k!=""){if(!create_database($k,$K["collation"]))$xi=false;$Le=$k;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($Le),lang(198),$xi);}}else{if(!$K["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($B).(preg_match('~^[a-z0-9_]+$~i',$K["collation"])?" COLLATE $K[collation]":""),substr(ME,0,-1),lang(199));}}page_header(DB!=""?lang(68):lang(121),$m,array(),h(DB));$lb=collations();$B=DB;if($_POST)$B=$K["name"];elseif(DB!="")$K["collation"]=db_collation(DB,$lb);elseif(JUSH=="sql"){foreach(get_vals("SHOW GRANTS")as$vd){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vd,$A)&&$A[1]){$B=stripcslashes(idf_unescape("`$A[2]`"));break;}}}echo'

    -',($_POST["add_x"]||strpos($F,"\n")?'
    ':'')."\n".($Pa?html_select("collation",array(""=>"(".'Kollation'.")")+$Pa,$L["collation"]).'':""),script("focus(qs('#name'));"),' -';if(DB!="")echo"".confirm(sprintf('Drop %s?',DB))."\n";elseif(!$_POST["add_x"]&&$_GET["db"]=="")echo"\n";echo' -

    -';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$F=$_GET["name"];$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){$D=($_POST["drop"]?'Fremdschlüssel wurde entfernt.':($F!=""?'Fremdschlüssel wurde geändert.':'Fremdschlüssel wurde erstellt.'));$B=ME."table=".urlencode($a);if(!$_POST["drop"]){$L["source"]=array_filter($L["source"],'strlen');ksort($L["source"]);$dg=array();foreach($L["source"]as$z=>$X)$dg[$z]=$L["target"][$z];$L["target"]=$dg;}if($y=="sqlite")queries_redirect($B,$D,recreate_table($a,$a,array(),array(),array(" $F"=>($_POST["drop"]?"":" ".format_foreign_key($L)))));else{$oa="ALTER TABLE ".table($a);$_b="\nDROP ".($y=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($F);if($_POST["drop"])query_redirect($oa.$_b,$B,$D);else{query_redirect($oa.($F!=""?"$_b,":"")."\nADD".format_foreign_key($L),$B,$D);$l='Quell- und Zielspalten müssen vom gleichen Datentyp sein, es muss unter den Zielspalten ein Index existieren und die referenzierten Daten müssen existieren.'."
    $l";}}}page_header('Fremdschlüssel',$l,array("table"=>$a),h($a));if($_POST){ksort($L["source"]);if($_POST["add"])$L["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$L["target"]=array();}elseif($F!=""){$q=foreign_keys($a);$L=$q[$F];$L["source"][]="";}else{$L["table"]=$a;$L["source"]=array("");}echo' +',($_POST["add"]||strpos($B,"\n")?'
    ':'')."\n".($lb?html_select("collation",array(""=>"(".lang(107).")")+$lb,$K["collation"]).doc_link(array('sql'=>"charset-charsets.html",'mariadb'=>"supported-character-sets-and-collations/",'mssql'=>"relational-databases/system-functions/sys-fn-helpcollations-transact-sql",)):""),' +';if(DB!="")echo"".confirm(lang(184,DB))."\n";elseif(!$_POST["add"]&&$_GET["db"]=="")echo +icon("plus","add[0]","+",lang(114))."\n";echo +input_token(),' +';}elseif(isset($_GET["scheme"])){$K=$_POST;if($_POST&&!$m){$_=preg_replace('~ns=[^&]*&~','',ME)."ns=";if($_POST["drop"])query_redirect("DROP SCHEMA ".idf_escape($_GET["ns"]),$_,lang(200));else{$B=trim($K["name"]);$_ +.=urlencode($B);if($_GET["ns"]=="")query_redirect("CREATE SCHEMA ".idf_escape($B),$_,lang(201));elseif($_GET["ns"]!=$B)query_redirect("ALTER SCHEMA ".idf_escape($_GET["ns"])." RENAME TO ".idf_escape($B),$_,lang(202));else +redirect($_);}}page_header($_GET["ns"]!=""?lang(69):lang(70),$m);if(!$K)$K["name"]=$_GET["ns"];echo' +
    +

    + +';if($_GET["ns"]!="")echo"".confirm(lang(184,$_GET["ns"]))."\n";echo +input_token(),'

    +';}elseif(isset($_GET["call"])){$ca=($_GET["name"]?:$_GET["call"]);page_header(lang(203).": ".h($ca),$m);$Dh=routine($_GET["call"],(isset($_GET["callf"])?"FUNCTION":"PROCEDURE"));$Xd=array();$ug=array();foreach($Dh["fields"]as$t=>$n){if(substr($n["inout"],-3)=="OUT"&&JUSH=='sql')$ug[$t]="@".idf_escape($n["field"])." AS ".idf_escape($n["field"]);if(!$n["inout"]||substr($n["inout"],0,2)=="IN")$Xd[]=$t;}if(!$m&&$_POST){$Ua=array();foreach($Dh["fields"]as$y=>$n){$X="";if(in_array($y,$Xd)){$X=process_input($n);if($X===false)$X="''";if(isset($ug[$y]))connection()->query("SET @".idf_escape($n["field"])." = $X");}if(isset($ug[$y]))$Ua[]="@".idf_escape($n["field"]);elseif(in_array($y,$Xd))$Ua[]=$X;}$H=(isset($_GET["callf"])?"SELECT ":"CALL ").(idx($Dh["returns"],"type")=="record"?"* FROM ":"").table($ca)."(".implode(", ",$Ua).")";$si=microtime(true);$I=connection()->multi_query($H);$qa=connection()->affected_rows;echo +adminer()->selectQuery($H,$si,!$I);if(!$I)echo"

    ".error()."\n";else{$h=connect();if($h)$h->select_db(DB);do{$I=connection()->store_result();if(is_object($I))print_select_result($I,$h);else +echo"

    ".lang(204,$qa)." ".@date("H:i:s")."\n";}while(connection()->next_result());if($ug)print_select_result(connection()->query("SELECT ".implode(", ",$ug)));}}echo'

    -';$Ff=array_keys(fields($a));if($L["db"]!="")$f->select_db($L["db"]);if($L["ns"]!="")set_schema($L["ns"]);$df=array_keys(array_filter(table_status('',true),'fk_support'));$dg=array_keys(fields(in_array($L["table"],$df)?$L["table"]:reset($df)));$Xd="this.form['change-js'].value = '1'; this.form.submit();";echo"

    ".'Zieltabelle'.": ".html_select("table",$df,$L["table"],$Xd)."\n";if($y=="pgsql")echo'Schema'.": ".html_select("ns",$b->schemas(),$L["ns"]!=""?$L["ns"]:$_GET["ns"],$Xd);elseif($y!="sqlite"){$mb=array();foreach($b->databases()as$j){if(!information_schema($j))$mb[]=$j;}echo'DB'.": ".html_select("db",$mb,$L["db"]!=""?$L["db"]:$_GET["db"],$Xd);}echo' -

    - - -';$Zc=0;foreach($L["source"]as$z=>$X){echo"","
    UrsprungZiel
    ".html_select("source[".(+$z)."]",array(-1=>"")+$Ff,$X,($Zc==count($L["source"])-1?"foreignAddRow.call(this);":1),"label-source"),"".html_select("target[".(+$z)."]",$dg,$L["target"][$z],1,"label-target");$Zc++;}echo'
    +';if($Xd){echo"\n";foreach($Xd +as$y){$n=$Dh["fields"][$y];$B=$n["field"];echo"
    ".adminer()->fieldName($n);$Y=idx($_POST["fields"],$B);if($Y!=""){if($n["type"]=="set")$Y=implode(",",$Y);}input($n,$Y,idx($_POST["function"],$B,""));echo"\n";}echo"
    \n";}echo'

    + +',input_token(),'

    + +
    +';function
    +pre_tr($Hh){return
    +preg_replace('~^~m','',preg_replace('~\|~','',preg_replace('~\|$~m',"",rtrim($Hh))));}$R='(\+--[-+]+\+\n)';$K='(\| .* \|\n)';echo
    +preg_replace_callback("~^$R?$K$R?($K*)$R?~m",function($A){$dd=pre_tr($A[2]);return"\n".($A[1]?"$dd\n":$dd).pre_tr($A[4])."\n
    ";},preg_replace('~(\n( -|mysql)> )(.+)~',"\\1\\3",preg_replace('~(.+)\n---+\n~',"\\1\n",h($Dh['comment']))));echo'
    +';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$B=$_GET["name"];$K=$_POST;if($_POST&&!$m&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){if(!$_POST["drop"]){$K["source"]=array_filter($K["source"],'strlen');ksort($K["source"]);$Mi=array();foreach($K["source"]as$y=>$X)$Mi[$y]=$K["target"][$y];$K["target"]=$Mi;}if(JUSH=="sqlite")$I=recreate_table($a,$a,array(),array(),array(" $B"=>($K["drop"]?"":" ".format_foreign_key($K))));else{$b="ALTER TABLE ".table($a);$I=($B==""||queries("$b DROP ".(JUSH=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($B)));if(!$K["drop"])$I=queries("$b ADD".format_foreign_key($K));}queries_redirect(ME."table=".urlencode($a),($K["drop"]?lang(205):($B!=""?lang(206):lang(207))),$I);if(!$K["drop"])$m=lang(208);}page_header(lang(209),$m,array("table"=>$a),h($a));if($_POST){ksort($K["source"]);if($_POST["add"])$K["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$K["target"]=array();}elseif($B!=""){$md=foreign_keys($a);$K=$md[$B];$K["source"][]="";}else{$K["table"]=$a;$K["source"]=array("");}echo' +
    +';$ji=array_keys(fields($a));if($K["db"]!="")connection()->select_db($K["db"]);if($K["ns"]!=""){$qg=get_schema();set_schema($K["ns"]);}$ph=array_keys(array_filter(table_status('',true),'Adminer\fk_support'));$Mi=array_keys(fields(in_array($K["table"],$ph)?$K["table"]:reset($ph)));$ag="this.form['change-js'].value = '1'; this.form.submit();";echo"

    \n";if(support("scheme")){$Kh=array_filter(adminer()->schemas(),function($Jh){return!preg_match('~^information_schema$~i',$Jh);});echo"";if($K["ns"]!="")set_schema($qg);}elseif(JUSH!="sqlite"){$Sb=array();foreach(adminer()->databases()as$k){if(!information_schema($k))$Sb[]=$k;}echo"";}echo +input_hidden("change-js"),'

    + + +';$_e=0;foreach($K["source"]as$y=>$X){echo"","
    ',lang(143),'',lang(144),'
    ".html_select("source[".(+$y)."]",array(-1=>"")+$ji,$X,($_e==count($K["source"])-1?"foreignAddRow.call(this);":""),"label-source"),"".html_select("target[".(+$y)."]",$Mi,idx($K["target"],$y),"","label-target");$_e++;}echo'

    -ON DELETE: ',html_select("on_delete",array(-1=>"")+explode("|",$Wd),$L["on_delete"]),' ON UPDATE: ',html_select("on_update",array(-1=>"")+explode("|",$Wd),$L["on_update"]),'','

    - -

    -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["view"])){$a=$_GET["view"];$L=$_POST;$me="VIEW";if($y=="pgsql"&&$a!=""){$Mf=table_status($a);$me=strtoupper($Mf["Engine"]);}if($_POST&&!$l){$F=trim($L["name"]);$pa=" AS\n$L[select]";$B=ME."table=".urlencode($F);$D='View wurde geändert.';$V=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$F&&$y!="sqlite"&&$V=="VIEW"&&$me=="VIEW")query_redirect(($y=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($F).$pa,$B,$D);else{$fg=$F."_adminer_".uniqid();drop_create("DROP $me ".table($a),"CREATE $V ".table($F).$pa,"DROP $V ".table($F),"CREATE $V ".table($fg).$pa,"DROP $V ".table($fg),($_POST["drop"]?substr(ME,0,-1):$B),'View wurde entfernt.',$D,'View wurde erstellt.',$a,$F);}}if(!$_POST&&$a!=""){$L=view($a);$L["name"]=$a;$L["materialized"]=($me!="VIEW");if(!$l)$l=error();}page_header(($a!=""?'View ändern':'View erstellen'),$l,array("table"=>$a),h($a));echo' + + +',(DRIVER==='pgsql'?html_select("deferrable",array('NOT DEFERRABLE','DEFERRABLE','DEFERRABLE INITIALLY DEFERRED'),$K["deferrable"]).' ':''),doc_link(array('sql'=>"innodb-foreign-key-constraints.html",'mariadb'=>"foreign-keys/",'pgsql'=>"sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES",'mssql'=>"t-sql/statements/create-table-transact-sql",'oracle'=>"SQLRF01111",)),'

    + +

    +';if($B!="")echo'',confirm(lang(184,$B));echo +input_token(),' +';}elseif(isset($_GET["view"])){$a=$_GET["view"];$K=$_POST;$rg="VIEW";if(JUSH=="pgsql"&&$a!=""){$P=table_status1($a);$rg=strtoupper($P["Engine"]);}if($_POST&&!$m){$B=trim($K["name"]);$ya=" AS\n$K[select]";$We=ME."table=".urlencode($B);$qf=lang(213);$U=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$B&&JUSH!="sqlite"&&$U=="VIEW"&&$rg=="VIEW")query_redirect((JUSH=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($B).$ya,$We,$qf);else{$Oi=$B."_adminer_".uniqid();drop_create("DROP $rg ".table($a),"CREATE $U ".table($B).$ya,"DROP $U ".table($B),"CREATE $U ".table($Oi).$ya,"DROP $U ".table($Oi),($_POST["drop"]?substr(ME,0,-1):$We),lang(214),$qf,lang(215),$a,$B);}}if(!$_POST&&$a!=""){$K=view($a);$K["name"]=$a;$K["materialized"]=($rg!="VIEW");if(!$m)$m=error();}page_header(($a!=""?lang(44):lang(216)),$m,array("table"=>$a),h($a));echo'

    -

    Name: -',(support("materializedview")?" ".checkbox("materialized",1,$L["materialized"],'Materialized view'):""),'

    ';textarea("select",$L["select"]);echo'

    - -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}echo' -

    -';}elseif(isset($_GET["trigger"])){$a=$_GET["trigger"];$F=$_GET["name"];$_g=trigger_options();$L=(array)trigger($F,$a)+array("Trigger"=>$a."_bi");if($_POST){if(!$l&&in_array($_POST["Timing"],$_g["Timing"])&&in_array($_POST["Event"],$_g["Event"])&&in_array($_POST["Type"],$_g["Type"])){$Vd=" ON ".table($a);$_b="DROP TRIGGER ".idf_escape($F).($y=="pgsql"?$Vd:"");$B=ME."table=".urlencode($a);if($_POST["drop"])query_redirect($_b,$B,'Trigger wurde entfernt.');else{if($F!="")queries($_b);queries_redirect($B,($F!=""?'Trigger wurde geändert.':'Trigger wurde erstellt.'),queries(create_trigger($Vd,$_POST)));if($F!="")queries(create_trigger($Vd,$L+array("Type"=>reset($_g["Type"]))));}}$L=$_POST;}page_header(($F!=""?'Trigger ändern'.": ".h($F):'Trigger erstellen'),$l,array("table"=>$a));echo' +

    ',lang(194),': +',(support("materializedview")?" ".checkbox("materialized",1,$K["materialized"],lang(137)):""),'

    ';textarea("select",$K["select"]);echo'

    + +';if($a!="")echo'',confirm(lang(184,$a));echo +input_token(),' +';}elseif(isset($_GET["event"])){$aa=$_GET["event"];$re=array("YEAR","QUARTER","MONTH","DAY","HOUR","MINUTE","WEEK","SECOND","YEAR_MONTH","DAY_HOUR","DAY_MINUTE","DAY_SECOND","HOUR_MINUTE","HOUR_SECOND","MINUTE_SECOND");$ti=array("ENABLED"=>"ENABLE","DISABLED"=>"DISABLE","SLAVESIDE_DISABLED"=>"DISABLE ON SLAVE");$K=$_POST;if($_POST&&!$m){if($_POST["drop"])query_redirect("DROP EVENT ".idf_escape($aa),substr(ME,0,-1),lang(217));elseif(in_array($K["INTERVAL_FIELD"],$re)&&isset($ti[$K["STATUS"]])){$Ih="\nON SCHEDULE ".($K["INTERVAL_VALUE"]?"EVERY ".q($K["INTERVAL_VALUE"])." $K[INTERVAL_FIELD]".($K["STARTS"]?" STARTS ".q($K["STARTS"]):"").($K["ENDS"]?" ENDS ".q($K["ENDS"]):""):"AT ".q($K["STARTS"]))." ON COMPLETION".($K["ON_COMPLETION"]?"":" NOT")." PRESERVE";queries_redirect(substr(ME,0,-1),($aa!=""?lang(218):lang(219)),queries(($aa!=""?"ALTER EVENT ".idf_escape($aa).$Ih.($aa!=$K["EVENT_NAME"]?"\nRENAME TO ".idf_escape($K["EVENT_NAME"]):""):"CREATE EVENT ".idf_escape($K["EVENT_NAME"]).$Ih)."\n".$ti[$K["STATUS"]]." COMMENT ".q($K["EVENT_COMMENT"]).rtrim(" DO\n$K[EVENT_DEFINITION]",";").";"));}}page_header(($aa!=""?lang(220).": ".h($aa):lang(221)),$m);if(!$K&&$aa!=""){$L=get_rows("SELECT * FROM information_schema.EVENTS WHERE EVENT_SCHEMA = ".q(DB)." AND EVENT_NAME = ".q($aa));$K=reset($L);}echo' +

    + +
    ',lang(194),' +
    ',lang(222),' +
    ',lang(223),' +
    ',lang(224),' ',html_select("INTERVAL_FIELD",$re,$K["INTERVAL_FIELD"]),'
    ',lang(124),'',html_select("STATUS",$ti,$K["STATUS"]),'
    ',lang(51),' +
    ',checkbox("ON_COMPLETION","PRESERVE",$K["ON_COMPLETION"]=="PRESERVE",lang(225)),'
    +

    ';textarea("EVENT_DEFINITION",$K["EVENT_DEFINITION"]);echo'

    + +';if($aa!="")echo'',confirm(lang(184,$aa));echo +input_token(),'

    +';}elseif(isset($_GET["procedure"])){$ca=($_GET["name"]?:$_GET["procedure"]);$Dh=(isset($_GET["function"])?"FUNCTION":"PROCEDURE");$K=$_POST;$K["fields"]=(array)$K["fields"];if($_POST&&!process_fields($K["fields"])&&!$m){$ng=routine($_GET["procedure"],$Dh);$Oi="$K[name]_adminer_".uniqid();foreach($K["fields"]as$y=>$n){if($n["field"]=="")unset($K["fields"][$y]);}drop_create("DROP $Dh ".routine_id($ca,$ng),create_routine($Dh,$K),"DROP $Dh ".routine_id($K["name"],$K),create_routine($Dh,array("name"=>$Oi)+$K),"DROP $Dh ".routine_id($Oi,$K),substr(ME,0,-1),lang(226),lang(227),lang(228),$ca,$K["name"]);}page_header(($ca!=""?(isset($_GET["function"])?lang(229):lang(230)).": ".h($ca):(isset($_GET["function"])?lang(231):lang(232))),$m);if(!$_POST){if($ca=="")$K["language"]="sql";else{$K=routine($_GET["procedure"],$Dh);$K["name"]=$ca;}}$lb=get_vals("SHOW CHARACTER SET");sort($lb);$Eh=routine_languages();echo($lb?"".optionlist($lb)."":""),'
    - -
    Zeitpunkt',html_select("Timing",$_g["Timing"],$L["Timing"],"triggerChange(/^".preg_quote($a,"/")."_[ba][iud]$/, '".js_escape($a)."', this.form);"),'
    Ereignis',html_select("Event",$_g["Event"],$L["Event"],"this.form['Timing'].onchange();"),(in_array("UPDATE OF",$_g["Event"])?" ":""),'
    Typ',html_select("Type",$_g["Type"],$L["Type"]),'
    -

    Name: -',script("qs('#form')['Timing'].onchange();"),'

    ';textarea("Statement",$L["Statement"]);echo'

    - -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["select"])){$a=$_GET["select"];$S=table_status1($a);$x=indexes($a);$n=fields($a);$q=column_foreign_keys($a);$Td=$S["Oid"];parse_str($_COOKIE["adminer_import"],$ja);$lf=array();$e=array();$ig=null;foreach($n -as$z=>$m){$F=$b->fieldName($m);if(isset($m["privileges"]["select"])&&$F!=""){$e[$z]=html_entity_decode(strip_tags($F),ENT_QUOTES);if(is_shortable($m))$ig=$b->selectLengthProcess();}$lf+=$m["privileges"];}list($N,$t)=$b->selectColumnsProcess($e,$x);$Wc=count($t)selectSearchProcess($n,$x);$fe=$b->selectOrderProcess($n,$x);$_=$b->selectLimitProcess();if($_GET["val"]&&is_ajax()){header("Content-Type: text/plain; charset=utf-8");foreach($_GET["val"]as$Gg=>$L){$pa=convert_field($n[key($L)]);$N=array($pa?$pa:idf_escape(key($L)));$Z[]=where_check($Gg,$n);$K=$k->select($a,$N,$Z,$N);if($K)echo -reset($K->fetch_row());}exit;}$Oe=$Ig=null;foreach($x -as$w){if($w["type"]=="PRIMARY"){$Oe=array_flip($w["columns"]);$Ig=($N?$Oe:array());foreach($Ig -as$z=>$X){if(in_array(idf_escape($z),$N))unset($Ig[$z]);}break;}}if($Td&&!$Oe){$Oe=$Ig=array($Td=>0);$x[]=array("type"=>"PRIMARY","columns"=>array($Td));}if($_POST&&!$l){$fh=$Z;if(!$_POST["all"]&&is_array($_POST["check"])){$Ga=array();foreach($_POST["check"]as$Ea)$Ga[]=where_check($Ea,$n);$fh[]="((".implode(") OR (",$Ga)."))";}$fh=($fh?"\nWHERE ".implode(" AND ",$fh):"");if($_POST["export"]){cookie("adminer_import","output=".urlencode($_POST["output"])."&format=".urlencode($_POST["format"]));dump_headers($a);$b->dumpTable($a,"");$tc=($N?implode(", ",$N):"*").convert_fields($e,$n,$N)."\nFROM ".table($a);$xc=($t&&$Wc?"\nGROUP BY ".implode(", ",$t):"").($fe?"\nORDER BY ".implode(", ",$fe):"");if(!is_array($_POST["check"])||$Oe)$I="SELECT $tc$fh$xc";else{$Eg=array();foreach($_POST["check"]as$X)$Eg[]="(SELECT".limit($tc,"\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n).$xc,1).")";$I=implode(" UNION ALL ",$Eg);}$b->dumpData($a,"table",$I);exit;}if(!$b->selectEmailProcess($Z,$q)){if($_POST["save"]||$_POST["delete"]){$J=true;$ka=0;$P=array();if(!$_POST["delete"]){foreach($e -as$F=>$X){$X=process_input($n[$F]);if($X!==null&&($_POST["clone"]||$X!==false))$P[idf_escape($F)]=($X!==false?$X:idf_escape($F));}}if($_POST["delete"]||$P){if($_POST["clone"])$I="INTO ".table($a)." (".implode(", ",array_keys($P)).")\nSELECT ".implode(", ",$P)."\nFROM ".table($a);if($_POST["all"]||($Oe&&is_array($_POST["check"]))||$Wc){$J=($_POST["delete"]?$k->delete($a,$fh):($_POST["clone"]?queries("INSERT $I$fh"):$k->update($a,$P,$fh)));$ka=$f->affected_rows;}else{foreach((array)$_POST["check"]as$X){$eh="\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n);$J=($_POST["delete"]?$k->delete($a,$eh,1):($_POST["clone"]?queries("INSERT".limit1($a,$I,$eh)):$k->update($a,$P,$eh,1)));if(!$J)break;$ka+=$f->affected_rows;}}}$D=sprintf('%d Artikel betroffen.',$ka);if($_POST["clone"]&&$J&&$ka==1){$id=last_id();if($id)$D=sprintf('Datensatz%s wurde eingefügt.'," $id");}queries_redirect(remove_from_uri($_POST["all"]&&$_POST["delete"]?"page":""),$D,$J);if(!$_POST["delete"]){edit_form($a,$n,(array)$_POST["fields"],!$_POST["clone"]);page_footer();exit;}}elseif(!$_POST["import"]){if(!$_POST["val"])$l='Ctrl+Klick zum Bearbeiten des Wertes.';else{$J=true;$ka=0;foreach($_POST["val"]as$Gg=>$L){$P=array();foreach($L -as$z=>$X){$z=bracket_escape($z,1);$P[idf_escape($z)]=(preg_match('~char|text~',$n[$z]["type"])||$X!=""?$b->processInput($n[$z],$X):"NULL");}$J=$k->update($a,$P," WHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($Gg,$n),!$Wc&&!$Oe," ");if(!$J)break;$ka+=$f->affected_rows;}queries_redirect(remove_from_uri(),sprintf('%d Artikel betroffen.',$ka),$J);}}elseif(!is_string($jc=get_file("csv_file",true)))$l=upload_error($jc);elseif(!preg_match('~~u',$jc))$l='Die Datei muss UTF-8 kodiert sein.';else{cookie("adminer_import","output=".urlencode($ja["output"])."&format=".urlencode($_POST["separator"]));$J=true;$Qa=array_keys($n);preg_match_all('~(?>"[^"]*"|[^"\r\n]+)+~',$jc,$ud);$ka=count($ud[0]);$k->begin();$xf=($_POST["separator"]=="csv"?",":($_POST["separator"]=="tsv"?"\t":";"));$M=array();foreach($ud[0]as$z=>$X){preg_match_all("~((?>\"[^\"]*\")+|[^$xf]*)$xf~",$X.$xf,$vd);if(!$z&&!array_diff($vd[1],$Qa)){$Qa=$vd[1];$ka--;}else{$P=array();foreach($vd[1]as$u=>$Ma)$P[idf_escape($Qa[$u])]=($Ma==""&&$n[$Qa[$u]]["null"]?"NULL":q(str_replace('""','"',preg_replace('~^"|"$~','',$Ma))));$M[]=$P;}}$J=(!$M||$k->insertUpdate($a,$M,$Oe));if($J)$J=$k->commit();queries_redirect(remove_from_uri("page"),lang(array('%d Datensatz wurde importiert.','%d Datensätze wurden importiert.'),$ka),$J);$k->rollback();}}}$Wf=$b->tableName($S);if(is_ajax()){page_headers();ob_start();}else -page_header('Daten zeigen von'.": $Wf",$l);$P=null;if(isset($lf["insert"])||!support("table")){$P="";foreach((array)$_GET["where"]as$X){if($q[$X["col"]]&&count($q[$X["col"]])==1&&($X["op"]=="="||(!$X["op"]&&!preg_match('~[_%]~',$X["val"]))))$P.="&set".urlencode("[".bracket_escape($X["col"])."]")."=".urlencode($X["val"]);}}$b->selectLinks($S,$P);if(!$e&&support("table"))echo"

    ".'Auswahl der Tabelle fehlgeschlagen'.($n?".":": ".error())."\n";else{echo"

    \n","
    ";hidden_fields_get();echo(DB!=""?''.(isset($_GET["ns"])?'':""):"");echo'',"
    \n";$b->selectColumnsPrint($N,$e);$b->selectSearchPrint($Z,$e,$x);$b->selectOrderPrint($fe,$e,$x);$b->selectLimitPrint($_);$b->selectLengthPrint($ig);$b->selectActionPrint($x);echo"
    \n";$G=$_GET["page"];if($G=="last"){$sc=$f->result(count_rows($a,$Z,$Wc,$t));$G=floor(max(0,$sc-1)/$_);}$sf=$N;$wc=$t;if(!$sf){$sf[]="*";$ab=convert_fields($e,$n,$N);if($ab)$sf[]=substr($ab,2);}foreach($N -as$z=>$X){$m=$n[idf_unescape($X)];if($m&&($pa=convert_field($m)))$sf[$z]="$pa AS $X";}if(!$Wc&&$Ig){foreach($Ig -as$z=>$X){$sf[]=idf_escape($z);if($wc)$wc[]=idf_escape($z);}}$J=$k->select($a,$sf,$Z,$wc,$fe,$_,$G,true);if(!$J)echo"

    ".error()."\n";else{if($y=="mssql"&&$G)$J->seek($_*$G);$Mb=array();echo"

    \n";$M=array();while($L=$J->fetch_assoc()){if($G&&$y=="oracle")unset($L["RNUM"]);$M[]=$L;}if($_GET["page"]!="last"&&$_!=""&&$t&&$Wc&&$y=="sql")$sc=$f->result(" SELECT FOUND_ROWS()");if(!$M)echo"

    ".'Keine Datensätze.'."\n";else{$wa=$b->backwardKeys($a,$Wf);echo"

    ","",script("mixin(qs('#table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true), onkeydown: editingKeydown});"),"".(!$t&&$N?"":"\n";if(is_ajax()){if($_%2==1&&$G%2==1)odd();ob_end_clean();}foreach($b->rowDescriptions($M,$q)as$E=>$L){$Fg=unique_array($M[$E],$x);if(!$Fg){$Fg=array();foreach($M[$E]as$z=>$X){if(!preg_match('~^(COUNT\((\*|(DISTINCT )?`(?:[^`]|``)+`)\)|(AVG|GROUP_CONCAT|MAX|MIN|SUM)\(`(?:[^`]|``)+`\))$~',$z))$Fg[$z]=$X;}}$Gg="";foreach($Fg -as$z=>$X){if(($y=="sql"||$y=="pgsql")&&preg_match('~char|text|enum|set~',$n[$z]["type"])&&strlen($X)>64){$z=(strpos($z,'(')?$z:idf_escape($z));$z="MD5(".($y!='sql'||preg_match("~^utf8~",$n[$z]["collation"])?$z:"CONVERT($z USING ".charset($f).")").")";$X=md5($X);}$Gg.="&".($X!==null?urlencode("where[".bracket_escape($z)."]")."=".urlencode($X):"null%5B%5D=".urlencode($z));}echo"".(!$t&&$N?"":"";}}}if($wa)echo"\n";}if(is_ajax())exit;echo"
    ".script("qs('#all-page').onclick = partial(formCheck, /check/);","")." ".'Ändern'."");$Kd=array();$uc=array();reset($N);$af=1;foreach($M[0]as$z=>$X){if(!isset($Ig[$z])){$X=$_GET["columns"][key($N)];$m=$n[$N?($X?$X["col"]:current($N)):$z];$F=($m?$b->fieldName($m,$af):($X["fun"]?"*":$z));if($F!=""){$af++;$Kd[$z]=$F;$d=idf_escape($z);$Ic=remove_from_uri('(order|desc)[^=]*|page').'&order%5B0%5D='.urlencode($z);$sb="&desc%5B0%5D=1";echo"".script("mixin(qsl('th'), {onmouseover: partial(columnMouse), onmouseout: partial(columnMouse, ' hidden')});",""),'';echo -apply_sql_function($X["fun"],$F)."";echo"";}$uc[$z]=$X["fun"];next($N);}}$od=array();if($_GET["modify"]){foreach($M -as$L){foreach($L -as$z=>$X)$od[$z]=max($od[$z],min(40,strlen(utf8_decode($X))));}}echo($wa?"".'Relationen':"")."
    ".checkbox("check[]",substr($Gg,1),in_array(substr($Gg,1),(array)$_POST["check"])).($Wc||information_schema(DB)?"":" ".'bearbeiten'.""));foreach($L -as$z=>$X){if(isset($Kd[$z])){$m=$n[$z];$X=$k->value($X,$m);if($X!=""&&(!isset($Mb[$z])||$Mb[$z]!=""))$Mb[$z]=(is_mail($X)?$Kd[$z]:"");$A="";if(preg_match('~blob|bytea|raw|file~',$m["type"])&&$X!="")$A=ME.'download='.urlencode($a).'&field='.urlencode($z).$Gg;if(!$A&&$X!==null){foreach((array)$q[$z]as$p){if(count($q[$z])==1||end($p["source"])==$z){$A="";foreach($p["source"]as$u=>$Ff)$A.=where_link($u,$p["target"][$u],$M[$E][$Ff]);$A=($p["db"]!=""?preg_replace('~([?&]db=)[^&]+~','\1'.urlencode($p["db"]),ME):ME).'select='.urlencode($p["table"]).$A;if($p["ns"])$A=preg_replace('~([?&]ns=)[^&]+~','\1'.urlencode($p["ns"]),$A);if(count($p["source"])==1)break;}}}if($z=="COUNT(*)"){$A=ME."select=".urlencode($a);$u=0;foreach((array)$_GET["where"]as$W){if(!array_key_exists($W["col"],$Fg))$A.=where_link($u++,$W["col"],$W["val"],$W["op"]);}foreach($Fg -as$ad=>$W)$A.=where_link($u++,$ad,$W);}$X=select_value($X,$A,$m,$ig);$v=h("val[$Gg][".bracket_escape($z)."]");$Y=$_POST["val"][$Gg][bracket_escape($z)];$Hb=!is_array($L[$z])&&is_utf8($X)&&$M[$E][$z]==$L[$z]&&!$uc[$z];$hg=preg_match('~text|lob~',$m["type"]);echo"".($hg?"":"");}else{$sd=strpos($X,"…");echo" data-text='".($sd?2:($hg?1:0))."'".($Hb?"":" data-warning='".h('Benutzen Sie den Link zum Bearbeiten dieses Wertes.')."'").">$X";$b->backwardKeysPrint($wa,$M[$E]);echo"
    \n","
    \n";}if(!is_ajax()){if($M||$G){$Wb=true;if($_GET["page"]!="last"){if($_==""||(count($M)<$_&&($M||!$G)))$sc=($G?$G*$_:0)+count($M);elseif($y!="sql"||!$Wc){$sc=($Wc?false:found_rows($S,$Z));if($sc$_||$G));if($se){echo(($sc===false?count($M)+1:$sc-$G*$_)>$_?'

    '.'Mehr Daten laden'.''.script("qsl('a').onclick = partial(selectLoadMore, ".(+$_).", '".'Lade'."…');",""):''),"\n";}}echo"

    \n";}if(adminer()->selectImportPrint())echo"

    ","".lang(76)."",script("qsl('a').onclick = partial(toggle, 'import');",""),"";echo +input_token(),"\n",(!$xd&&$M?"":script("tableCheck();"));}}}if(is_ajax()){ob_end_clean();exit;}}elseif(isset($_GET["variables"])){$P=isset($_GET["status"]);page_header($P?lang(124):lang(123));$Oj=($P?adminer()->showStatus():adminer()->showVariables());if(!$Oj)echo"

    ".lang(14)."\n";else{echo"\n";foreach($Oj +as$K){echo"";$y=array_shift($K);echo"
    ".h($y)."";foreach($K +as$X)echo"".nl_br(h($X));}echo"
    \n";}}elseif(isset($_GET["script"])){header("Content-Type: text/javascript; charset=utf-8");if($_GET["script"]=="db"){$_i=array("Data_length"=>0,"Index_length"=>0,"Data_free"=>0);foreach(table_status()as$B=>$S){json_row("Comment-$B",h($S["Comment"]));if(!is_view($S)||preg_match('~materialized~i',$S["Engine"])){foreach(array("Engine","Collation")as$y)json_row("$y-$B",h($S[$y]));foreach($_i+array("Auto_increment"=>0,"Rows"=>0)as$y=>$X){if($S[$y]!=""){$X=format_number($S[$y]);if($X>=0)json_row("$y-$B",($y=="Rows"&&$X&&$S["Engine"]==(JUSH=="pgsql"?"table":"InnoDB")?"~ $X":$X));if(isset($_i[$y]))$_i[$y]+=($S["Engine"]!="InnoDB"||$y!="Data_free"?$S[$y]:0);}elseif(array_key_exists($y,$S))json_row("$y-$B","?");}}}foreach($_i +as$y=>$X)json_row("sum-$y",format_number($X));json_row("");}elseif($_GET["script"]=="kill")connection()->query("KILL ".number($_POST["kill"]));else{foreach(count_tables(adminer()->databases())as$k=>$X){json_row("tables-$k",$X);json_row("size-$k",db_size($k));}json_row("");}exit;}else{$Ki=array_merge((array)$_POST["tables"],(array)$_POST["views"]);if($Ki&&!$m&&!$_POST["search"]){$I=true;$qf="";if(JUSH=="sql"&&$_POST["tables"]&&count($_POST["tables"])>1&&($_POST["drop"]||$_POST["truncate"]||$_POST["copy"]))queries("SET foreign_key_checks = 0");if($_POST["truncate"]){if($_POST["tables"])$I=truncate_tables($_POST["tables"]);$qf=lang(279);}elseif($_POST["move"]){$I=move_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(280);}elseif($_POST["copy"]){$I=copy_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(281);}elseif($_POST["drop"]){if($_POST["views"])$I=drop_views($_POST["views"]);if($I&&$_POST["tables"])$I=drop_tables($_POST["tables"]);$qf=lang(282);}elseif(JUSH=="sqlite"&&$_POST["check"]){foreach((array)$_POST["tables"]as$R){foreach(get_rows("PRAGMA integrity_check(".q($R).")")as$K)$qf +.="".h($R).": ".h($K["integrity_check"])."
    ";}}elseif(JUSH!="sql"){$I=(JUSH=="sqlite"?queries("VACUUM"):apply_queries("VACUUM".($_POST["optimize"]?"":" ANALYZE"),$_POST["tables"]));$qf=lang(283);}elseif(!$_POST["tables"])$qf=lang(11);elseif($I=queries(($_POST["optimize"]?"OPTIMIZE":($_POST["check"]?"CHECK":($_POST["repair"]?"REPAIR":"ANALYZE")))." TABLE ".implode(", ",array_map('Adminer\idf_escape',$_POST["tables"])))){while($K=$I->fetch_assoc())$qf +.="".h($K["Table"]).": ".h($K["Msg_text"])."
    ";}queries_redirect(substr(ME,0,-1),$qf,$I);}page_header(($_GET["ns"]==""?lang(38).": ".h(DB):lang(80).": ".h($_GET["ns"])),$m,true);if(adminer()->homepage()){if($_GET["ns"]!==""){echo"

    ".lang(284)."

    \n";$Ji=tables_list();if(!$Ji)echo"

    ".lang(11)."\n";else{echo"

    \n";if(support("table")){echo"
    ".lang(285)."
    ",html_select("op",adminer()->operators(),idx($_POST,"op",JUSH=="elastic"?"should":"LIKE %%"))," ",script("qsl('input').onkeydown = partialArg(bodyKeydown, 'search');","")," \n","
    \n";if($_POST["search"]&&$_POST["query"]!=""){$_GET["where"][0]["op"]=$_POST["op"];search_tables();}}echo"
    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),'','\n";$T=0;foreach($Ji +as$B=>$U){$Rj=($U!==null&&!preg_match('~table|sequence~i',$U));$u=h("Table-".$B);echo'
    '.script("qs('#check-all').onclick = partial(formCheck, /^(tables|views)\[/);",""),''.lang(139);$e=array("Engine"=>array(lang(286).doc_link(array('sql'=>'storage-engines.html'))));if(collations())$e["Collation"]=array(lang(128).doc_link(array('sql'=>'charset-charsets.html','mariadb'=>'supported-character-sets-and-collations/')));if(function_exists('Adminer\alter_table'))$e["Data_length"]=array(lang(287).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT','oracle'=>'REFRN20286')),"create",lang(45));if(support('indexes'))$e["Index_length"]=array(lang(288).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT')),"indexes",lang(142));$e["Data_free"]=array(lang(289).doc_link(array('sql'=>'show-table-status.html')),"edit",lang(46));if(function_exists('Adminer\alter_table'))$e["Auto_increment"]=array(lang(52).doc_link(array('sql'=>'example-auto-increment.html','mariadb'=>'auto_increment/')),"auto_increment=1&create",lang(45));$e["Rows"]=array(lang(290).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'catalog-pg-class.html#CATALOG-PG-CLASS','oracle'=>'REFRN20286')),"select",lang(42));if(support("comment"))$e["Comment"]=array(lang(51).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-info.html#FUNCTIONS-INFO-COMMENT-TABLE')));foreach($e +as$d)echo"$d[0]";echo"
    '.checkbox(($Rj?"views[]":"tables[]"),$B,in_array("$B",$Ki,true),"","","",$u),''.(support("table")||support("indexes")?"".h($B).'':h($B));if($Rj&&!preg_match('~materialized~i',$U)){$Wi=lang(138);echo''.(support("view")?"$Wi":$Wi),'?';}else{foreach($e +as$y=>$d){$u=" id='$y-".h($B)."'";echo($d[1]?"?":"");}$T++;}echo"\n";}echo"
    ".lang(263,count($Ji)),"".h(JUSH=="sql"?get_val("SELECT @@default_storage_engine"):""),"".h(db_collation(DB,collations()));foreach(array("Data_length","Index_length","Data_free")as$y)echo($e[$y]?"":"");echo"\n","
    \n",script("ajaxSetHtml('".js_escape(ME)."script=db');"),"
    \n";if(!information_schema(DB)){$Lj=" ".on_help("'VACUUM'");$eg=" ".on_help(JUSH=="sql"?"'OPTIMIZE TABLE'":"'VACUUM OPTIMIZE'");$bh=(JUSH=="sqlite"?$Lj." ".on_help("'PRAGMA integrity_check'"):(JUSH=="pgsql"?$Lj.$eg:(JUSH=="sql"?" ".on_help("'ANALYZE TABLE'").$eg." ".on_help("'CHECK TABLE'")." ".on_help("'REPAIR TABLE'"):""))).(function_exists('Adminer\truncate_tables')?" ".on_help(JUSH=="sqlite"?"'DELETE'":"'TRUNCATE".(JUSH=="pgsql"?"'":" TABLE'")).confirm():"").(function_exists('Adminer\drop_tables')?"".on_help("'DROP TABLE'").confirm():"");echo($bh?"\n";}echo"
    \n",script("tableCheck();");}echo(function_exists('Adminer\alter_table')?"

    ".lang(73)."

    \n";$Fh=routines();if($Fh){echo"\n",'\n";foreach($Fh +as$K){$B=($K["SPECIFIC_NAME"]==$K["ROUTINE_NAME"]?"":"&name=".urlencode($K["ROUTINE_NAME"]));echo'','
    '.lang(194).''.lang(50).''.lang(233)."
    '.h($K["ROUTINE_NAME"]).'',''.h($K["ROUTINE_TYPE"]),''.h($K["DTD_IDENTIFIER"]),''.lang(145)."";}echo"
    \n";}echo'

    ".lang(74)."

    \n";$Yh=get_vals("SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = current_schema() ORDER BY sequence_name");if($Yh){echo"\n","\n";foreach($Yh +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(6)."

    \n";$Ij=types();if($Ij){echo"\n","\n";foreach($Ij +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(75)."

    \n";$L=get_rows("SHOW EVENTS");if($L){echo"\n","\n";foreach($L +as$K)echo"","
    ".lang(194)."".lang(301)."".lang(222)."".lang(223)."
    ".h($K["Name"]),"".($K["Execute at"]?lang(302)."".$K["Execute at"]:lang(224)." ".$K["Interval value"]." ".$K["Interval field"]."$K[Starts]"),"$K[Ends]",''.lang(145).'';echo"
    \n";$Hc=get_val("SELECT @@event_scheduler");if($Hc&&$Hc!="ON")echo"

    event_scheduler: ".h($Hc)."\n";}echo'

    '.'Attention : ne l\'utilisez pas dans un environnement de production !'.'
    ',"\n",'',$b->loginFormField('db','
    '.'Base de données'.'',''."\n"),"
    \n","

    \n";return -true;}function -login($rd,$_e){return -true;}}function -adminer_object(){$Ge=array(new -FCSqliteConnectionWithoutCredentials());return -new -AdminerPlugin($Ge);}function -adminer_errors($Rb,$Tb){return!!preg_match('~^(Trying to access array offset on value of type null|Undefined array key)~',$Tb);}error_reporting(6135);set_error_handler('adminer_errors',E_WARNING);$kc=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($kc||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$Hg=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($Hg)$$X=$Hg;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function -connection(){global$f;return$f;}function -adminer(){global$b;return$b;}function -version(){global$da;return$da;}function -idf_unescape($Kc){if(!preg_match('~^[`\'"]~',$Kc))return$Kc;$hd=substr($Kc,-1);return -str_replace($hd.$hd,$hd,substr($Kc,1,-1));}function +* @version 5.4.2 +*/namespace +Adminer;const +VERSION="5.4.2";error_reporting(24575);set_error_handler(function($Dc,$Fc){return!!preg_match('~^Undefined (array key|offset|index)~',$Fc);},E_WARNING|E_NOTICE);$bd=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($bd||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$xj=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($xj)$$X=$xj;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function +connection($h=null){return($h?:Db::$instance);}function +adminer(){return +Adminer::$instance;}function +driver(){return +Driver::$instance;}function +connect(){$Hb=adminer()->credentials();$J=Driver::connect($Hb[0],$Hb[1],$Hb[2]);return(is_object($J)?$J:null);}function +idf_unescape($v){if(!preg_match('~^[`\'"[]~',$v))return$v;$Le=substr($v,-1);return +str_replace($Le.$Le,$Le,substr($v,1,-1));}function +q($Q){return +connection()->quote($Q);}function escape_string($X){return substr(q($X),1,-1);}function +idx($xa,$y,$l=null){return($xa&&array_key_exists($y,$xa)?$xa[$y]:$l);}function number($X){return preg_replace('~[^0-9]+~','',$X);}function number_type(){return'((?$W){unset($Te[$z][$ad]);if(is_array($W)){$Te[$z][stripslashes($ad)]=$W;$Te[]=&$Te[$z][stripslashes($ad)];}else$Te[$z][stripslashes($ad)]=($kc?$W:stripslashes($W));}}}}function -bracket_escape($Kc,$ua=false){static$vg=array(':'=>':1',']'=>':2','['=>':3','"'=>':4');return -strtr($Kc,($ua?array_flip($vg):$vg));}function -min_version($Xg,$td="",$g=null){global$f;if(!$g)$g=$f;$yf=$g->server_info;if($td&&preg_match('~([\d.]+)-MariaDB~',$yf,$C)){$yf=$C[1];$Xg=$td;}return(version_compare($yf,$Xg)>=0);}function -charset($f){return(min_version("5.5.3",0,$f)?"utf8mb4":"utf8");}function -script($Ff,$ug="\n"){return"$Ff$ug";}function -script_src($Mg){return"\n";}function -nonce(){return' nonce="'.get_nonce().'"';}function -target_blank(){return' target="_blank" rel="noreferrer noopener"';}function -h($Q){return -str_replace("\0","�",htmlspecialchars($Q,ENT_QUOTES,'utf-8'));}function -nl_br($Q){return -str_replace("\n","
    ",$Q);}function -checkbox($F,$Y,$Fa,$ed="",$Yd="",$Ja="",$fd=""){$K="".($Yd?script("qsl('input').onclick = function () { $Yd };",""):"");return($ed!=""||$Ja?"$K".h($ed)."":$K);}function -optionlist($de,$tf=null,$Qg=false){$K="";foreach($de -as$ad=>$W){$ee=array($ad=>$W);if(is_array($W)){$K.='';$ee=$W;}foreach($ee -as$z=>$X)$K.=''.h($X);if(is_array($W))$K.='';}return$K;}function -html_select($F,$de,$Y="",$Xd=true,$fd=""){if($Xd)return"".(is_string($Xd)?script("qsl('select').onchange = function () { $Xd };",""):"");$K="";foreach($de -as$z=>$X)$K.="";return$K;}function -select_input($ra,$de,$Y="",$Xd="",$Ee=""){$cg=($de?"select":"input");return"<$cg$ra".($de?">

    ","$md",script("qsl('a').onclick = partial(toggle, 'fieldset-$v');",""),"","
    \n";}function -selectOrderPrint($fe,$e,$x){print_fieldset("sort",'Trier',$fe);$u=0;foreach((array)$_GET["order"]as$z=>$X){if($X!=""){echo"
    ".select_input(" name='order[$u]'",$e,$X,"selectFieldChange"),checkbox("desc[$u]",1,isset($_GET["desc"][$z]),'décroissant')."
    \n";$u++;}}echo"
    ".select_input(" name='order[$u]'",$e,"","selectAddRow"),checkbox("desc[$u]",1,false,'décroissant')."
    \n","\n";}function -selectLimitPrint($_){echo"
    ".'Limite'."
    ";echo"",script("qsl('input').oninput = selectFieldChange;",""),"
    \n";}function -selectLengthPrint($ig){if($ig!==null){echo"
    ".'Longueur du texte'."
    ","","
    \n";}}function -selectActionPrint($x){echo"
    ".'Action'."
    ",""," ","\n","var indexColumns = ";$e=array();foreach($x -as$w){$gb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$gb)$e[$gb]=1;}$e[""]=1;foreach($e -as$z=>$X)json_row($z);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
    \n";}function +rowDescriptions(array$L,array$ld){return$L;}function +selectLink($X,array$n){}function +selectVal($X,$_,array$n,$sg){$J=($X===null?"NULL":(preg_match("~char|binary|boolean~",$n["type"])&&!preg_match("~var~",$n["type"])?"$X":(preg_match('~json~',$n["type"])?"$X":$X)));if(is_blob($n)&&!is_utf8($X))$J="".lang(48,strlen($sg))."";return($_?"$J":$J);}function +editVal($X,array$n){return$X;}function +config(){return +array();}function +tableStructurePrint(array$o,$Bi=null){echo"
    \n","\n","\n";$vi=driver()->structuredTypes();foreach($o +as$n){echo"
    ".lang(49)."".lang(50).(support("comment")?"".lang(51):"")."
    ".h($n["field"]);$U=h($n["full_type"]);$c=h($n["collation"]);echo"".(in_array($U,(array)$vi[lang(6)])?"$U":$U.($c&&isset($Bi["Collation"])&&$c!=$Bi["Collation"]?" $c":""))."",($n["null"]?" NULL":""),($n["auto_increment"]?" ".lang(52)."":"");$l=h($n["default"]);echo(isset($n["default"])?" [".($n["generated"]?"$l":$l)."]":""),(support("comment")?"".h($n["comment"]):""),"\n";}echo"
    \n","
    \n";}function +tableIndexesPrint(array$x,array$Bi){$Cg=false;foreach($x +as$B=>$w)$Cg|=!!$w["partial"];echo"\n";$Ub=first(driver()->indexAlgorithms($Bi));foreach($x +as$B=>$w){ksort($w["columns"]);$bh=array();foreach($w["columns"]as$y=>$X)$bh[]="".h($X)."".($w["lengths"][$y]?"(".$w["lengths"][$y].")":"").($w["descs"][$y]?" DESC":"");echo"","
    $w[type]".($Ub&&$w['algorithm']!=$Ub?" ($w[algorithm])":""),"".implode(", ",$bh);if($Cg)echo"".($w['partial']?"WHERE ".h($w['partial']):"");echo"\n";}echo"
    \n";}function +selectColumnsPrint(array$M,array$e){print_fieldset("select",lang(54),$M);$t=0;$M[""]=array();foreach($M +as$y=>$X){$X=idx($_GET["columns"],$y,array());$d=select_input(" name='columns[$t][col]'",$e,$X["col"],($y!==""?"selectFieldChange":"selectAddRow"));echo"
    ".(driver()->functions||driver()->grouping?html_select("columns[$t][fun]",array(-1=>"")+array_filter(array(lang(55)=>driver()->functions,lang(56)=>driver()->grouping)),$X["fun"]).on_help("event.target.value && event.target.value.replace(/ |\$/, '(') + ')'",1).script("qsl('select').onchange = function () { helpClose();".($y!==""?"":" qsl('select, input', this.parentNode).onchange();")." };","")."($d)":$d)."
    \n";$t++;}echo"\n";}function +selectSearchPrint(array$Z,array$e,array$x){print_fieldset("search",lang(57),$Z);foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT")echo"
    (".implode(", ",array_map('Adminer\h',$w["columns"])).") AGAINST"," ",script("qsl('input').oninput = selectFieldChange;",""),(JUSH=='sql'?checkbox("boolean[$t]",1,isset($_GET["boolean"][$t]),"BOOL"):''),"
    \n";}$Va="this.parentNode.firstChild.onchange();";foreach(array_merge((array)$_GET["where"],array(array()))as$t=>$X){if(!$X||("$X[col]$X[val]"!=""&&in_array($X["op"],adminer()->operators())))echo"
    ".select_input(" name='where[$t][col]'",$e,$X["col"],($X?"selectFieldChange":"selectAddRow"),"(".lang(58).")"),html_select("where[$t][op]",adminer()->operators(),$X["op"],$Va),"",script("mixin(qsl('input'), {oninput: function () { $Va }, onkeydown: selectSearchKeydown, onsearch: selectSearchSearch});",""),"
    \n";}echo"\n";}function +selectOrderPrint(array$ig,array$e,array$x){print_fieldset("sort",lang(59),$ig);$t=0;foreach((array)$_GET["order"]as$y=>$X){if($X!=""){echo"
    ".select_input(" name='order[$t]'",$e,$X,"selectFieldChange"),checkbox("desc[$t]",1,isset($_GET["desc"][$y]),lang(60))."
    \n";$t++;}}echo"
    ".select_input(" name='order[$t]'",$e,"","selectAddRow"),checkbox("desc[$t]",1,false,lang(60))."
    \n","\n";}function +selectLimitPrint($z){echo"
    ".lang(61)."
    ","",script("qsl('input').oninput = selectFieldChange;",""),"
    \n";}function +selectLengthPrint($Si){if($Si!==null)echo"
    ".lang(62)."
    ","","
    \n";}function +selectActionPrint(array$x){echo"
    ".lang(63)."
    ",""," ","\n","const indexColumns = ";$e=array();foreach($x +as$w){$Lb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$Lb)$e[$Lb]=1;}$e[""]=1;foreach($e +as$y=>$X)json_row($y);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
    \n";}function selectCommandPrint(){return!information_schema(DB);}function selectImportPrint(){return!information_schema(DB);}function -selectEmailPrint($Lb,$e){}function -selectColumnsProcess($e,$x){global$uc,$yc;$N=array();$t=array();foreach((array)$_GET["columns"]as$z=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],$uc)||in_array($X["fun"],$yc)))){$N[$z]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],$yc))$t[]=$N[$z];}}return -array($N,$t);}function -selectSearchProcess($n,$x){global$f,$k;$K=array();foreach($x -as$u=>$w){if($w["type"]=="FULLTEXT"&&$_GET["fulltext"][$u]!="")$K[]="MATCH (".implode(", ",array_map('idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$u]).(isset($_GET["boolean"][$u])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$z=>$X){if("$X[col]$X[val]"!=""&&in_array($X["op"],$this->operators)){$Me="";$Va=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Nc=process_length($X["val"]);$Va.=" ".($Nc!=""?$Nc:"(NULL)");}elseif($X["op"]=="SQL")$Va=" $X[val]";elseif($X["op"]=="LIKE %%")$Va=" LIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="ILIKE %%")$Va=" ILIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Me="$X[op](".q($X["val"]).", ";$Va=")";}elseif(!preg_match('~NULL$~',$X["op"]))$Va.=" ".$this->processInput($n[$X["col"]],$X["val"]);if($X["col"]!="")$K[]=$Me.$k->convertSearch(idf_escape($X["col"]),$X,$n[$X["col"]]).$Va;else{$Qa=array();foreach($n -as$F=>$m){if((preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$m["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$m["type"]))&&(!preg_match('~date|timestamp~',$m["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"])))$Qa[]=$Me.$k->convertSearch(idf_escape($F),$X,$m).$Va;}$K[]=($Qa?"(".implode(" OR ",$Qa).")":"1 = 0");}}}return$K;}function -selectOrderProcess($n,$x){$K=array();foreach((array)$_GET["order"]as$z=>$X){if($X!="")$K[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$z])?" DESC":"");}return$K;}function -selectLimitProcess(){return(isset($_GET["limit"])?$_GET["limit"]:"50");}function -selectLengthProcess(){return(isset($_GET["text_length"])?$_GET["text_length"]:"100");}function -selectEmailProcess($Z,$pc){return +selectEmailPrint(array$vc,array$e){}function +selectColumnsProcess(array$e,array$x){$M=array();$xd=array();foreach((array)$_GET["columns"]as$y=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],driver()->functions)||in_array($X["fun"],driver()->grouping)))){$M[$y]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],driver()->grouping))$xd[]=$M[$y];}}return +array($M,$xd);}function +selectSearchProcess(array$o,array$x){$J=array();foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT"&&idx($_GET["fulltext"],$t)!="")$J[]="MATCH (".implode(", ",array_map('Adminer\idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$t]).(isset($_GET["boolean"][$t])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$y=>$X){$jb=$X["col"];if("$jb$X[val]"!=""&&in_array($X["op"],adminer()->operators())){$ub=array();foreach(($jb!=""?array($jb=>$o[$jb]):$o)as$B=>$n){$Xg="";$tb=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Xd=process_length($X["val"]);$tb +.=" ".($Xd!=""?$Xd:"(NULL)");}elseif($X["op"]=="SQL")$tb=" $X[val]";elseif(preg_match('~^(I?LIKE) %%$~',$X["op"],$A))$tb=" $A[1] ".adminer()->processInput($n,"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Xg="$X[op](".q($X["val"]).", ";$tb=")";}elseif(!preg_match('~NULL$~',$X["op"]))$tb +.=" ".adminer()->processInput($n,$X["val"]);if($jb!=""||(isset($n["privileges"]["where"])&&(preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$n["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$n["type"]))&&(!preg_match('~date|timestamp~',$n["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"]))))$ub[]=$Xg.driver()->convertSearch(idf_escape($B),$X,$n).$tb;}$J[]=(count($ub)==1?$ub[0]:($ub?"(".implode(" OR ",$ub).")":"1 = 0"));}}return$J;}function +selectOrderProcess(array$o,array$x){$J=array();foreach((array)$_GET["order"]as$y=>$X){if($X!="")$J[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$y])?" DESC":"");}return$J;}function +selectLimitProcess(){return(isset($_GET["limit"])?intval($_GET["limit"]):50);}function +selectLengthProcess(){return(isset($_GET["text_length"])?"$_GET[text_length]":"100");}function +selectEmailProcess(array$Z,array$ld){return false;}function -selectQueryBuild($N,$Z,$t,$fe,$_,$G){return"";}function -messageQuery($I,$jg,$fc=false){global$y,$k;restart_session();$Fc=&get_session("queries");if(!$Fc[$_GET["db"]])$Fc[$_GET["db"]]=array();if(strlen($I)>1e6)$I=preg_replace('~[\x80-\xFF]+$~','',substr($I,0,1e6))."\n…";$Fc[$_GET["db"]][]=array($I,time(),$jg);$Jf="sql-".count($Fc[$_GET["db"]]);$K="".'Requête SQL'."\n";if(!$fc&&($ch=$k->warnings())){$v="warnings-".count($Fc[$_GET["db"]]);$K="".'Warnings'.", $K\n";}return" ".@date("H:i:s").""." $K';}function -editRowPrint($R,$n,$L,$Kg){}function -editFunctions($m){global$Gb;$K=($m["null"]?"NULL/":"");$Kg=isset($_GET["select"])||where($_GET);foreach($Gb -as$z=>$uc){if(!$z||(!isset($_GET["call"])&&$Kg)){foreach($uc -as$Be=>$X){if(!$Be||preg_match("~$Be~",$m["type"]))$K.="/$X";}}if($z&&!preg_match('~set|blob|bytea|raw|file|bool~',$m["type"]))$K.="/SQL";}if($m["auto_increment"]&&!$Kg)$K='Incrément automatique';return -explode("/",$K);}function -editInput($R,$m,$ra,$Y){if($m["type"]=="enum")return(isset($_GET["select"])?" ":"").($m["null"]?" ":"").enum_input("radio",$ra,$m,$Y,0);return"";}function -editHint($R,$m,$Y){return"";}function -processInput($m,$Y,$s=""){if($s=="SQL")return$Y;$F=$m["field"];$K=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$K="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$K=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$K=idf_escape($F)." $s $K";elseif(preg_match('~^[+-] interval$~',$s))$K=idf_escape($F)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)?$Y:$K);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$K="$s(".idf_escape($F).", $K)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$K="$s($K)";return -unconvert_field($m,$K);}function -dumpOutput(){$K=array('text'=>'ouvrir','file'=>'enregistrer');if(function_exists('gzencode'))$K['gz']='gzip';return$K;}function -dumpFormat(){return -array('sql'=>'SQL','csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function -dumpDatabase($j){}function -dumpTable($R,$Pf,$Yc=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($Pf)dump_csv(array_keys(fields($R)));}else{if($Yc==2){$n=array();foreach(fields($R)as$F=>$m)$n[]=idf_escape($F)." $m[full_type]";$h="CREATE TABLE ".table($R)." (".implode(", ",$n).")";}else$h=create_sql($R,$_POST["auto_increment"],$Pf);set_utf8mb4($h);if($Pf&&$h){if($Pf=="DROP+CREATE"||$Yc==1)echo"DROP ".($Yc==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($Yc==1)$h=remove_definer($h);echo"$h;\n\n";}}}function -dumpData($R,$Pf,$I){global$f,$y;$wd=($y=="sqlite"?0:1048576);if($Pf){if($_POST["format"]=="sql"){if($Pf=="TRUNCATE+INSERT")echo -truncate_sql($R).";\n";$n=fields($R);}$J=$f->query($I,1);if($J){$Sc="";$Ca="";$cd=array();$Rf="";$ic=($R!=''?'fetch_assoc':'fetch_row');while($L=$J->$ic()){if(!$cd){$Ug=array();foreach($L -as$X){$m=$J->fetch_field();$cd[]=$m->name;$z=idf_escape($m->name);$Ug[]="$z = VALUES($z)";}$Rf=($Pf=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Ug):"").";\n";}if($_POST["format"]!="sql"){if($Pf=="table"){dump_csv($cd);$Pf="INSERT";}dump_csv($L);}else{if(!$Sc)$Sc="INSERT INTO ".table($R)." (".implode(", ",array_map('idf_escape',$cd)).") VALUES";foreach($L -as$z=>$X){$m=$n[$z];$L[$z]=($X!==null?unconvert_field($m,preg_match(number_type(),$m["type"])&&!preg_match('~\[~',$m["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$pf=($wd?"\n":" ")."(".implode(",\t",$L).")";if(!$Ca)$Ca=$Sc.$pf;elseif(strlen($Ca)+4+strlen($pf)+strlen($Rf)<$wd)$Ca.=",$pf";else{echo$Ca.$Rf;$Ca=$Sc.$pf;}}}if($Ca)echo$Ca.$Rf;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",$f->error)."\n";}}function -dumpFilename($Jc){return -friendly_url($Jc!=""?$Jc:(SERVER!=""?SERVER:"localhost"));}function -dumpHeaders($Jc,$Id=false){$qe=$_POST["output"];$bc=(preg_match('~sql~',$_POST["format"])?"sql":($Id?"tar":"csv"));header("Content-Type: ".($qe=="gz"?"application/x-gzip":($bc=="tar"?"application/x-tar":($bc=="sql"||$qe!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($qe=="gz")ob_start('ob_gzencode',1e6);return$bc;}function +selectQueryBuild(array$M,array$Z,array$xd,array$ig,$z,$D){return"";}function +messageQuery($H,$Ti,$Tc=false){restart_session();$Kd=&get_session("queries");if(!idx($Kd,$_GET["db"]))$Kd[$_GET["db"]]=array();if(strlen($H)>1e6)$H=preg_replace('~[\x80-\xFF]+$~','',substr($H,0,1e6))."\n…";$Kd[$_GET["db"]][]=array($H,time(),$Ti);$oi="sql-".count($Kd[$_GET["db"]]);$J="".lang(65)." �\n";if(!$Tc&&($Vj=driver()->warnings())){$u="warnings-".count($Kd[$_GET["db"]]);$J="".lang(47).", $J\n";}return" ".@date("H:i:s").""." $J';}function +editRowPrint($R,array$o,$K,$_j){}function +editFunctions(array$n){$J=($n["null"]?"NULL/":"");$_j=isset($_GET["select"])||where($_GET);foreach(array(driver()->insertFunctions,driver()->editFunctions)as$y=>$sd){if(!$y||(!isset($_GET["call"])&&$_j)){foreach($sd +as$Lg=>$X){if(!$Lg||preg_match("~$Lg~",$n["type"]))$J +.="/$X";}}if($y&&$sd&&!preg_match('~set|bool~',$n["type"])&&!is_blob($n))$J +.="/SQL";}if($n["auto_increment"]&&!$_j)$J=lang(52);return +explode("/",$J);}function +editInput($R,array$n,$_a,$Y){if($n["type"]=="enum")return(isset($_GET["select"])?" ":"").enum_input("radio",$_a,$n,$Y,"NULL");return"";}function +editHint($R,array$n,$Y){return"";}function +processInput(array$n,$Y,$s=""){if($s=="SQL")return$Y;$B=$n["field"];$J=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$J="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$J=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$J=idf_escape($B)." $s $J";elseif(preg_match('~^[+-] interval$~',$s))$J=idf_escape($B)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)&&JUSH!="pgsql"?$Y:$J);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$J="$s(".idf_escape($B).", $J)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$J="$s($J)";return +unconvert_field($n,$J);}function +dumpOutput(){$J=array('text'=>lang(66),'file'=>lang(67));if(function_exists('gzencode'))$J['gz']='gzip';return$J;}function +dumpFormat(){return(support("dump")?array('sql'=>'SQL'):array())+array('csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function +dumpDatabase($k){}function +dumpTable($R,$wi,$ze=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($wi)dump_csv(array_keys(fields($R)));}else{if($ze==2){$o=array();foreach(fields($R)as$B=>$n)$o[]=idf_escape($B)." $n[full_type]";$i="CREATE TABLE ".table($R)." (".implode(", ",$o).")";}else$i=create_sql($R,$_POST["auto_increment"],$wi);set_utf8mb4($i);if($wi&&$i){if($wi=="DROP+CREATE"||$ze==1)echo"DROP ".($ze==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($ze==1)$i=remove_definer($i);echo"$i;\n\n";}}}function +dumpData($R,$wi,$H){if($wi){$hf=(JUSH=="sqlite"?0:1048576);$o=array();$Td=false;if($_POST["format"]=="sql"){if($wi=="TRUNCATE+INSERT")echo +truncate_sql($R).";\n";$o=fields($R);if(JUSH=="mssql"){foreach($o +as$n){if($n["auto_increment"]){echo"SET IDENTITY_INSERT ".table($R)." ON;\n";$Td=true;break;}}}}$I=connection()->query($H,1);if($I){$oe="";$Pa="";$Ee=array();$td=array();$yi="";$Wc=($R!=''?'fetch_assoc':'fetch_row');$Eb=0;while($K=$I->$Wc()){if(!$Ee){$Nj=array();foreach($K +as$X){$n=$I->fetch_field();if(idx($o[$n->name],'generated')){$td[$n->name]=true;continue;}$Ee[]=$n->name;$y=idf_escape($n->name);$Nj[]="$y = VALUES($y)";}$yi=($wi=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj):"").";\n";}if($_POST["format"]!="sql"){if($wi=="table"){dump_csv($Ee);$wi="INSERT";}dump_csv($K);}else{if(!$oe)$oe="INSERT INTO ".table($R)." (".implode(", ",array_map('Adminer\idf_escape',$Ee)).") VALUES";foreach($K +as$y=>$X){if($td[$y]){unset($K[$y]);continue;}$n=$o[$y];$K[$y]=($X!==null?unconvert_field($n,preg_match(number_type(),$n["type"])&&!preg_match('~\[~',$n["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$Hh=($hf?"\n":" ")."(".implode(",\t",$K).")";if(!$Pa)$Pa=$oe.$Hh;elseif(JUSH=='mssql'?$Eb%1000!=0:strlen($Pa)+4+strlen($Hh)+strlen($yi)<$hf)$Pa +.=",$Hh";else{echo$Pa.$yi;$Pa=$oe.$Hh;}}$Eb++;}if($Pa)echo$Pa.$yi;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",connection()->error)."\n";if($Td)echo"SET IDENTITY_INSERT ".table($R)." OFF;\n";}}function +dumpFilename($Rd){return +friendly_url($Rd!=""?$Rd:(SERVER?:"localhost"));}function +dumpHeaders($Rd,$Af=false){$vg=$_POST["output"];$Oc=(preg_match('~sql~',$_POST["format"])?"sql":($Af?"tar":"csv"));header("Content-Type: ".($vg=="gz"?"application/x-gzip":($Oc=="tar"?"application/x-tar":($Oc=="sql"||$vg!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($vg=="gz"){ob_start(function($Q){return +gzencode($Q);},1e6);}return$Oc;}function +dumpFooter(){if($_POST["format"]=="sql")echo"-- ".gmdate("Y-m-d H:i:s e")."\n";}function importServerPath(){return"adminer.sql";}function -homepage(){echo'

    -',$this->name(),' ',$da,' -',(version_compare($da,$_COOKIE["adminer_version"])<0?h($_COOKIE["adminer_version"]):""),' -

    -';if($Hd=="auth"){$qe="";foreach((array)$_SESSION["pwds"]as$Wg=>$zf){foreach($zf -as$O=>$Sg){foreach($Sg -as$Rg=>$_e){if($_e!==null){$mb=$_SESSION["db"][$Wg][$O][$Rg];foreach(($mb?array_keys($mb):array(""))as$j)$qe.="
  • ($zb[$Wg]) ".h($Rg.($O!=""?"@".$this->serverName($O):"").($j!=""?" - $j":""))."\n";}}}}if($qe)echo"
      \n$qe
    \n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$Hd&&DB!=""){$f->select_db(DB);$T=table_status('',true);}echo -script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=4.8.1");if(support("sql")){echo' -';if($T){$qd=array();foreach($T -as$R=>$V)$qd[]=preg_quote($R,'/');echo"var jushLinks = { $y: [ '".js_escape(ME).(support("table")?"table=":"select=")."\$&', /\\b(".implode("|",$qd).")\\b/g ] };\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.$y;\n";}$yf=$f->server_info;echo'bodyLoad(\'',(is_object($f)?preg_replace('~^(\d\.?\d).*~s','\1',$yf):""),'\'',(preg_match('~MariaDB~',$yf)?", true":""),'); - -';}$this->databasesPrint($Hd);if(DB==""||!$Hd){echo"

    ".'Aucune table.'."\n";else$this->tablesPrint($T);}}}function -databasesPrint($Hd){global$b,$f;$i=$this->databases();if(DB&&$i&&!in_array(DB,$i))array_unshift($i,DB);echo'

    -

    -';hidden_fields_get();$kb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"".'DB'.": ".($i?"$kb":"\n"),"\n";foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo"";break;}}echo"

    \n";}function -tablesPrint($T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T -as$R=>$Mf){$F=$this->tableName($Mf);if($F!=""){echo'
    • ".'select'." ",(support("table")||support("indexes")?'$F":"$F")."\n";}}echo"
    \n";}}$b=(function_exists('adminer_object')?adminer_object():new -Adminer);$Wa=driver_config();$Le=$Wa['possible_drivers'];$y=$Wa['jush'];$Cg=$Wa['types'];$Of=$Wa['structured_types'];$Jg=$Wa['unsigned'];$ae=$Wa['operators'];$uc=$Wa['functions'];$yc=$Wa['grouping'];$Gb=$Wa['edit_functions'];if($b->operators===null)$b->operators=$ae;define("SERVER",$_GET[DRIVER]);define("DB",$_GET["db"]);define("ME",preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));$da="4.8.1";function -page_header($mg,$l="",$Ba=array(),$ng=""){global$ba,$da,$b,$zb,$y;page_headers();if(is_ajax()&&$l){page_messages($l);exit;}$og=$mg.($ng!=""?": $ng":"");$pg=strip_tags($og.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".$b->name());echo' - +navigation($xf){echo"

    ".adminer()->name()." ".VERSION;$If=$_COOKIE["adminer_version"];echo" ".(version_compare(VERSION,$If)<0?h($If):"")."","

    \n";switch_lang();if($xf=="auth"){$vg="";foreach((array)$_SESSION["pwds"]as$Pj=>$ai){foreach($ai +as$N=>$Jj){$B=h(get_setting("vendor-$Pj-$N")?:get_driver($Pj));foreach($Jj +as$V=>$F){if($F!==null){$Sb=$_SESSION["db"][$Pj][$N][$V];foreach(($Sb?array_keys($Sb):array(""))as$k)$vg +.="
  • ($B) ".h("$V@".($N!=""?adminer()->serverName($N):"").($k!=""?" - $k":""))."\n";}}}}if($vg)echo"
      \n$vg
    \n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$xf&&DB!=""){connection()->select_db(DB);$T=table_status('',true);}adminer()->syntaxHighlighting($T);adminer()->databasesPrint($xf);$ka=array();if(DB==""||!$xf){if(support("sql")){$ka[]="".lang(65)."";$ka[]="".lang(76)."";}$ka[]="".lang(77)."";}$Yd=$_GET["ns"]!==""&&!$xf&&DB!="";if($Yd&&function_exists('Adminer\alter_table'))$ka[]='".lang(78)."";echo($ka?"

    ".lang(11)."

    \n";}}}function +syntaxHighlighting(array$T){echo +script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=5.4.2",true);if(support("sql")){echo"\n";if($T){$Ve=array();foreach($T +as$R=>$U)$Ve[]=preg_quote($R,'/');echo"var jushLinks = { ".JUSH.":";json_row(js_escape(ME).(support("table")?"table":"select").'=$&','/\b('.implode('|',$Ve).')\b/g',false);if(support('routine')){foreach(routines()as$K)json_row(js_escape(ME).'function='.urlencode($K["SPECIFIC_NAME"]).'&name=$&','/\b'.preg_quote($K["ROUTINE_NAME"],'/').'(?=["`]?\()/g',false);}json_row('');echo"};\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.".JUSH.";\n";if(isset($_GET["sql"])||isset($_GET["trigger"])||isset($_GET["check"])){$Ii=array_fill_keys(array_keys($T),array());foreach(driver()->allFields()as$R=>$o){foreach($o +as$n)$Ii[$R][]=$n["field"];}echo"addEventListener('DOMContentLoaded', () => { autocompleter = jush.autocompleteSql('".idf_escape("")."', ".json_encode($Ii)."); });\n";}}echo"\n";}echo +script("syntaxHighlighting('".preg_replace('~^(\d\.?\d).*~s','\1',connection()->server_info)."', '".connection()->flavor."');");}function +databasesPrint($xf){$j=adminer()->databases();if(DB&&$j&&!in_array(DB,$j))array_unshift($j,DB);echo"
    \n

    \n";hidden_fields_get();$Qb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"","\n";if(support("scheme")){if($xf!="db"&&DB!=""&&connection()->select_db(DB)){echo"
    ";if($_GET["ns"]!="")set_schema($_GET["ns"]);}}foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo +input_hidden($X);break;}}echo"

    \n";}function +tablesPrint(array$T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T +as$R=>$P){$R="$R";$B=adminer()->tableName($P);if($B!=""&&!$P["partition"])echo'
    • ".lang(81)." ",(support("table")||support("indexes")?'$B":"$B")."\n";}echo"
    \n";}function +showVariables(){return +show_variables();}function +showStatus(){return +show_status();}function +processList(){return +process_list();}function +killProcess($u){return +kill_process($u);}}class +Plugins{private +static$append=array('dumpFormat'=>true,'dumpOutput'=>true,'editRowPrint'=>true,'editFunctions'=>true,'config'=>true);var$plugins;var$error='';private$hooks=array();function +__construct($Qg){if($Qg===null){$Qg=array();$Ja="adminer-plugins";if(is_dir($Ja)){foreach(glob("$Ja/*.php")as$p)$this->includeOnce($p);}$Jd=" href='https://www.adminer.org/plugins/#use'".target_blank();if(file_exists("$Ja.php")){$Zd=$this->includeOnce("$Ja.php");if(is_array($Zd)){foreach($Zd +as$Pg)$Qg[get_class($Pg)]=$Pg;}else$this->error +.=lang(82,"$Ja.php",$Jd)."
    ";}foreach(get_declared_classes()as$fb){if(!$Qg[$fb]&&(preg_match('~^Adminer\w~i',$fb)||is_subclass_of($fb,'Adminer\Plugin'))){$sh=new +\ReflectionClass($fb);$zb=$sh->getConstructor();if($zb&&$zb->getNumberOfRequiredParameters())$this->error +.=lang(83,$Jd,"$fb","$Ja.php")."
    ";else$Qg[$fb]=new$fb;}}}$this->plugins=$Qg;$na=new +Adminer;$Qg[]=$na;$sh=new +\ReflectionObject($na);foreach($sh->getMethods()as$vf){foreach($Qg +as$Pg){$B=$vf->getName();if(method_exists($Pg,$B))$this->hooks[$B][]=$Pg;}}}function +includeOnce($p){return +include_once"./$p";}function +__call($B,array$_g){$wa=array();foreach($_g +as$y=>$X)$wa[]=&$_g[$y];$J=null;foreach($this->hooks[$B]as$Pg){$Y=call_user_func_array(array($Pg,$B),$wa);if($Y!==null){if(!self::$append[$B])return$Y;$J=$Y+(array)$J;}}return$J;}}abstract +class +Plugin{protected$translations=array();function +description(){return$this->lang('');}function +screenshot(){return"";}protected +function +lang($v,$Of=null){$wa=func_get_args();$wa[0]=idx($this->translations[LANG],$v)?:$v;return +call_user_func_array('Adminer\lang_format',$wa);}}Adminer::$instance=(function_exists('adminer_object')?adminer_object():(is_dir("adminer-plugins")||file_exists("adminer-plugins.php")?new +Plugins(null):new +Adminer));SqlDriver::$drivers=array("server"=>"MySQL / MariaDB")+SqlDriver::$drivers;if(!defined('Adminer\DRIVER')){define('Adminer\DRIVER',"server");if(extension_loaded("mysqli")&&$_GET["ext"]!="pdo"){class +Db +extends +\MySQLi{static$instance;var$extension="MySQLi",$flavor='';function +__construct(){parent::init();}function +attach($N,$V,$F){mysqli_report(MYSQLI_REPORT_OFF);list($Nd,$Rg)=host_port($N);$ri=adminer()->connectSsl();if($ri)$this->ssl_set($ri['key'],$ri['cert'],$ri['ca'],'','');$J=@$this->real_connect(($N!=""?$Nd:ini_get("mysqli.default_host")),($N.$V!=""?$V:ini_get("mysqli.default_user")),($N.$V.$F!=""?$F:ini_get("mysqli.default_pw")),null,(is_numeric($Rg)?intval($Rg):ini_get("mysqli.default_port")),(is_numeric($Rg)?null:$Rg),($ri?($ri['verify']!==false?2048:64):0));$this->options(MYSQLI_OPT_LOCAL_INFILE,0);return($J?'':$this->error);}function +set_charset($Xa){if(parent::set_charset($Xa))return +true;parent::set_charset('utf8');return$this->query("SET NAMES $Xa");}function +next_result(){return +self::more_results()&&parent::next_result();}function +quote($Q){return"'".$this->escape_string($Q)."'";}}}elseif(extension_loaded("mysql")&&!((ini_bool("sql.safe_mode")||ini_bool("mysql.allow_local_infile"))&&extension_loaded("pdo_mysql"))){class +Db +extends +SqlDb{private$link;function +attach($N,$V,$F){if(ini_bool("mysql.allow_local_infile"))return +lang(84,"'mysql.allow_local_infile'","MySQLi","PDO_MySQL");$this->link=@mysql_connect(($N!=""?$N:ini_get("mysql.default_host")),($N.$V!=""?$V:ini_get("mysql.default_user")),($N.$V.$F!=""?$F:ini_get("mysql.default_password")),true,131072);if(!$this->link)return +mysql_error();$this->server_info=mysql_get_server_info($this->link);return'';}function +set_charset($Xa){if(function_exists('mysql_set_charset')){if(mysql_set_charset($Xa,$this->link))return +true;mysql_set_charset('utf8',$this->link);}return$this->query("SET NAMES $Xa");}function +quote($Q){return"'".mysql_real_escape_string($Q,$this->link)."'";}function +select_db($Pb){return +mysql_select_db($Pb,$this->link);}function +query($H,$sj=false){$I=@($sj?mysql_unbuffered_query($H,$this->link):mysql_query($H,$this->link));$this->error="";if(!$I){$this->errno=mysql_errno($this->link);$this->error=mysql_error($this->link);return +false;}if($I===true){$this->affected_rows=mysql_affected_rows($this->link);$this->info=mysql_info($this->link);return +true;}return +new +Result($I);}}class +Result{var$num_rows;private$result;private$offset=0;function +__construct($I){$this->result=$I;$this->num_rows=mysql_num_rows($I);}function +fetch_assoc(){return +mysql_fetch_assoc($this->result);}function +fetch_row(){return +mysql_fetch_row($this->result);}function +fetch_field(){$J=mysql_fetch_field($this->result,$this->offset++);$J->orgtable=$J->table;$J->charsetnr=($J->blob?63:0);return$J;}function +__destruct(){mysql_free_result($this->result);}}}elseif(extension_loaded("pdo_mysql")){class +Db +extends +PdoDb{var$extension="PDO_MySQL";function +attach($N,$V,$F){$gg=array(\PDO::MYSQL_ATTR_LOCAL_INFILE=>false);$ri=adminer()->connectSsl();if($ri){if($ri['key'])$gg[\PDO::MYSQL_ATTR_SSL_KEY]=$ri['key'];if($ri['cert'])$gg[\PDO::MYSQL_ATTR_SSL_CERT]=$ri['cert'];if($ri['ca'])$gg[\PDO::MYSQL_ATTR_SSL_CA]=$ri['ca'];if(isset($ri['verify']))$gg[\PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT]=$ri['verify'];}list($Nd,$Rg)=host_port($N);return$this->dsn("mysql:charset=utf8;host=$Nd".($Rg?(is_numeric($Rg)?";port=":";unix_socket=").$Rg:""),$V,$F,$gg);}function +set_charset($Xa){return$this->query("SET NAMES $Xa");}function +select_db($Pb){return$this->query("USE ".idf_escape($Pb));}function +query($H,$sj=false){$this->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,!$sj);return +parent::query($H,$sj);}}}class +Driver +extends +SqlDriver{static$extensions=array("MySQLi","MySQL","PDO_MySQL");static$jush="sql";var$unsigned=array("unsigned","zerofill","unsigned zerofill");var$operators=array("=","<",">","<=",">=","!=","LIKE","LIKE %%","REGEXP","IN","FIND_IN_SET","IS NULL","NOT LIKE","NOT REGEXP","NOT IN","IS NOT NULL","SQL");var$functions=array("char_length","date","from_unixtime","lower","round","floor","ceil","sec_to_time","time_to_sec","upper");var$grouping=array("avg","count","count distinct","group_concat","max","min","sum");static +function +connect($N,$V,$F){$g=parent::connect($N,$V,$F);if(is_string($g)){if(function_exists('iconv')&&!is_utf8($g)&&strlen($Hh=iconv("windows-1250","utf-8",$g))>strlen($g))$g=$Hh;return$g;}$g->set_charset(charset($g));$g->query("SET sql_quote_show_create = 1, autocommit = 1");$g->flavor=(preg_match('~MariaDB~',$g->server_info)?'maria':'mysql');add_driver(DRIVER,($g->flavor=='maria'?"MariaDB":"MySQL"));return$g;}function +__construct(Db$g){parent::__construct($g);$this->types=array(lang(27)=>array("tinyint"=>3,"smallint"=>5,"mediumint"=>8,"int"=>10,"bigint"=>20,"decimal"=>66,"float"=>12,"double"=>21),lang(28)=>array("date"=>10,"datetime"=>19,"timestamp"=>19,"time"=>10,"year"=>4),lang(29)=>array("char"=>255,"varchar"=>65535,"tinytext"=>255,"text"=>65535,"mediumtext"=>16777215,"longtext"=>4294967295),lang(85)=>array("enum"=>65535,"set"=>64),lang(30)=>array("bit"=>20,"binary"=>255,"varbinary"=>65535,"tinyblob"=>255,"blob"=>65535,"mediumblob"=>16777215,"longblob"=>4294967295),lang(32)=>array("geometry"=>0,"point"=>0,"linestring"=>0,"polygon"=>0,"multipoint"=>0,"multilinestring"=>0,"multipolygon"=>0,"geometrycollection"=>0),);$this->insertFunctions=array("char"=>"md5/sha1/password/encrypt/uuid","binary"=>"md5/sha1","date|time"=>"now",);$this->editFunctions=array(number_type()=>"+/-","date"=>"+ interval/- interval","time"=>"addtime/subtime","char|text"=>"concat",);if(min_version('5.7.8',10.2,$g))$this->types[lang(29)]["json"]=4294967295;if(min_version('',10.7,$g)){$this->types[lang(29)]["uuid"]=128;$this->insertFunctions['uuid']='uuid';}if(min_version(9,'',$g)){$this->types[lang(27)]["vector"]=16383;$this->insertFunctions['vector']='string_to_vector';}if(min_version(5.1,'',$g))$this->partitionBy=array("HASH","LINEAR HASH","KEY","LINEAR KEY","RANGE","LIST");if(min_version(5.7,10.2,$g))$this->generated=array("STORED","VIRTUAL");}function +unconvertFunction(array$n){return(preg_match("~binary~",$n["type"])?"UNHEX":($n["type"]=="bit"?doc_link(array('sql'=>'bit-value-literals.html'),"b''"):(preg_match("~geometry|point|linestring|polygon~",$n["type"])?"GeomFromText":"")));}function +insert($R,array$O){return($O?parent::insert($R,$O):queries("INSERT INTO ".table($R)." ()\nVALUES ()"));}function +insertUpdate($R,array$L,array$G){$e=array_keys(reset($L));$Xg="INSERT INTO ".table($R)." (".implode(", ",$e).") VALUES\n";$Nj=array();foreach($e +as$y)$Nj[$y]="$y = VALUES($y)";$yi="\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj);$Nj=array();$Re=0;foreach($L +as$O){$Y="(".implode(", ",$O).")";if($Nj&&(strlen($Xg)+$Re+strlen($Y)+strlen($yi)>1e6)){if(!queries($Xg.implode(",\n",$Nj).$yi))return +false;$Nj=array();$Re=0;}$Nj[]=$Y;$Re+=strlen($Y)+2;}return +queries($Xg.implode(",\n",$Nj).$yi);}function +slowQuery($H,$Ui){if(min_version('5.7.8','10.1.2')){if($this->conn->flavor=='maria')return"SET STATEMENT max_statement_time=$Ui FOR $H";elseif(preg_match('~^(SELECT\b)(.+)~is',$H,$A))return"$A[1] /*+ MAX_EXECUTION_TIME(".($Ui*1000).") */ $A[2]";}}function +convertSearch($v,array$X,array$n){return(preg_match('~char|text|enum|set~',$n["type"])&&!preg_match("~^utf8~",$n["collation"])&&preg_match('~[\x80-\xFF]~',$X['val'])?"CONVERT($v USING ".charset($this->conn).")":$v);}function +warnings(){$I=$this->conn->query("SHOW WARNINGS");if($I&&$I->num_rows){ob_start();print_select_result($I);return +ob_get_clean();}}function +tableHelp($B,$ze=false){$Ze=($this->conn->flavor=='maria');if(information_schema(DB))return +strtolower("information-schema-".($Ze?"$B-table/":str_replace("_","-",$B)."-table.html"));if(DB=="mysql")return($Ze?"mysql$B-table/":"system-schema.html");}function +partitionsInfo($R){$qd="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($R);$I=$this->conn->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $qd ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");$J=array();list($J["partition_by"],$J["partition"],$J["partitions"])=$I->fetch_row();$Hg=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $qd AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$J["partition_names"]=array_keys($Hg);$J["partition_values"]=array_values($Hg);return$J;}function +hasCStyleEscapes(){static$Sa;if($Sa===null){$pi=get_val("SHOW VARIABLES LIKE 'sql_mode'",1,$this->conn);$Sa=(strpos($pi,'NO_BACKSLASH_ESCAPES')===false);}return$Sa;}function +engines(){$J=array();foreach(get_rows("SHOW ENGINES")as$K){if(preg_match("~YES|DEFAULT~",$K["Support"]))$J[]=$K["Engine"];}return$J;}function +indexAlgorithms(array$Bi){return(preg_match('~^(MEMORY|NDB)$~',$Bi["Engine"])?array("HASH","BTREE"):array());}}function +idf_escape($v){return"`".str_replace("`","``",$v)."`";}function +table($v){return +idf_escape($v);}function +get_databases($id){$J=get_session("dbs");if($J===null){$H="SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";$J=($id?slow_query($H):get_vals($H));restart_session();set_session("dbs",$J);stop_session();}return$J;}function +limit($H,$Z,$z,$C=0,$Vh=" "){return" $H$Z".($z?$Vh."LIMIT $z".($C?" OFFSET $C":""):"");}function +limit1($R,$H,$Z,$Vh="\n"){return +limit($H,$Z,1,0,$Vh);}function +db_collation($k,array$lb){$J=null;$i=get_val("SHOW CREATE DATABASE ".idf_escape($k),1);if(preg_match('~ COLLATE ([^ ]+)~',$i,$A))$J=$A[1];elseif(preg_match('~ CHARACTER SET ([^ ]+)~',$i,$A))$J=$lb[$A[1]][-1];return$J;}function +logged_user(){return +get_val("SELECT USER()");}function +tables_list(){return +get_key_vals("SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME");}function +count_tables(array$j){$J=array();foreach($j +as$k)$J[$k]=count(get_vals("SHOW TABLES IN ".idf_escape($k)));return$J;}function +table_status($B="",$Uc=false){$J=array();foreach(get_rows($Uc?"SELECT TABLE_NAME AS Name, ENGINE AS Engine, TABLE_COMMENT AS Comment FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ".($B!=""?"AND TABLE_NAME = ".q($B):"ORDER BY Name"):"SHOW TABLE STATUS".($B!=""?" LIKE ".q(addcslashes($B,"%_\\")):""))as$K){if($K["Engine"]=="InnoDB")$K["Comment"]=preg_replace('~(?:(.+); )?InnoDB free: .*~','\1',$K["Comment"]);if(!isset($K["Engine"]))$K["Comment"]="";if($B!="")$K["Name"]=$B;$J[$K["Name"]]=$K;}return$J;}function +is_view(array$S){return$S["Engine"]===null;}function +fk_support(array$S){return +preg_match('~InnoDB|IBMDB2I'.(min_version(5.6)?'|NDB':'').'~i',$S["Engine"]);}function +fields($R){$Ze=(connection()->flavor=='maria');$J=array();foreach(get_rows("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ".q($R)." ORDER BY ORDINAL_POSITION")as$K){$n=$K["COLUMN_NAME"];$U=$K["COLUMN_TYPE"];$ud=$K["GENERATION_EXPRESSION"];$Rc=$K["EXTRA"];preg_match('~^(VIRTUAL|PERSISTENT|STORED)~',$Rc,$td);preg_match('~^([^( ]+)(?:\((.+)\))?( unsigned)?( zerofill)?$~',$U,$cf);$l=$K["COLUMN_DEFAULT"];if($l!=""){$ye=preg_match('~text|json~',$cf[1]);if(!$Ze&&$ye)$l=preg_replace("~^(_\w+)?('.*')$~",'\2',stripslashes($l));if($Ze||$ye){$l=($l=="NULL"?null:preg_replace_callback("~^'(.*)'$~",function($A){return +stripslashes(str_replace("''","'",$A[1]));},$l));}if(!$Ze&&preg_match('~binary~',$cf[1])&&preg_match('~^0x(\w*)$~',$l,$A))$l=pack("H*",$A[1]);}$J[$n]=array("field"=>$n,"full_type"=>$U,"type"=>$cf[1],"length"=>$cf[2],"unsigned"=>ltrim($cf[3].$cf[4]),"default"=>($td?($Ze?$ud:stripslashes($ud)):$l),"null"=>($K["IS_NULLABLE"]=="YES"),"auto_increment"=>($Rc=="auto_increment"),"on_update"=>(preg_match('~\bon update (\w+)~i',$Rc,$A)?$A[1]:""),"collation"=>$K["COLLATION_NAME"],"privileges"=>array_flip(explode(",","$K[PRIVILEGES],where,order")),"comment"=>$K["COLUMN_COMMENT"],"primary"=>($K["COLUMN_KEY"]=="PRI"),"generated"=>($td[1]=="PERSISTENT"?"STORED":$td[1]),);}return$J;}function +indexes($R,$h=null){$J=array();foreach(get_rows("SHOW INDEX FROM ".table($R),$h)as$K){$B=$K["Key_name"];$J[$B]["type"]=($B=="PRIMARY"?"PRIMARY":($K["Index_type"]=="FULLTEXT"?"FULLTEXT":($K["Non_unique"]?($K["Index_type"]=="SPATIAL"?"SPATIAL":"INDEX"):"UNIQUE")));$J[$B]["columns"][]=$K["Column_name"];$J[$B]["lengths"][]=($K["Index_type"]=="SPATIAL"?null:$K["Sub_part"]);$J[$B]["descs"][]=null;$J[$B]["algorithm"]=$K["Index_type"];}return$J;}function +foreign_keys($R){static$Lg='(?:`(?:[^`]|``)+`|"(?:[^"]|"")+")';$J=array();$Fb=get_val("SHOW CREATE TABLE ".table($R),1);if($Fb){preg_match_all("~CONSTRAINT ($Lg) FOREIGN KEY ?\\(((?:$Lg,? ?)+)\\) REFERENCES ($Lg)(?:\\.($Lg))? \\(((?:$Lg,? ?)+)\\)(?: ON DELETE (".driver()->onActions."))?(?: ON UPDATE (".driver()->onActions."))?~",$Fb,$df,PREG_SET_ORDER);foreach($df +as$A){preg_match_all("~$Lg~",$A[2],$ji);preg_match_all("~$Lg~",$A[5],$Mi);$J[idf_unescape($A[1])]=array("db"=>idf_unescape($A[4]!=""?$A[3]:$A[4]),"table"=>idf_unescape($A[4]!=""?$A[4]:$A[3]),"source"=>array_map('Adminer\idf_unescape',$ji[0]),"target"=>array_map('Adminer\idf_unescape',$Mi[0]),"on_delete"=>($A[6]?:"RESTRICT"),"on_update"=>($A[7]?:"RESTRICT"),);}}return$J;}function +view($B){return +array("select"=>preg_replace('~^(?:[^`]|`[^`]*`)*\s+AS\s+~isU','',get_val("SHOW CREATE VIEW ".table($B),1)));}function +collations(){$J=array();foreach(get_rows("SHOW COLLATION")as$K){if($K["Default"])$J[$K["Charset"]][-1]=$K["Collation"];else$J[$K["Charset"]][]=$K["Collation"];}ksort($J);foreach($J +as$y=>$X)sort($J[$y]);return$J;}function +information_schema($k){return($k=="information_schema")||(min_version(5.5)&&$k=="performance_schema");}function +error(){return +h(preg_replace('~^You have an error.*syntax to use~U',"Syntax error",connection()->error));}function +create_database($k,$c){return +queries("CREATE DATABASE ".idf_escape($k).($c?" COLLATE ".q($c):""));}function +drop_databases(array$j){$J=apply_queries("DROP DATABASE",$j,'Adminer\idf_escape');restart_session();set_session("dbs",null);return$J;}function +rename_database($B,$c){$J=false;if(create_database($B,$c)){$T=array();$Sj=array();foreach(tables_list()as$R=>$U){if($U=='VIEW')$Sj[]=$R;else$T[]=$R;}$J=(!$T&&!$Sj)||move_tables($T,$Sj,$B);drop_databases($J?array(DB):array());}return$J;}function +auto_increment(){$Ca=" PRIMARY KEY";if($_GET["create"]!=""&&$_POST["auto_increment_col"]){foreach(indexes($_GET["create"])as$w){if(in_array($_POST["fields"][$_POST["auto_increment_col"]]["orig"],$w["columns"],true)){$Ca="";break;}if($w["type"]=="PRIMARY")$Ca=" UNIQUE";}}return" AUTO_INCREMENT$Ca";}function +alter_table($R,$B,array$o,array$kd,$qb,$yc,$c,$Ba,$E){$b=array();foreach($o +as$n){if($n[1]){$l=$n[1][3];if(preg_match('~ GENERATED~',$l)){$n[1][3]=(connection()->flavor=='maria'?"":$n[1][2]);$n[1][2]=$l;}$b[]=($R!=""?($n[0]!=""?"CHANGE ".idf_escape($n[0]):"ADD"):" ")." ".implode($n[1]).($R!=""?$n[2]:"");}else$b[]="DROP ".idf_escape($n[0]);}$b=array_merge($b,$kd);$P=($qb!==null?" COMMENT=".q($qb):"").($yc?" ENGINE=".q($yc):"").($c?" COLLATE ".q($c):"").($Ba!=""?" AUTO_INCREMENT=$Ba":"");if($E){$Hg=array();if($E["partition_by"]=='RANGE'||$E["partition_by"]=='LIST'){foreach($E["partition_names"]as$y=>$X){$Y=$E["partition_values"][$y];$Hg[]="\n PARTITION ".idf_escape($X)." VALUES ".($E["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$P +.="\nPARTITION BY $E[partition_by]($E[partition])";if($Hg)$P +.=" (".implode(",",$Hg)."\n)";elseif($E["partitions"])$P +.=" PARTITIONS ".(+$E["partitions"]);}elseif($E===null)$P +.="\nREMOVE PARTITIONING";if($R=="")return +queries("CREATE TABLE ".table($B)." (\n".implode(",\n",$b)."\n)$P");if($R!=$B)$b[]="RENAME TO ".table($B);if($P)$b[]=ltrim($P);return($b?queries("ALTER TABLE ".table($R)."\n".implode(",\n",$b)):true);}function +alter_indexes($R,$b){$Wa=array();foreach($b +as$X)$Wa[]=($X[2]=="DROP"?"\nDROP INDEX ".idf_escape($X[1]):"\nADD $X[0] ".($X[0]=="PRIMARY"?"KEY ":"").($X[1]!=""?idf_escape($X[1])." ":"")."(".implode(", ",$X[2]).")");return +queries("ALTER TABLE ".table($R).implode(",",$Wa));}function +truncate_tables(array$T){return +apply_queries("TRUNCATE TABLE",$T);}function +drop_views(array$Sj){return +queries("DROP VIEW ".implode(", ",array_map('Adminer\table',$Sj)));}function +drop_tables(array$T){return +queries("DROP TABLE ".implode(", ",array_map('Adminer\table',$T)));}function +move_tables(array$T,array$Sj,$Mi){$wh=array();foreach($T +as$R)$wh[]=table($R)." TO ".idf_escape($Mi).".".table($R);if(!$wh||queries("RENAME TABLE ".implode(", ",$wh))){$Yb=array();foreach($Sj +as$R)$Yb[table($R)]=view($R);connection()->select_db($Mi);$k=idf_escape(DB);foreach($Yb +as$B=>$Rj){if(!queries("CREATE VIEW $B AS ".str_replace(" $k."," ",$Rj["select"]))||!queries("DROP VIEW $k.$B"))return +false;}return +true;}return +false;}function +copy_tables(array$T,array$Sj,$Mi){queries("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'");foreach($T +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));if(($_POST["overwrite"]&&!queries("\nDROP TABLE IF EXISTS $B"))||!queries("CREATE TABLE $B LIKE ".table($R))||!queries("INSERT INTO $B SELECT * FROM ".table($R)))return +false;foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K){$lj=$K["Trigger"];if(!queries("CREATE TRIGGER ".($Mi==DB?idf_escape("copy_$lj"):idf_escape($Mi).".".idf_escape($lj))." $K[Timing] $K[Event] ON $B FOR EACH ROW\n$K[Statement];"))return +false;}}foreach($Sj +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));$Rj=view($R);if(($_POST["overwrite"]&&!queries("DROP VIEW IF EXISTS $B"))||!queries("CREATE VIEW $B AS $Rj[select]"))return +false;}return +true;}function +trigger($B,$R){if($B=="")return +array();$L=get_rows("SHOW TRIGGERS WHERE `Trigger` = ".q($B));return +reset($L);}function +triggers($R){$J=array();foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K)$J[$K["Trigger"]]=array($K["Timing"],$K["Event"]);return$J;}function +trigger_options(){return +array("Timing"=>array("BEFORE","AFTER"),"Event"=>array("INSERT","UPDATE","DELETE"),"Type"=>array("FOR EACH ROW"),);}function +routine($B,$U){$o=get_rows("SELECT + PARAMETER_NAME field, + DATA_TYPE type, + CHARACTER_MAXIMUM_LENGTH length, + REGEXP_REPLACE(DTD_IDENTIFIER, '^[^ ]+ ', '') `unsigned`, + 1 `null`, + DTD_IDENTIFIER full_type, + PARAMETER_MODE `inout`, + CHARACTER_SET_NAME collation +FROM information_schema.PARAMETERS +WHERE SPECIFIC_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND SPECIFIC_NAME = ".q($B)." +ORDER BY ORDINAL_POSITION");$J=connection()->query("SELECT ROUTINE_COMMENT comment, ROUTINE_DEFINITION definition, 'SQL' language +FROM information_schema.ROUTINES +WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND ROUTINE_NAME = ".q($B))->fetch_assoc();if($o&&$o[0]['field']=='')$J['returns']=array_shift($o);$J['fields']=$o;return$J;}function +routines(){return +get_rows("SELECT SPECIFIC_NAME, ROUTINE_NAME, ROUTINE_TYPE, DTD_IDENTIFIER FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE()");}function +routine_languages(){return +array();}function +routine_id($B,array$K){return +idf_escape($B);}function +last_id($I){return +get_val("SELECT LAST_INSERT_ID()");}function +explain(Db$g,$H){return$g->query("EXPLAIN ".(min_version(5.1)&&!min_version(5.7)?"PARTITIONS ":"").$H);}function +found_rows(array$S,array$Z){return($Z||$S["Engine"]!="InnoDB"?null:$S["Rows"]);}function +create_sql($R,$Ba,$wi){$J=get_val("SHOW CREATE TABLE ".table($R),1);if(!$Ba)$J=preg_replace('~ AUTO_INCREMENT=\d+~','',$J);return$J;}function +truncate_sql($R){return"TRUNCATE ".table($R);}function +use_sql($Pb,$wi=""){$B=idf_escape($Pb);$J="";if(preg_match('~CREATE~',$wi)&&($i=get_val("SHOW CREATE DATABASE $B",1))){set_utf8mb4($i);if($wi=="DROP+CREATE")$J="DROP DATABASE IF EXISTS $B;\n";$J +.="$i;\n";}return$J."USE $B";}function +trigger_sql($R){$J="";foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")),null,"-- ")as$K)$J +.="\nCREATE TRIGGER ".idf_escape($K["Trigger"])." $K[Timing] $K[Event] ON ".table($K["Table"])." FOR EACH ROW\n$K[Statement];;\n";return$J;}function +show_variables(){return +get_rows("SHOW VARIABLES");}function +show_status(){return +get_rows("SHOW STATUS");}function +process_list(){return +get_rows("SHOW FULL PROCESSLIST");}function +convert_field(array$n){if(preg_match("~binary~",$n["type"]))return"HEX(".idf_escape($n["field"]).")";if($n["type"]=="bit")return"BIN(".idf_escape($n["field"])." + 0)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"]))return(min_version(8)?"ST_":"")."AsWKT(".idf_escape($n["field"]).")";}function +unconvert_field(array$n,$J){if(preg_match("~binary~",$n["type"]))$J="UNHEX($J)";if($n["type"]=="bit")$J="CONVERT(b$J, UNSIGNED)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"])){$Xg=(min_version(8)?"ST_":"");$J=$Xg."GeomFromText($J, $Xg"."SRID($n[field]))";}return$J;}function +support($Vc){return +preg_match('~^(comment|columns|copy|database|drop_col|dump|indexes|kill|privileges|move_col|procedure|processlist|routine|sql|status|table|trigger|variables|view'.(min_version(5.1)?'|event':'').(min_version(8)?'|descidx':'').(min_version('8.0.16','10.2.1')?'|check':'').')$~',$Vc);}function +kill_process($u){return +queries("KILL ".number($u));}function +connection_id(){return"SELECT CONNECTION_ID()";}function +max_connections(){return +get_val("SELECT @@max_connections");}function +types(){return +array();}function +type_values($u){return"";}function +schemas(){return +array();}function +get_schema(){return"";}function +set_schema($Jh,$h=null){return +true;}}define('Adminer\JUSH',Driver::$jush);define('Adminer\SERVER',"".$_GET[DRIVER]);define('Adminer\DB',"$_GET[db]");define('Adminer\ME',preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').($_GET["ext"]?"ext=".urlencode($_GET["ext"]).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));function +page_header($Wi,$m="",$Oa=array(),$Xi=""){page_headers();if(is_ajax()&&$m){page_messages($m);exit;}if(!ob_get_level())ob_start('ob_gzhandler',4096);$Yi=$Wi.($Xi!=""?": $Xi":"");$Zi=strip_tags($Yi.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".adminer()->name());echo' + -',$pg,' - -',script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=4.8.1");if($b->head()){echo' - -';foreach($b->css()as$eb){echo' -';}}echo' - -';$o=get_temp_dir()."/adminer.version";if(!$_COOKIE["adminer_version"]&&function_exists('openssl_verify')&&file_exists($o)&&filemtime($o)+86400>time()){$Xg=unserialize(file_get_contents($o));$Ve="-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwqWOVuF5uw7/+Z70djoK -RlHIZFZPO0uYRezq90+7Amk+FDNd7KkL5eDve+vHRJBLAszF/7XKXe11xwliIsFs -DFWQlsABVZB3oisKCBEuI71J4kPH8dKGEWR9jDHFw3cWmoH3PmqImX6FISWbG3B8 -h7FIx3jEaw5ckVPVTeo5JRm/1DZzJxjyDenXvBQ/6o9DgZKeNDgxwKzH+sw9/YCO -jHnq1cFpOIISzARlrHMa/43YfeNRAm/tsBXjSxembBPo7aQZLAWHmaj5+K19H10B -nCpz9Y++cipkVEiKRGih4ZEvjoFysEOdRLj6WiD/uUNky4xGeA6LaJqh5XpkFkcQ -fQIDAQAB ------END PUBLIC KEY----- -";if(openssl_verify($Xg["version"],base64_decode($Xg["signature"]),$Ve)==1)$_COOKIE["adminer_version"]=$Xg["version"];}echo' -mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick',(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '$da', '".js_escape(ME)."', '".get_token()."')");?>}); -document.body.className = document.body.className.replace(/ nojs/, ' js'); -var offlineMessage = ' - - -',script("mixin(qs('#help'), {onmouseover: function () { helpOpen = 1; }, onmouseout: helpMouseout});"),' -
    -';if($Ba!==null){$A=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $og

    \n","\n";restart_session();page_messages($l);$i=&get_session("dbs");if(DB!=""&&$i&&!in_array(DB,$i,true))$i=null;stop_session();define("PAGE_HEADER",1);}function -page_headers(){global$b;header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: SAMEORIGIN");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach($b->csp()as$db){$Dc=array();foreach($db -as$z=>$X)$Dc[]="$z $X";header("Content-Security-Policy: ".implode("; ",$Dc));}$b->headers();}function + +',$Zi,' + +';$Jb=adminer()->css();if(is_int(key($Jb)))$Jb=array_fill_keys($Jb,'light');$Fd=in_array('light',$Jb)||in_array('',$Jb);$Dd=in_array('dark',$Jb)||in_array('',$Jb);$Mb=($Fd?($Dd?null:false):($Dd?:null));$nf=" media='(prefers-color-scheme: dark)'";if($Mb!==false)echo"\n";echo"\n",script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=5.4.2");if(adminer()->head($Mb))echo"\n","\n";foreach($Jb +as$Dj=>$yf){$_a=($yf=='dark'&&!$Mb?$nf:($yf=='light'&&$Dd?" media='(prefers-color-scheme: light)'":""));echo"\n";}echo"\n\n";$p=get_temp_dir()."/adminer.version";echo +script("mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick".(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '".VERSION."')")."}); +document.body.classList.replace('nojs', 'js'); +const offlineMessage = '".js_escape(lang(87))."'; +const thousandsSeparator = '".js_escape(lang(4))."';"),"\n",script("mixin(qs('#help'), {onmouseover: () => { helpOpen = 1; }, onmouseout: helpMouseout});"),"
    \n","".icon("move","","menu","")."".script("qs('#menuopen').onclick = event => { qs('#foot').classList.toggle('foot'); event.stopPropagation(); }");if($Oa!==null){$_=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $Yi

    \n","\n";restart_session();page_messages($m);$j=&get_session("dbs");if(DB!=""&&$j&&!in_array(DB,$j,true))$j=null;stop_session();define('Adminer\PAGE_HEADER',1);}function +page_headers(){header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: deny");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach(adminer()->csp(csp())as$Ib){$Hd=array();foreach($Ib +as$y=>$X)$Hd[]="$y $X";header("Content-Security-Policy: ".implode("; ",$Hd));}adminer()->headers();}function csp(){return -array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self'","frame-src"=>"https://www.adminer.org","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function -get_nonce(){static$Nd;if(!$Nd)$Nd=base64_encode(rand_string());return$Nd;}function -page_messages($l){$Lg=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$Ed=$_SESSION["messages"][$Lg];if($Ed){echo"
    ".implode("
    \n
    ",$Ed)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Lg]);}if($l)echo"
    $l
    \n";}function -page_footer($Hd=""){global$b,$U;echo'
    - -';if($Hd!="auth"){echo'
    +array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self' https://www.adminer.org","frame-src"=>"'none'","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function +get_nonce(){static$Kf;if(!$Kf)$Kf=base64_encode(rand_string());return$Kf;}function +page_messages($m){$Cj=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$uf=idx($_SESSION["messages"],$Cj);if($uf){echo"
    ".implode("
    \n
    ",$uf)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Cj]);}if($m)echo"
    $m
    \n";if(adminer()->error)echo"
    ".adminer()->error."
    \n";}function +page_footer($xf=""){echo"
    \n\n\n\n",script("setupSubmitHighlight(document);");}function +int32($Cf){while($Cf>=2147483648)$Cf-=4294967296;while($Cf<=-2147483649)$Cf+=4294967296;return(int)$Cf;}function +long2str(array$W,$Uj){$Hh='';foreach($W +as$X)$Hh +.=pack('V',$X);if($Uj)return +substr($Hh,0,end($W));return$Hh;}function +str2long($Hh,$Uj){$W=array_values(unpack('V*',str_pad($Hh,4*ceil(strlen($Hh)/4),"\0")));if($Uj)$W[]=strlen($Hh);return$W;}function +xxtea_mx($bk,$ak,$zi,$Ce){return +int32((($bk>>5&0x7FFFFFF)^$ak<<2)+(($ak>>3&0x1FFFFFFF)^$bk<<4))^int32(($zi^$ak)+($Ce^$bk));}function +encrypt_string($ui,$y){if($ui=="")return"";$y=array_values(unpack("V*",pack("H*",md5($y))));$W=str2long($ui,true);$Cf=count($W)-1;$bk=$W[$Cf];$ak=$W[0];$hh=floor(6+52/($Cf+1));$zi=0;while($hh-->0){$zi=int32($zi+0x9E3779B9);$pc=$zi>>2&3;for($xg=0;$xg<$Cf;$xg++){$ak=$W[$xg+1];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$xg]+$Bf);$W[$xg]=$bk;}$ak=$W[0];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$Cf]+$Bf);$W[$Cf]=$bk;}return long2str($W,false);}function -decrypt_string($Nf,$z){if($Nf=="")return"";if(!$z)return -false;$z=array_values(unpack("V*",pack("H*",md5($z))));$W=str2long($Nf,false);$E=count($W)-1;$ih=$W[$E];$hh=$W[0];$H=floor(6+52/($E+1));$Sf=int32($H*0x9E3779B9);while($Sf){$Fb=$Sf>>2&3;for($re=$E;$re>0;$re--){$ih=$W[$re-1];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[$re]-$Jd);$W[$re]=$hh;}$ih=$W[$E];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[0]-$Jd);$W[0]=$hh;$Sf=int32($Sf-0x9E3779B9);}return -long2str($W,true);}$f='';$Cc=$_SESSION["token"];if(!$Cc)$_SESSION["token"]=rand(1,1e6);$U=get_token();$De=array();if($_COOKIE["adminer_permanent"]){foreach(explode(" ",$_COOKIE["adminer_permanent"])as$X){list($z)=explode(":",$X);$De[$z]=$X;}}function -add_invalid_login(){global$b;$r=file_open_lock(get_temp_dir()."/adminer.invalid");if(!$r)return;$Uc=unserialize(stream_get_contents($r));$jg=time();if($Uc){foreach($Uc -as$Vc=>$X){if($X[0]<$jg)unset($Uc[$Vc]);}}$Tc=&$Uc[$b->bruteForceKey()];if(!$Tc)$Tc=array($jg+30*60,0);$Tc[1]++;file_write_unlock($r,serialize($Uc));}function -check_invalid_login(){global$b;$Uc=unserialize(@file_get_contents(get_temp_dir()."/adminer.invalid"));$Tc=($Uc?$Uc[$b->bruteForceKey()]:array());$Md=($Tc[1]>29?$Tc[0]-time():0);if($Md>0)auth_error(lang(array('Trop de connexions échouées, essayez à nouveau dans %d minute.','Trop de connexions échouées, essayez à nouveau dans %d minutes.'),ceil($Md/60)));}$sa=$_POST["auth"];if($sa){session_regenerate_id();$Wg=$sa["driver"];$O=$sa["server"];$Rg=$sa["username"];$_e=(string)$sa["password"];$j=$sa["db"];set_password($Wg,$O,$Rg,$_e);$_SESSION["db"][$Wg][$O][$Rg][$j]=true;if($sa["permanent"]){$z=base64_encode($Wg)."-".base64_encode($O)."-".base64_encode($Rg)."-".base64_encode($j);$Re=$b->permanentLogin(true);$De[$z]="$z:".base64_encode($Re?encrypt_string($_e,$Re):"");cookie("adminer_permanent",implode(" ",$De));}if(count($_POST)==1||DRIVER!=$Wg||SERVER!=$O||$_GET["username"]!==$Rg||DB!=$j)redirect(auth_url($Wg,$O,$Rg,$j));}elseif($_POST["logout"]&&(!$Cc||verify_token())){foreach(array("pwds","db","dbs","queries")as$z)set_session($z,null);unset_permanent();redirect(substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1),'Au revoir !'.' '.'Thanks for using Adminer, consider donating.');}elseif($De&&!$_SESSION["pwds"]){session_regenerate_id();$Re=$b->permanentLogin();foreach($De -as$z=>$X){list(,$Ia)=explode(":",$X);list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));set_password($Wg,$O,$Rg,decrypt_string(base64_decode($Ia),$Re));$_SESSION["db"][$Wg][$O][$Rg][$j]=true;}}function -unset_permanent(){global$De;foreach($De -as$z=>$X){list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));if($Wg==DRIVER&&$O==SERVER&&$Rg==$_GET["username"]&&$j==DB)unset($De[$z]);}cookie("adminer_permanent",implode(" ",$De));}function -auth_error($l){global$b,$Cc;$_f=session_name();if(isset($_GET["username"])){header("HTTP/1.1 403 Forbidden");if(($_COOKIE[$_f]||$_GET[$_f])&&!$Cc)$l='Session expirée, veuillez vous authentifier à nouveau.';else{restart_session();add_invalid_login();$_e=get_password();if($_e!==null){if($_e===false)$l.=($l?'
    ':'').sprintf('Le mot de passe a expiré. Implémentez la méthode %s afin de le rendre permanent.',target_blank(),'permanentLogin()');set_password(DRIVER,SERVER,$_GET["username"],null);}unset_permanent();}}if(!$_COOKIE[$_f]&&$_GET[$_f]&&ini_bool("session.use_only_cookies"))$l='Veuillez activer les sessions.';$ue=session_get_cookie_params();cookie("adminer_key",($_COOKIE["adminer_key"]?$_COOKIE["adminer_key"]:rand_string()),$ue["lifetime"]);page_header('Authentification',$l,null);echo"
    \n","
    ";if(hidden_fields($_POST,array("auth")))echo"

    ".'The action will be performed after successful login with the same credentials.'."\n";echo"

    \n";$b->loginForm();echo"
    \n";page_footer("auth");exit;}if(isset($_GET["username"])&&!class_exists("Min_DB")){unset($_SESSION["pwds"][DRIVER]);unset_permanent();page_header('Extension introuvable',sprintf('Aucune des extensions PHP supportées (%s) n\'est disponible.',implode(", ",$Le)),false);page_footer("auth");exit;}stop_session(true);if(isset($_GET["username"])&&is_string(get_password())){list($Hc,$He)=explode(":",SERVER,2);if(preg_match('~^\s*([-+]?\d+)~',$He,$C)&&($C[1]<1024||$C[1]>65535))auth_error('Connecting to privileged ports is not allowed.');check_invalid_login();$f=connect();$k=new -Min_Driver($f);}$rd=null;if(!is_object($f)||($rd=$b->login($_GET["username"],get_password()))!==true){$l=(is_string($f)?h($f):(is_string($rd)?$rd:'Authentification échouée.'));auth_error($l.(preg_match('~^ | $~',get_password())?'
    '.'There is a space in the input password which might be the cause.':''));}if($_POST["logout"]&&$Cc&&!verify_token()){page_header('Déconnexion','Token CSRF invalide. Veuillez renvoyer le formulaire.');page_footer("db");exit;}if($sa&&$_POST["token"])$_POST["token"]=$U;$l='';if($_POST){if(!verify_token()){$Pc="max_input_vars";$_d=ini_get($Pc);if(extension_loaded("suhosin")){foreach(array("suhosin.request.max_vars","suhosin.post.max_vars")as$z){$X=ini_get($z);if($X&&(!$_d||$X<$_d)){$Pc=$z;$_d=$X;}}}$l=(!$_POST["token"]&&$_d?sprintf('Le nombre maximum de champs est dépassé. Veuillez augmenter %s.',"'$Pc'"):'Token CSRF invalide. Veuillez renvoyer le formulaire.'.' '.'Si vous n\'avez pas envoyé cette requête depuis Adminer, alors fermez cette page.');}}elseif($_SERVER["REQUEST_METHOD"]=="POST"){$l=sprintf('Données POST trop grandes. Réduisez la taille des données ou augmentez la valeur de %s dans la configuration de PHP.',"'post_max_size'");if(isset($_GET["sql"]))$l.=' '.'Vous pouvez uploader un gros fichier SQL par FTP et ensuite l\'importer depuis le serveur.';}function -select($J,$g=null,$ie=array(),$_=0){global$y;$qd=array();$x=array();$e=array();$_a=array();$Cg=array();$K=array();odd('');for($u=0;(!$_||$u<$_)&&($L=$J->fetch_row());$u++){if(!$u){echo"
    \n","\n","";for($Zc=0;$Zcfetch_field();$F=$m->name;$he=$m->orgtable;$ge=$m->orgname;$K[$m->table]=$he;if($ie&&$y=="sql")$qd[$Zc]=($F=="table"?"table=":($F=="possible_keys"?"indexes=":null));elseif($he!=""){if(!isset($x[$he])){$x[$he]=array();foreach(indexes($he,$g)as$w){if($w["type"]=="PRIMARY"){$x[$he]=array_flip($w["columns"]);break;}}$e[$he]=$x[$he];}if(isset($e[$he][$ge])){unset($e[$he][$ge]);$x[$he][$ge]=$Zc;$qd[$Zc]=$he;}}if($m->charsetnr==63)$_a[$Zc]=true;$Cg[$Zc]=$m->type;echo"name!=$ge?" title='".h(($he!=""?"$he.":"").$ge)."'":"").">".h($F).($ie?'':"");}echo"\n";}echo"";foreach($L -as$z=>$X){$A="";if(isset($qd[$z])&&!$e[$qd[$z]]){if($ie&&$y=="sql"){$R=$L[array_search("table=",$qd)];$A=ME.$qd[$z].urlencode($ie[$R]!=""?$ie[$R]:$R);}else{$A=ME."edit=".urlencode($qd[$z]);foreach($x[$qd[$z]]as$Ma=>$Zc)$A.="&where".urlencode("[".bracket_escape($Ma)."]")."=".urlencode($L[$Zc]);}}elseif(is_url($X))$A=$X;if($X===null)$X="NULL";elseif($_a[$z]&&!is_utf8($X))$X="".lang(array('%d octet','%d octets'),strlen($X))."";else{$X=h($X);if($Cg[$z]==254)$X="$X";}if($A)$X="$X";echo"
    $X";}}echo($u?"
    \n
    ":"

    ".'Aucun résultat.')."\n";return$K;}function -referencable_primary($vf){$K=array();foreach(table_status('',true)as$Wf=>$R){if($Wf!=$vf&&fk_support($R)){foreach(fields($Wf)as$m){if($m["primary"]){if($K[$Wf]){unset($K[$Wf]);break;}$K[$Wf]=$m;}}}}return$K;}function -adminer_settings(){parse_str($_COOKIE["adminer_settings"],$Bf);return$Bf;}function -adminer_setting($z){$Bf=adminer_settings();return$Bf[$z];}function -set_adminer_settings($Bf){return -cookie("adminer_settings",http_build_query($Bf+adminer_settings()));}function -textarea($F,$Y,$M=10,$Qa=80){global$y;echo"";}function -edit_type($z,$m,$Pa,$q=array(),$ec=array()){global$Of,$Cg,$Jg,$Wd;$V=$m["type"];echo'',"',($Jg?"':''),(isset($m['on_update'])?"':''),($q?" ":" ");}function -process_length($nd){global$Qb;return(preg_match("~^\\s*\\(?\\s*$Qb(?:\\s*,\\s*$Qb)*+\\s*\\)?\\s*\$~",$nd)&&preg_match_all("~$Qb~",$nd,$ud)?"(".implode(",",$ud[0]).")":preg_replace('~^[0-9].*~','(\0)',preg_replace('~[^-0-9,+()[\]]~','',$nd)));}function -process_type($m,$Na="COLLATE"){global$Jg;return" $m[type]".process_length($m["length"]).(preg_match(number_type(),$m["type"])&&in_array($m["unsigned"],$Jg)?" $m[unsigned]":"").(preg_match('~char|text|enum|set~',$m["type"])&&$m["collation"]?" $Na ".q($m["collation"]):"");}function -process_field($m,$Bg){return -array(idf_escape(trim($m["field"])),process_type($Bg),($m["null"]?" NULL":" NOT NULL"),default_value($m),(preg_match('~timestamp|datetime~',$m["type"])&&$m["on_update"]?" ON UPDATE $m[on_update]":""),(support("comment")&&$m["comment"]!=""?" COMMENT ".q($m["comment"]):""),($m["auto_increment"]?auto_increment():null),);}function -default_value($m){$ob=$m["default"];return($ob===null?"":" DEFAULT ".(preg_match('~char|binary|text|enum|set~',$m["type"])||preg_match('~^(?![a-z])~i',$ob)?q($ob):$ob));}function -type_class($V){foreach(array('char'=>'text','date'=>'time|year','binary'=>'blob','enum'=>'set',)as$z=>$X){if(preg_match("~$z|$X~",$V))return" class='$z'";}}function -edit_fields($n,$Pa,$V="TABLE",$q=array()){global$Qc;$n=array_values($n);$pb=(($_POST?$_POST["defaults"]:adminer_setting("defaults"))?"":" class='hidden'");$Ua=(($_POST?$_POST["comments"]:adminer_setting("comments"))?"":" class='hidden'");echo' -';if($V=="PROCEDURE"){echo'';}echo'',($V=="TABLE"?'Nom de la colonne':'Nom du paramètre'),'Type',script("qs('#enum-edit').onblur = editingLengthBlur;"),'Longueur -','Options';if($V=="TABLE"){echo'NULL -AI',doc_link(array('sqlite'=>"autoinc.html",)),'Valeur par défaut -',(support("comment")?"".'Commentaire':"");}echo'',"".script("row_count = ".count($n).";"),' - -',script("mixin(qsl('tbody'), {onclick: editingClick, onkeydown: editingKeydown, oninput: editingInput});");foreach($n -as$u=>$m){$u++;$je=$m[($_POST?"orig":"field")];$wb=(isset($_POST["add"][$u-1])||(isset($m["field"])&&!$_POST["drop_col"][$u]))&&(support("drop_col")||$je=="");echo' -',($V=="PROCEDURE"?"".html_select("fields[$u][inout]",explode("|",$Qc),$m["inout"]):""),'';if($wb){echo'';}echo'';edit_type("fields[$u]",$m,$Pa,$q);if($V=="TABLE"){echo'',checkbox("fields[$u][null]",1,$m["null"],"","","block","label-null"),'',checkbox("fields[$u][has_default]",1,$m["has_default"],"","","","label-default"),'',(support("comment")?"":"");}echo"",(support("move_col")?" "." "." ":""),($je==""||support("drop_col")?"":"");}}function -process_fields(&$n){$Sd=0;if($_POST["up"]){$hd=0;foreach($n -as$z=>$m){if(key($_POST["up"])==$z){unset($n[$z]);array_splice($n,$hd,0,array($m));break;}if(isset($m["field"]))$hd=$Sd;$Sd++;}}elseif($_POST["down"]){$rc=false;foreach($n -as$z=>$m){if(isset($m["field"])&&$rc){unset($n[key($_POST["down"])]);array_splice($n,$Sd,0,array($rc));break;}if(key($_POST["down"])==$z)$rc=$m;$Sd++;}}elseif($_POST["add"]){$n=array_values($n);array_splice($n,key($_POST["add"]),0,array(array()));}elseif(!$_POST["drop_col"])return +select_input($_a,array$gg,$Y="",$ag="",$Og=""){$Li=($gg?"select":"input");return"<$Li$_a".($gg?">

    ".sprintf('Version de %s : %s via l\'extension PHP %s',$zb[DRIVER],"".h($f->server_info)."","$f->extension")."\n","

    ".sprintf('Authentifié en tant que : %s',"".h(logged_user())."")."\n";$i=$b->databases();if($i){$rf=support("scheme");$Pa=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$i=($_GET["dbsize"]?count_tables($i):array_flip($i));foreach($i -as$j=>$T){$mf=h(ME)."db=".urlencode($j);$v=h("Db-".$j);echo"".(support("database")?"
    ":"")."".'Base de données'." - ".'Rafraîchir'.""."".'Interclassement'."".'Tables'."".'Taille'." - ".'Calcul'."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$j,in_array($j,(array)$_POST["db"]),"","","",$v):""),"".h($j)."";$Oa=h(db_collation($j,$Pa));echo"".(support("database")?"$Oa":$Oa),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($j):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),"\n","
    \n",script("tableCheck();");}}page_footer("db");}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?$f->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}connect_error();exit;}$Wd="RESTRICT|NO ACTION|CASCADE|SET NULL|SET DEFAULT";class -TmpFile{var$handler;var$size;function +normalize_enum(array$A){$X=$A[0];return"'".str_replace("'","''",addcslashes(stripcslashes(str_replace($X[0].$X[0],$X[0],substr($X,1,-1))),'\\'))."'";}function +grant($vd,array$eh,$e,$Xf){if(!$eh)return +true;if($eh==array("ALL PRIVILEGES","GRANT OPTION"))return($vd=="GRANT"?queries("$vd ALL PRIVILEGES$Xf WITH GRANT OPTION"):queries("$vd ALL PRIVILEGES$Xf")&&queries("$vd GRANT OPTION$Xf"));return +queries("$vd ".preg_replace('~(GRANT OPTION)\([^)]*\)~','\1',implode("$e, ",$eh).$e).$Xf);}function +drop_create($jc,$i,$lc,$Pi,$nc,$We,$tf,$rf,$sf,$Uf,$Gf){if($_POST["drop"])query_redirect($jc,$We,$tf);elseif($Uf=="")query_redirect($i,$We,$sf);elseif($Uf!=$Gf){$Gb=queries($i);queries_redirect($We,$rf,$Gb&&queries($jc));if($Gb)queries($lc);}else +queries_redirect($We,$rf,queries($Pi)&&queries($nc)&&queries($jc)&&queries($i));}function +create_trigger($Xf,array$K){$Vi=" $K[Timing] $K[Event]".(preg_match('~ OF~',$K["Event"])?" $K[Of]":"");return"CREATE TRIGGER ".idf_escape($K["Trigger"]).(JUSH=="mssql"?$Xf.$Vi:$Vi.$Xf).rtrim(" $K[Type]\n$K[Statement]",";").";";}function +create_routine($Dh,array$K){$O=array();$o=(array)$K["fields"];ksort($o);foreach($o +as$n){if($n["field"]!="")$O[]=(preg_match("~^(".driver()->inout.")\$~",$n["inout"])?"$n[inout] ":"").idf_escape($n["field"]).process_type($n,"CHARACTER SET");}$Xb=rtrim($K["definition"],";");return"CREATE $Dh ".idf_escape(trim($K["name"]))." (".implode(", ",$O).")".($Dh=="FUNCTION"?" RETURNS".process_type($K["returns"],"CHARACTER SET"):"").($K["language"]?" LANGUAGE $K[language]":"").(JUSH=="pgsql"?" AS ".q($Xb):"\n$Xb;");}function +remove_definer($H){return +preg_replace('~^([A-Z =]+) DEFINER=`'.preg_replace('~@(.*)~','`@`(%|\1)',logged_user()).'`~','\1',$H);}function +format_foreign_key(array$q){$k=$q["db"];$Lf=$q["ns"];return" FOREIGN KEY (".implode(", ",array_map('Adminer\idf_escape',$q["source"])).") REFERENCES ".($k!=""&&$k!=$_GET["db"]?idf_escape($k).".":"").($Lf!=""&&$Lf!=$_GET["ns"]?idf_escape($Lf).".":"").idf_escape($q["table"])." (".implode(", ",array_map('Adminer\idf_escape',$q["target"])).")".(preg_match("~^(".driver()->onActions.")\$~",$q["on_delete"])?" ON DELETE $q[on_delete]":"").(preg_match("~^(".driver()->onActions.")\$~",$q["on_update"])?" ON UPDATE $q[on_update]":"").($q["deferrable"]?" $q[deferrable]":"");}function +tar_file($p,$aj){$J=pack("a100a8a8a8a12a12",$p,644,0,0,decoct($aj->size),decoct(time()));$db=8*32;for($t=0;$tsend();echo +str_repeat("\0",511-($aj->size+511)%512);}function +doc_link(array$Kg,$Qi="?"){$Zh=connection()->server_info;$Qj=preg_replace('~^(\d\.?\d).*~s','\1',$Zh);$Ej=array('sql'=>"https://dev.mysql.com/doc/refman/$Qj/en/",'sqlite'=>"https://www.sqlite.org/",'pgsql'=>"https://www.postgresql.org/docs/".(connection()->flavor=='cockroach'?"current":$Qj)."/",'mssql'=>"https://learn.microsoft.com/en-us/sql/",'oracle'=>"https://www.oracle.com/pls/topic/lookup?ctx=db".preg_replace('~^.* (\d+)\.(\d+)\.\d+\.\d+\.\d+.*~s','\1\2',$Zh)."&id=",);if(connection()->flavor=='maria'){$Ej['sql']="https://mariadb.com/kb/en/";$Kg['sql']=(isset($Kg['mariadb'])?$Kg['mariadb']:str_replace(".html","/",$Kg['sql']));}return($Kg[JUSH]?"$Qi":"");}function +db_size($k){if(!connection()->select_db($k))return"?";$J=0;foreach(table_status()as$S)$J+=$S["Data_length"]+$S["Index_length"];return +format_number($J);}function +set_utf8mb4($i){static$O=false;if(!$O&&preg_match('~\butf8mb4~i',$i)){$O=true;echo"SET NAMES ".charset(connection()).";\n\n";}}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?connection()->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}if(DB!=""){header("HTTP/1.1 404 Not Found");page_header(lang(38).": ".h(DB),lang(118),true);}else{if($_POST["db"]&&!$m)queries_redirect(substr(ME,0,-1),lang(119),drop_databases($_POST["db"]));page_header(lang(120),$m,false);echo"

    ".lang(125,get_driver(DRIVER),"".h(connection()->server_info)."","".connection()->extension."")."\n","

    ".lang(126,"".h(logged_user())."")."\n";$j=adminer()->databases();if($j){$Lh=support("scheme");$lb=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$j=($_GET["dbsize"]?count_tables($j):array_flip($j));foreach($j +as$k=>$T){$Ch=h(ME)."db=".urlencode($k);$u=h("Db-".$k);echo"".(support("database")?"
    ":"")."".lang(38).(get_session("dbs")!==null?" - ".lang(127)."":"")."".lang(128)."".lang(129)."".lang(130)." - ".lang(131)."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$k,in_array($k,(array)$_POST["db"]),"","","",$u):""),"".h($k)."";$c=h(db_collation($k,$lb));echo"".(support("database")?"$c":$c),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($k):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),input_token(),"
    \n",script("tableCheck();");}if(!empty(adminer()->plugins)){echo"
    \n","

    ".lang(134)."

    \n
      \n";foreach(adminer()->plugins +as$Pg){$bc=(method_exists($Pg,'description')?$Pg->description():"");if(!$bc){$sh=new +\ReflectionObject($Pg);if(preg_match('~^/[\s*]+(.+)~',$sh->getDocComment(),$A))$bc=$A[1];}$Mh=(method_exists($Pg,'screenshot')?$Pg->screenshot():"");echo"
    • ".get_class($Pg)."".h($bc?": $bc":"").($Mh?" (".lang(135).")":"")."\n";}echo"
    \n";adminer()->pluginsLinks();echo"
    \n";}}page_footer("db");exit;}if(support("scheme")){if(DB!=""&&$_GET["ns"]!==""){if(!isset($_GET["ns"]))redirect(preg_replace('~ns=[^&]*&~','',ME)."ns=".get_schema());if(!set_schema($_GET["ns"])){header("HTTP/1.1 404 Not Found");page_header(lang(80).": ".h($_GET["ns"]),lang(136),true);page_footer("ns");exit;}}}adminer()->afterConnect();class +TmpFile{private$handler;var$size;function __construct(){$this->handler=tmpfile();}function -write($Za){$this->size+=strlen($Za);fwrite($this->handler,$Za);}function -send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}$Qb="'(?:''|[^'\\\\]|\\\\.)*'";$Qc="IN|OUT|INOUT";if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["download"])){$a=$_GET["download"];$n=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$N=array(idf_escape($_GET["field"]));$J=$k->select($a,$N,array(where($_GET,$n)),$N);$L=($J?$J->fetch_row():array());echo$k->value($L[0],$n[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$n=fields($a);if(!$n)$l=error();$S=table_status1($a,true);$F=$b->tableName($S);page_header(($n&&is_view($S)?$S['Engine']=='materialized view'?'Vue matérialisée':'Vue':'Table').": ".($F!=""?$F:h($a)),$l);$b->selectLinks($S);$Ta=$S["Comment"];if($Ta!="")echo"

    ".'Commentaire'.": ".h($Ta)."\n";if($n)$b->tableStructurePrint($n);if(!is_view($S)){if(support("indexes")){echo"

    ".'Index'."

    \n";$x=indexes($a);if($x)$b->tableIndexesPrint($x);echo'

    ".'Clés étrangères'."

    \n";$q=foreign_keys($a);if($q){echo"\n","\n";foreach($q -as$F=>$p){echo"","
    ".'Source'."".'Cible'."".'ON DELETE'."".'ON UPDATE'."
    ".implode(", ",array_map('h',$p["source"]))."","".($p["db"]!=""?"".h($p["db"]).".":"").($p["ns"]!=""?"".h($p["ns"]).".":"").h($p["table"])."","(".implode(", ",array_map('h',$p["target"])).")","".h($p["on_delete"])."\n","".h($p["on_update"])."\n",''.'Modifier'.'';}echo"
    \n";}echo'

    ".'Déclencheurs'."

    \n";$Ag=triggers($a);if($Ag){echo"\n";foreach($Ag -as$z=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($z)."".'Modifier'."\n";echo"
    \n";}echo'
    +write($Ab){$this->size+=strlen($Ab);fwrite($this->handler,$Ab);}function +send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["callf"]))$_GET["call"]=$_GET["callf"];if(isset($_GET["function"]))$_GET["procedure"]=$_GET["function"];if(isset($_GET["download"])){$a=$_GET["download"];$o=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$M=array(idf_escape($_GET["field"]));$I=driver()->select($a,$M,array(where($_GET,$o)),$M);$K=($I?$I->fetch_row():array());echo +driver()->value($K[0],$o[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$o=fields($a);if(!$o)$m=error()?:lang(11);$S=table_status1($a);$B=adminer()->tableName($S);page_header(($o&&is_view($S)?$S['Engine']=='materialized view'?lang(137):lang(138):lang(139)).": ".($B!=""?$B:h($a)),$m);$Bh=array();foreach($o +as$y=>$n)$Bh+=$n["privileges"];adminer()->selectLinks($S,(isset($Bh["insert"])||!support("table")?"":null));$qb=$S["Comment"];if($qb!="")echo"

    ".lang(51).": ".h($qb)."\n";if($o)adminer()->tableStructurePrint($o,$S);function +tables_links(array$T){echo"

    \n";}$ke=driver()->inheritsFrom($a);if($ke){echo"

    ".lang(140)."

    \n";tables_links($ke);}if(support("indexes")&&driver()->supportsIndex($S)){echo"

    ".lang(141)."

    \n";$x=indexes($a);if($x)adminer()->tableIndexesPrint($x,$S);echo'

    ".lang(106)."

    \n";$md=foreign_keys($a);if($md){echo"\n","\n";foreach($md +as$B=>$q){echo"","
    ".lang(143)."".lang(144)."".lang(109)."".lang(108)."
    ".implode(", ",array_map('Adminer\h',$q["source"]))."";$_=($q["db"]!=""?preg_replace('~db=[^&]*~',"db=".urlencode($q["db"]),ME):($q["ns"]!=""?preg_replace('~ns=[^&]*~',"ns=".urlencode($q["ns"]),ME):ME));echo"".($q["db"]!=""&&$q["db"]!=DB?"".h($q["db"]).".":"").($q["ns"]!=""&&$q["ns"]!=$_GET["ns"]?"".h($q["ns"]).".":"").h($q["table"])."","(".implode(", ",array_map('Adminer\h',$q["target"])).")","".h($q["on_delete"]),"".h($q["on_update"]),''.lang(145).'',"\n";}echo"
    \n";}echo'

    ".lang(147)."

    \n";$Za=driver()->checkConstraints($a);if($Za){echo"\n";foreach($Za +as$y=>$X)echo"","
    ".h($X),"".lang(145)."","\n";echo"
    \n";}echo'

    ".lang(149)."

    \n";$oj=triggers($a);if($oj){echo"\n";foreach($oj +as$y=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($y)."".lang(145)."\n";echo"
    \n";}echo'

    ".lang(151)."

    \n";$Dg=driver()->partitionsInfo($a);if($Dg)echo"

    BY ".h("$Dg[partition_by]($Dg[partition])")."\n";tables_links($je);}}elseif(isset($_GET["schema"])){page_header(lang(71),"",array(),h(DB.($_GET["ns"]?".$_GET[ns]":"")));$Fi=array();$Gi=array();$da=($_GET["schema"]?:$_COOKIE["adminer_schema-".str_replace(".","_",DB)]);preg_match_all('~([^:]+):([-0-9.]+)x([-0-9.]+)(_|$)~',$da,$df,PREG_SET_ORDER);foreach($df +as$t=>$A){$Fi[$A[1]]=array($A[2],$A[3]);$Gi[]="\n\t'".js_escape($A[1])."': [ $A[2], $A[3] ]";}$dj=0;$Ia=-1;$Jh=array();$rh=array();$Pe=array();$ua=driver()->allFields();foreach(table_status('',true)as$R=>$S){if(is_view($S))continue;$Sg=0;$Jh[$R]["fields"]=array();foreach($ua[$R]as$n){$Sg+=1.25;$n["pos"]=$Sg;$Jh[$R]["fields"][$n["field"]]=$n;}$Jh[$R]["pos"]=($Fi[$R]?:array($dj,0));foreach(adminer()->foreignKeys($R)as$X){if(!$X["db"]){$Ne=$Ia;if(idx($Fi[$R],1)||idx($Fi[$X["table"]],1))$Ne=min(idx($Fi[$R],1,0),idx($Fi[$X["table"]],1,0))-1;else$Ia-=.1;while($Pe[(string)$Ne])$Ne-=.0001;$Jh[$R]["references"][$X["table"]][(string)$Ne]=array($X["source"],$X["target"]);$rh[$X["table"]][$R][(string)$Ne]=$X["target"];$Pe[(string)$Ne]=true;}}$dj=max($dj,$Jh[$R]["pos"][0]+2.5+$Sg);}echo'

    -qs(\'#schema\').onselectstart = function () { return false; }; -var tablePos = {',implode(",",$Yf)."\n",'}; -var em = qs(\'#schema\').offsetHeight / ',$sg,'; +qs(\'#schema\').onselectstart = () => false; +const tablePos = {',implode(",",$Gi)."\n",'}; +const em = qs(\'#schema\').offsetHeight / ',$dj,'; document.onmousemove = schemaMousemove; document.onmouseup = partialArg(schemaMouseup, \'',js_escape(DB),'\'); -';foreach($qf -as$F=>$R){echo"
    ",''.h($F)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$m){$X=''.h($m["field"]).'';echo"
    ".($m["primary"]?"$X":$X);}foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$kd=$jd-$Xf[$F][1];$u=0;foreach($cf[0]as$Ff)echo"\n
    ";}}foreach((array)$ff[$F]as$eg=>$gf){foreach($gf -as$jd=>$e){$kd=$jd-$Xf[$F][1];$u=0;foreach($e -as$dg)echo"\n
    ";}}echo"\n
    \n";}foreach($qf -as$F=>$R){foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$Gd=$sg;$yd=-10;foreach($cf[0]as$z=>$Ff){$Je=$R["pos"][0]+$R["fields"][$Ff]["pos"];$Ke=$qf[$eg]["pos"][0]+$qf[$eg]["fields"][$cf[1][$z]]["pos"];$Gd=min($Gd,$Je,$Ke);$yd=max($yd,$Je,$Ke);}echo"
    \n";}}}echo'
    -
    ",''.h($B)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$n){$X=''.h($n["field"]).'';echo"
    ".($n["primary"]?"$X":$X);}foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($oh[0]as$ji)echo"\n
    "."
    ";}}foreach((array)$rh[$B]as$Ni=>$th){foreach($th +as$Ne=>$e){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($e +as$Mi)echo"\n
    "."
    "."
    ";}}echo"\n
    \n";}foreach($Jh +as$B=>$R){foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$wf=$dj;$jf=-10;foreach($oh[0]as$y=>$ji){$Tg=$R["pos"][0]+$R["fields"][$ji]["pos"];$Ug=$Jh[$Ni]["pos"][0]+$Jh[$Ni]["fields"][$oh[1][$y]]["pos"];$wf=min($wf,$Tg,$Ug);$jf=max($jf,$Tg,$Ug);}echo"
    \n";}}}echo'
    +
    - -';$lb=array('','USE','DROP+CREATE','CREATE');$Zf=array('','DROP+CREATE','CREATE');$ib=array('','TRUNCATE+INSERT','INSERT');if($y=="sql")$ib[]='INSERT+UPDATE';parse_str($_COOKIE["adminer_export"],$L);if(!$L)$L=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($L["events"])){$L["routines"]=$L["events"]=($_GET["dump"]=="");$L["triggers"]=$L["table_style"];}echo"
    ".'Sortie'."".html_select("output",$b->dumpOutput(),$L["output"],0)."\n";echo"
    ".'Format'."".html_select("format",$b->dumpFormat(),$L["format"],0)."\n";echo($y=="sqlite"?"":"
    ".'Base de données'."".html_select('db_style',$lb,$L["db_style"]).(support("routine")?checkbox("routines",1,$L["routines"],'Routines'):"").(support("event")?checkbox("events",1,$L["events"],'Évènements'):"")),"
    ".'Tables'."".html_select('table_style',$Zf,$L["table_style"]).checkbox("auto_increment",1,$L["auto_increment"],'Incrément automatique').(support("trigger")?checkbox("triggers",1,$L["triggers"],'Déclencheurs'):""),"
    ".'Données'."".html_select('data_style',$ib,$L["data_style"]),'
    -

    - - - -',script("qsl('table').onclick = dumpClick;");$Ne=array();if(DB!=""){$Fa=($a!=""?"":" checked");echo"","\n";$Zg="";$ag=tables_list();foreach($ag -as$F=>$V){$Me=preg_replace('~_.*~','',$F);$Fa=($a==""||$a==(substr($a,-1)=="%"?"$Me%":$F));$Qe="\n";$i=$b->databases();if($i){foreach($i -as$j){if(!information_schema($j)){$Me=preg_replace('~_.*~','',$j);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$F,$Fa,$F,"","block");if($V!==null&&!preg_match('~table~i',$V))$Zg.="$Qe\n";else -echo"$Qe\n";$Ne[$Me]++;}echo$Zg;if($ag)echo -script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$j,$a==""||$a=="$Me%",$j,"","block")."\n";$Ne[$Me]++;}}}else + +';$Rb=array('','USE','DROP+CREATE','CREATE');$Hi=array('','DROP+CREATE','CREATE');$Ob=array('','TRUNCATE+INSERT','INSERT');if(JUSH=="sql")$Ob[]='INSERT+UPDATE';$K=get_settings("adminer_export");if(!$K)$K=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($K["events"])){$K["routines"]=$K["events"]=($_GET["dump"]=="");$K["triggers"]=$K["table_style"];}echo"
    ".lang(153)."".html_radios("output",adminer()->dumpOutput(),$K["output"])."\n","
    ".lang(154)."".html_radios("format",adminer()->dumpFormat(),$K["format"])."\n",(JUSH=="sqlite"?"":"
    ".lang(38)."".html_select('db_style',$Rb,$K["db_style"]).(support("type")?checkbox("types",1,$K["types"],lang(6)):"").(support("routine")?checkbox("routines",1,$K["routines"],lang(73)):"").(support("event")?checkbox("events",1,$K["events"],lang(75)):"")),"
    ".lang(129)."".html_select('table_style',$Hi,$K["table_style"]).checkbox("auto_increment",1,$K["auto_increment"],lang(52)).(support("trigger")?checkbox("triggers",1,$K["triggers"],lang(149)):""),"
    ".lang(155)."".html_select('data_style',$Ob,$K["data_style"]),'
    +

    +',input_token(),' + +',script("qsl('table').onclick = dumpClick;");$Yg=array();if(DB!=""){$bb=($a!=""?"":" checked");echo"","\n";$Sj="";$Ji=tables_list();foreach($Ji +as$B=>$U){$Xg=preg_replace('~_.*~','',$B);$bb=($a==""||$a==(substr($a,-1)=="%"?"$Xg%":$B));$bh="\n";$j=adminer()->databases();if($j){foreach($j +as$k){if(!information_schema($k)){$Xg=preg_replace('~_.*~','',$k);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$B,$bb,$B,"","block");if($U!==null&&!preg_match('~table~i',$U))$Sj +.="$bh\n";else +echo"$bh\n";$Yg[$Xg]++;}echo$Sj;if($Ji)echo +script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$k,$a==""||$a=="$Xg%",$k,"","block")."\n";$Yg[$Xg]++;}}}else echo"
    ";}echo'
    -';$lc=true;foreach($Ne -as$z=>$X){if($z!=""&&$X>1){echo($lc?"

    ":" ")."".h($z)."";$lc=false;}}}elseif(isset($_GET["sql"])){if(!$l&&$_POST["export"]){dump_headers("sql");$b->dumpTable("","");$b->dumpData("","table",$_POST["query"]);exit;}restart_session();$Gc=&get_session("queries");$Fc=&$Gc[DB];if(!$l&&$_POST["clear"]){$Fc=array();redirect(remove_from_uri("history"));}page_header((isset($_GET["import"])?'Importer':'Requête SQL'),$l);if(!$l&&$_POST){$r=false;if(!isset($_GET["import"]))$I=$_POST["query"];elseif($_POST["webfile"]){$If=$b->importServerPath();$r=@fopen((file_exists($If)?$If:"compress.zlib://$If.gz"),"rb");$I=($r?fread($r,1e6):false);}else$I=get_file("sql_file",true);if(is_string($I)){if(function_exists('memory_get_usage'))@ini_set("memory_limit",max(ini_bytes("memory_limit"),2*strlen($I)+memory_get_usage()+8e6));if($I!=""&&strlen($I)<1e6){$H=$I.(preg_match("~;[ \t\r\n]*\$~",$I)?"":";");if(!$Fc||reset(end($Fc))!=$H){restart_session();$Fc[]=array($H,time());set_session("queries",$Gc);stop_session();}}$Gf="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|-- )[^\n]*\n?|--\r?\n)";$rb=";";$Sd=0;$Nb=true;$g=connect();if(is_object($g)&&DB!=""){$g->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$g);}$Sa=0;$Sb=array();$ve='[\'"'.($y=="sql"?'`#':($y=="sqlite"?'`[':($y=="mssql"?'[':''))).']|/\*|-- |$'.($y=="pgsql"?'|\$[^$]*\$':'');$tg=microtime(true);parse_str($_COOKIE["adminer_export"],$ia);$Eb=$b->dumpFormat();unset($Eb["sql"]);while($I!=""){if(!$Sd&&preg_match("~^$Gf*+DELIMITER\\s+(\\S+)~i",$I,$C)){$rb=$C[1];$I=substr($I,strlen($C[0]));}else{preg_match('('.preg_quote($rb)."\\s*|$ve)",$I,$C,PREG_OFFSET_CAPTURE,$Sd);list($rc,$Ie)=$C[0];if(!$rc&&$r&&!feof($r))$I.=fread($r,1e5);else{if(!$rc&&rtrim($I)=="")break;$Sd=$Ie+strlen($rc);if($rc&&rtrim($rc)!=$rb){while(preg_match('('.($rc=='/*'?'\*/':($rc=='['?']':(preg_match('~^-- |^#~',$rc)?"\n":preg_quote($rc)."|\\\\."))).'|$)s',$I,$C,PREG_OFFSET_CAPTURE,$Sd)){$pf=$C[0][0];if(!$pf&&$r&&!feof($r))$I.=fread($r,1e5);else{$Sd=$C[0][1]+strlen($pf);if($pf[0]!="\\")break;}}}else{$Nb=false;$H=substr($I,0,$Ie);$Sa++;$Qe="

    ".$b->sqlCommandQuery($H)."
    \n";if($y=="sqlite"&&preg_match("~^$Gf*+ATTACH\\b~i",$H,$C)){echo$Qe,"

    ".'ATTACH queries are not supported.'."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$Qe;ob_flush();flush();}$Lf=microtime(true);if($f->multi_query($H)&&is_object($g)&&preg_match("~^$Gf*+USE\\b~i",$H))$g->query($H);do{$J=$f->store_result();if($f->error){echo($_POST["only_errors"]?$Qe:""),"

    ".'Erreur dans la requête'.($f->errno?" ($f->errno)":"").": ".error()."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break -2;}else{$jg=" (".format_time($Lf).")".(strlen($H)<1000?" ".'Modifier'."":"");$ka=$f->affected_rows;$ch=($_POST["only_errors"]?"":$k->warnings());$dh="warnings-$Sa";if($ch)$jg.=", ".'Warnings'."".script("qsl('a').onclick = partial(toggle, '$dh');","");$Zb=null;$ac="explain-$Sa";if(is_object($J)){$_=$_POST["limit"];$ie=select($J,$g,array(),$_);if(!$_POST["only_errors"]){echo"

    \n";$Pd=$J->num_rows;echo"

    ".($Pd?($_&&$Pd>$_?sprintf('%d / ',$_):"").lang(array('%d ligne','%d lignes'),$Pd):""),$jg;if($g&&preg_match("~^($Gf|\\()*+SELECT\\b~i",$H)&&($Zb=explain($g,$H)))echo", Explain".script("qsl('a').onclick = partial(toggle, '$ac');","");$v="export-$Sa";echo", ".'Exporter'."".script("qsl('a').onclick = partial(toggle, '$v');","")."\n"."

    \n";}}else{if(preg_match("~^$Gf*+(CREATE|DROP|ALTER)$Gf++(DATABASE|SCHEMA)\\b~i",$H)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(array('Requête exécutée avec succès, %d ligne modifiée.','Requête exécutée avec succès, %d lignes modifiées.'),$ka)."$jg\n";}echo($ch?"

    \n":"");if($Zb){echo"\n";}}$Lf=microtime(true);}while($f->next_result());}$I=substr($I,$Sd);$Sd=0;}}}}if($Nb)echo"

    ".'Aucune commande à exécuter.'."\n";elseif($_POST["only_errors"]){echo"

    ".lang(array('%d requête exécutée avec succès.','%d requêtes exécutées avec succès.'),$Sa-count($Sb))," (".format_time($tg).")\n";}elseif($Sb&&$Sa>1)echo"

    ".'Erreur dans la requête'.": ".implode("",$Sb)."\n";}else -echo"

    ".upload_error($I)."\n";}echo' +';$cd=true;foreach($Yg +as$y=>$X){if($y!=""&&$X>1){echo($cd?"

    ":" ")."".h($y)."";$cd=false;}}}elseif(isset($_GET["privileges"])){page_header(lang(72));echo'

    \n";hidden_fields_get();echo +input_hidden("db",DB),($vd?"":input_hidden("grant")),"\n","\n";while($K=$I->fetch_assoc())echo'
    ".lang(36)."".lang(34)."
    '.h($K["User"])."".h($K["Host"]).''.lang(12)."\n";if(!$vd||DB!="")echo"
    \n";echo"
    \n","

    \n";}elseif(isset($_GET["sql"])){if(!$m&&$_POST["export"]){save_settings(array("output"=>$_POST["output"],"format"=>$_POST["format"]),"adminer_import");dump_headers("sql");if($_POST["format"]=="sql")echo"$_POST[query]\n";else{adminer()->dumpTable("","");adminer()->dumpData("","table",$_POST["query"]);adminer()->dumpFooter();}exit;}restart_session();$Ld=&get_session("queries");$Kd=&$Ld[DB];if(!$m&&$_POST["clear"]){$Kd=array();redirect(remove_from_uri("history"));}stop_session();page_header((isset($_GET["import"])?lang(76):lang(65)),$m);$Ue='--'.(JUSH=='sql'?' ':'');if(!$m&&$_POST){$r=false;if(!isset($_GET["import"]))$H=$_POST["query"];elseif($_POST["webfile"]){$ni=adminer()->importServerPath();$r=@fopen((file_exists($ni)?$ni:"compress.zlib://$ni.gz"),"rb");$H=($r?fread($r,1e6):false);}else$H=get_file("sql_file",true,";");if(is_string($H)){if(function_exists('memory_get_usage')&&($of=ini_bytes("memory_limit"))!="-1")@ini_set("memory_limit",max($of,strval(2*strlen($H)+memory_get_usage()+8e6)));if($H!=""&&strlen($H)<1e6){$hh=$H.(preg_match("~;[ \t\r\n]*\$~",$H)?"":";");if(!$Kd||first(end($Kd))!=$hh){restart_session();$Kd[]=array($hh,time());set_session("queries",$Ld);stop_session();}}$ki="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|$Ue)[^\n]*\n?|--\r?\n)";$Zb=driver()->delimiter;$C=0;$xc=true;$h=connect();if($h&&DB!=""){$h->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$h);}$pb=0;$Ec=array();$Ag='[\'"'.(JUSH=="sql"?'`#':(JUSH=="sqlite"?'`[':(JUSH=="mssql"?'[':''))).']|/\*|'.$Ue.'|$'.(JUSH=="pgsql"?'|\$([a-zA-Z]\w*)?\$':'');$ej=microtime(true);$oa=get_settings("adminer_import");while($H!=""){if(!$C&&preg_match("~^$ki*+DELIMITER\\s+(\\S+)~i",$H,$A)){$Zb=preg_quote($A[1]);$H=substr($H,strlen($A[0]));}elseif(!$C&&JUSH=='pgsql'&&preg_match("~^($ki*+COPY\\s+)[^;]+\\s+FROM\\s+stdin;~i",$H,$A)){$Zb="\n\\\\\\.\r?\n";$C=strlen($A[0]);}else{preg_match("($Zb\\s*|$Ag)",$H,$A,PREG_OFFSET_CAPTURE,$C);list($od,$Sg)=$A[0];if(!$od&&$r&&!feof($r))$H +.=fread($r,1e5);else{if(!$od&&rtrim($H)=="")break;$C=$Sg+strlen($od);if($od&&!preg_match("(^$Zb)",$od)){$Ta=driver()->hasCStyleEscapes()||(JUSH=="pgsql"&&($Sg>0&&strtolower($H[$Sg-1])=="e"));$Lg=($od=='/*'?'\*/':($od=='['?']':(preg_match("~^$Ue|^#~",$od)?"\n":preg_quote($od).($Ta?'|\\\\.':''))));while(preg_match("($Lg|\$)s",$H,$A,PREG_OFFSET_CAPTURE,$C)){$Hh=$A[0][0];if(!$Hh&&$r&&!feof($r))$H +.=fread($r,1e5);else{$C=$A[0][1]+strlen($Hh);if(!$Hh||$Hh[0]!="\\")break;}}}else{$xc=false;$hh=substr($H,0,$Sg+($Zb[0]=="\n"?3:0));$pb++;$bh="
    ".adminer()->sqlCommandQuery($hh)."
    \n";if(JUSH=="sqlite"&&preg_match("~^$ki*+ATTACH\\b~i",$hh,$A)){echo$bh,"

    ".lang(157)."\n";$Ec[]=" $pb";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$bh;ob_flush();flush();}$si=microtime(true);if(connection()->multi_query($hh)&&$h&&preg_match("~^$ki*+USE\\b~i",$hh))$h->query($hh);do{$I=connection()->store_result();if(connection()->error){echo($_POST["only_errors"]?$bh:""),"

    ".lang(158).(connection()->errno?" (".connection()->errno.")":"").": ".error()."\n";$Ec[]=" $pb";if($_POST["error_stops"])break +2;}else{$Ti=" (".format_time($si).")".(strlen($hh)<1000?" ".lang(12)."":"");$qa=connection()->affected_rows;$Vj=($_POST["only_errors"]?"":driver()->warnings());$Wj="warnings-$pb";if($Vj)$Ti +.=", ".lang(47)."".script("qsl('a').onclick = partial(toggle, '$Wj');","");$Mc=null;$mg=null;$Nc="explain-$pb";if(is_object($I)){$z=$_POST["limit"];$mg=print_select_result($I,$h,array(),$z);if(!$_POST["only_errors"]){echo"

    \n";$Nf=$I->num_rows;echo"
    \n";}}else{if(preg_match("~^$ki*+(CREATE|DROP|ALTER)$ki++(DATABASE|SCHEMA)\\b~i",$hh)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(161,$qa)."$Ti\n";}echo($Vj?"

    \n":"");if($Mc){echo"\n";}}$si=microtime(true);}while(connection()->next_result());}$H=substr($H,$C);$C=0;}}}}if($xc)echo"

    ".lang(162)."\n";elseif($_POST["only_errors"])echo"

    ".lang(163,$pb-count($Ec))," (".format_time($ej).")\n";elseif($Ec&&$pb>1)echo"

    ".lang(158).": ".implode("",$Ec)."\n";}else +echo"

    ".upload_error($H)."\n";}echo'

    -';$Xb="";if(!isset($_GET["import"])){$H=$_GET["sql"];if($_POST)$H=$_POST["query"];elseif($_GET["history"]=="all")$H=$Fc;elseif($_GET["history"]!="")$H=$Fc[$_GET["history"]][0];echo"

    ";textarea("query",$H,20);echo -script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    $Xb\n",'Limiter les lignes'.": \n";}else{echo"

    ".'Importer un fichier'."
    ";$zc=(extension_loaded("zlib")?"[.gz]":"");echo(ini_bool("file_uploads")?"SQL$zc (< ".ini_get("upload_max_filesize")."B): \n$Xb":'L\'importation de fichier est désactivée.'),"
    \n";$Mc=$b->importServerPath();if($Mc){echo"
    ".'Depuis le serveur'."
    ",sprintf('Fichier %s du serveur Web',"".h($Mc)."$zc"),' ',"
    \n";}echo"

    ";}echo -checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),'Arrêter en cas d\'erreur')."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),'Montrer seulement les erreurs')."\n","\n";if(!isset($_GET["import"])&&$Fc){print_fieldset("history",'Historique',$_GET["history"]!="");for($X=end($Fc);$X;$X=prev($Fc)){$z=key($Fc);list($H,$jg,$Ib)=$X;echo''.'Modifier'.""." ".@date("H:i:s",$jg).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace('~^(#|-- ).*~m','',$H)))),80,"").($Ib?" ($Ib)":"")."
    \n";}echo"\n","".'Tout modifier'."\n","\n";}echo'

    -';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$n=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$n):""):where($_GET,$n));$Kg=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($n -as$F=>$m){if(!isset($m["privileges"][$Kg?"update":"insert"])||$b->fieldName($m)==""||$m["generated"])unset($n[$F]);}if($_POST&&!$l&&!isset($_GET["select"])){$B=$_POST["referer"];if($_POST["insert"])$B=($Kg?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$B))$B=ME."select=".urlencode($a);$x=indexes($a);$Fg=unique_array($_GET["where"],$x);$Ye="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($B,'L\'élément a été supprimé.',$k->delete($a,$Ye,!$Fg));else{$P=array();foreach($n -as$F=>$m){$X=process_input($m);if($X!==false&&$X!==null)$P[idf_escape($F)]=$X;}if($Kg){if(!$P)redirect($B);queries_redirect($B,'L\'élément a été modifié.',$k->update($a,$P,$Ye,!$Fg));if(is_ajax()){page_headers();page_messages($l);exit;}}else{$J=$k->insert($a,$P);$id=($J?last_id():0);queries_redirect($B,sprintf('L\'élément%s a été inséré.',($id?" $id":"")),$J);}}}$L=null;if($_POST["save"])$L=(array)$_POST["fields"];elseif($Z){$N=array();foreach($n -as$F=>$m){if(isset($m["privileges"]["select"])){$pa=convert_field($m);if($_POST["clone"]&&$m["auto_increment"])$pa="''";if($y=="sql"&&preg_match("~enum|set~",$m["type"]))$pa="1*".idf_escape($F);$N[]=($pa?"$pa AS ":"").idf_escape($F);}}$L=array();if(!support("table"))$N=array("*");if($N){$J=$k->select($a,$N,array($Z),$N,array(),(isset($_GET["select"])?2:1));if(!$J)$l=error();else{$L=$J->fetch_assoc();if(!$L)$L=false;}if(isset($_GET["select"])&&(!$L||$J->fetch_assoc()))$L=null;}}if(!support("table")&&!$n){if(!$Z){$J=$k->select($a,array("*"),$Z,array("*"));$L=($J?$J->fetch_assoc():false);if(!$L)$L=array($k->primary=>"");}if($L){foreach($L -as$z=>$X){if(!$Z)$L[$z]=null;$n[$z]=array("field"=>$z,"null"=>($z!=$k->primary),"auto_increment"=>($z==$k->primary));}}}edit_form($a,$n,$L,$Kg);}elseif(isset($_GET["create"])){$a=$_GET["create"];$we=array();foreach(array('HASH','LINEAR HASH','KEY','LINEAR KEY','RANGE','LIST')as$z)$we[$z]=$z;$ef=referencable_primary($a);$q=array();foreach($ef -as$Wf=>$m)$q[str_replace("`","``",$Wf)."`".str_replace("`","``",$m["field"])]=$Wf;$le=array();$S=array();if($a!=""){$le=fields($a);$S=table_status($a);if(!$S)$l='Aucune table.';}$L=$_POST;$L["fields"]=(array)$L["fields"];if($L["auto_increment_col"])$L["fields"][$L["auto_increment_col"]]["auto_increment"]=true;if($_POST)set_adminer_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($L["fields"])&&!$l){if($_POST["drop"])queries_redirect(substr(ME,0,-1),'La table a été effacée.',drop_tables(array($a)));else{$n=array();$na=array();$Og=false;$oc=array();$ke=reset($le);$ma=" FIRST";foreach($L["fields"]as$z=>$m){$p=$q[$m["type"]];$Bg=($p!==null?$ef[$p]:$m);if($m["field"]!=""){if(!$m["has_default"])$m["default"]=null;if($z==$L["auto_increment_col"])$m["auto_increment"]=true;$Ue=process_field($m,$Bg);$na[]=array($m["orig"],$Ue,$ma);if(!$ke||$Ue!=process_field($ke,$ke)){$n[]=array($m["orig"],$Ue,$ma);if($m["orig"]!=""||$ma)$Og=true;}if($p!==null)$oc[idf_escape($m["field"])]=($a!=""&&$y!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$q[$m["type"]],'source'=>array($m["field"]),'target'=>array($Bg["field"]),'on_delete'=>$m["on_delete"],));$ma=" AFTER ".idf_escape($m["field"]);}elseif($m["orig"]!=""){$Og=true;$n[]=array($m["orig"]);}if($m["orig"]!=""){$ke=next($le);if(!$ke)$ma="";}}$ye="";if($we[$L["partition_by"]]){$ze=array();if($L["partition_by"]=='RANGE'||$L["partition_by"]=='LIST'){foreach(array_filter($L["partition_names"])as$z=>$X){$Y=$L["partition_values"][$z];$ze[]="\n PARTITION ".idf_escape($X)." VALUES ".($L["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$ye.="\nPARTITION BY $L[partition_by]($L[partition])".($ze?" (".implode(",",$ze)."\n)":($L["partitions"]?" PARTITIONS ".(+$L["partitions"]):""));}elseif(support("partitioning")&&preg_match("~partitioned~",$S["Create_options"]))$ye.="\nREMOVE PARTITIONING";$D='La table a été modifiée.';if($a==""){cookie("adminer_engine",$L["Engine"]);$D='La table a été créée.';}$F=trim($L["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($F),$D,alter_table($a,$F,($y=="sqlite"&&($Og||$oc)?$na:$n),$oc,($L["Comment"]!=$S["Comment"]?$L["Comment"]:null),($L["Engine"]&&$L["Engine"]!=$S["Engine"]?$L["Engine"]:""),($L["Collation"]&&$L["Collation"]!=$S["Collation"]?$L["Collation"]:""),($L["Auto_increment"]!=""?number($L["Auto_increment"]):""),$ye));}}page_header(($a!=""?'Modifier la table':'Créer une table'),$l,array("table"=>$a),h($a));if(!$_POST){$L=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($Cg["int"])?"int":(isset($Cg["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$L=$S;$L["name"]=$a;$L["fields"]=array();if(!$_GET["auto_increment"])$L["Auto_increment"]="";foreach($le -as$m){$m["has_default"]=isset($m["default"]);$L["fields"][]=$m;}if(support("partitioning")){$tc="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($a);$J=$f->query("SELECT PARTITION_METHOD, PARTITION_ORDINAL_POSITION, PARTITION_EXPRESSION $tc ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");list($L["partition_by"],$L["partitions"],$L["partition"])=$J->fetch_row();$ze=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $tc AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$ze[""]="";$L["partition_names"]=array_keys($ze);$L["partition_values"]=array_values($ze);}}}$Pa=collations();$Pb=engines();foreach($Pb -as$Ob){if(!strcasecmp($Ob,$L["Engine"])){$L["Engine"]=$Ob;break;}}echo' +';$Kc="";if(!isset($_GET["import"])){$hh=$_GET["sql"];if($_POST)$hh=$_POST["query"];elseif($_GET["history"]=="all")$hh=$Kd;elseif($_GET["history"]!="")$hh=idx($Kd[$_GET["history"]],0);echo"

    ";textarea("query",$hh,20);echo +script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    ";adminer()->sqlPrintAfter();echo"$Kc\n",lang(165).": \n";}else{$Ad=(extension_loaded("zlib")?"[.gz]":"");echo"

    ".lang(166)."
    ",file_input("SQL$Ad: \n$Kc"),"
    \n";$Wd=adminer()->importServerPath();if($Wd)echo"
    ".lang(167)."
    ",lang(168,"".h($Wd)."$Ad"),' ',"
    \n";echo"

    ";}echo +checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),lang(170))."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),lang(171))."\n",input_token();if(!isset($_GET["import"])&&$Kd){print_fieldset("history",lang(172),$_GET["history"]!="");for($X=end($Kd);$X;$X=prev($Kd)){$y=key($Kd);list($hh,$Ti,$sc)=$X;echo''.lang(12).""." ".@date("H:i:s",$Ti).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace("~^(#|$Ue).*~m",'',$hh)))),80,"").($sc?" ($sc)":"")."
    \n";}echo"\n","".lang(174)."\n","\n";}echo' +';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$o=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$o):""):where($_GET,$o));$_j=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($o +as$B=>$n){if((!$_j&&!isset($n["privileges"]["insert"]))||adminer()->fieldName($n)=="")unset($o[$B]);}if($_POST&&!$m&&!isset($_GET["select"])){$We=$_POST["referer"];if($_POST["insert"])$We=($_j?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$We))$We=ME."select=".urlencode($a);$x=indexes($a);$vj=unique_array($_GET["where"],$x);$kh="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($We,lang(175),driver()->delete($a,$kh,$vj?0:1));else{$O=array();foreach($o +as$B=>$n){$X=process_input($n);if($X!==false&&$X!==null)$O[idf_escape($B)]=$X;}if($_j){if(!$O)redirect($We);queries_redirect($We,lang(176),driver()->update($a,$O,$kh,$vj?0:1));if(is_ajax()){page_headers();page_messages($m);exit;}}else{$I=driver()->insert($a,$O);$Me=($I?last_id($I):0);queries_redirect($We,lang(177,($Me?" $Me":"")),$I);}}}$K=null;if($Z){$M=array();foreach($o +as$B=>$n){if(isset($n["privileges"]["select"])){$ya=($_POST["clone"]&&$n["auto_increment"]?"''":convert_field($n));$M[]=($ya?"$ya AS ":"").idf_escape($B);}}$K=array();if(!support("table"))$M=array("*");if($M){$I=driver()->select($a,$M,array($Z),$M,array(),(isset($_GET["select"])?2:1));if(!$I)$m=error();else{$K=$I->fetch_assoc();if(!$K)$K=false;}if(isset($_GET["select"])&&(!$K||$I->fetch_assoc()))$K=null;}}if(!support("table")&&!$o){if(!$Z){$I=driver()->select($a,array("*"),array(),array("*"));$K=($I?$I->fetch_assoc():false);if(!$K)$K=array(driver()->primary=>"");}if($K){foreach($K +as$y=>$X){if(!$Z)$K[$y]=null;$o[$y]=array("field"=>$y,"null"=>($y!=driver()->primary),"auto_increment"=>($y==driver()->primary));}}}if($_POST["save"])$K=(array)$_POST["fields"]+($K?$K:array());edit_form($a,$o,$K,$_j,$m);}elseif(isset($_GET["create"])){$a=$_GET["create"];$Fg=driver()->partitionBy;$Ig=($Fg?driver()->partitionsInfo($a):array());$qh=referencable_primary($a);$md=array();foreach($qh +as$Di=>$n)$md[str_replace("`","``",$Di)."`".str_replace("`","``",$n["field"])]=$Di;$pg=array();$S=array();if($a!=""){$pg=fields($a);$S=table_status1($a);if(count($S)<2)$m=lang(11);}$K=$_POST;$K["fields"]=(array)$K["fields"];if($K["auto_increment_col"])$K["fields"][$K["auto_increment_col"]]["auto_increment"]=true;if($_POST)save_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($K["fields"])&&!$m){if($_POST["drop"])queries_redirect(substr(ME,0,-1),lang(178),drop_tables(array($a)));else{$o=array();$ua=array();$Fj=false;$kd=array();$og=reset($pg);$sa=" FIRST";foreach($K["fields"]as$y=>$n){$q=$md[$n["type"]];$qj=($q!==null?$qh[$q]:$n);if($n["field"]!=""){if(!$n["generated"])$n["default"]=null;$gh=process_field($n,$qj);$ua[]=array($n["orig"],$gh,$sa);if(!$og||$gh!==process_field($og,$og)){$o[]=array($n["orig"],$gh,$sa);if($n["orig"]!=""||$sa)$Fj=true;}if($q!==null)$kd[idf_escape($n["field"])]=($a!=""&&JUSH!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$md[$n["type"]],'source'=>array($n["field"]),'target'=>array($qj["field"]),'on_delete'=>$n["on_delete"],));$sa=" AFTER ".idf_escape($n["field"]);}elseif($n["orig"]!=""){$Fj=true;$o[]=array($n["orig"]);}if($n["orig"]!=""){$og=next($pg);if(!$og)$sa="";}}$E=array();if(in_array($K["partition_by"],$Fg)){foreach($K +as$y=>$X){if(preg_match('~^partition~',$y))$E[$y]=$X;}foreach($E["partition_names"]as$y=>$B){if($B==""){unset($E["partition_names"][$y]);unset($E["partition_values"][$y]);}}$E["partition_names"]=array_values($E["partition_names"]);$E["partition_values"]=array_values($E["partition_values"]);if($E==$Ig)$E=array();}elseif(preg_match("~partitioned~",$S["Create_options"]))$E=null;$qf=lang(179);if($a==""){cookie("adminer_engine",$K["Engine"]);$qf=lang(180);}$B=trim($K["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($B),$qf,alter_table($a,$B,(JUSH=="sqlite"&&($Fj||$kd)?$ua:$o),$kd,($K["Comment"]!=$S["Comment"]?$K["Comment"]:null),($K["Engine"]&&$K["Engine"]!=$S["Engine"]?$K["Engine"]:""),($K["Collation"]&&$K["Collation"]!=$S["Collation"]?$K["Collation"]:""),($K["Auto_increment"]!=""?number($K["Auto_increment"]):""),$E));}}page_header(($a!=""?lang(45):lang(78)),$m,array("table"=>$a),h($a));if(!$_POST){$rj=driver()->types();$K=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($rj["int"])?"int":(isset($rj["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$K=$S;$K["name"]=$a;$K["fields"]=array();if(!$_GET["auto_increment"])$K["Auto_increment"]="";foreach($pg +as$n){$n["generated"]=$n["generated"]?:(isset($n["default"])?"DEFAULT":"");$K["fields"][]=$n;}if($Fg){$K+=$Ig;$K["partition_names"][]="";$K["partition_values"][]="";}}}$lb=collations();if(is_array(reset($lb)))$lb=call_user_func_array('array_merge',array_values($lb));$zc=driver()->engines();foreach($zc +as$yc){if(!strcasecmp($yc,$K["Engine"])){$K["Engine"]=$yc;break;}}echo'

    -';if(support("columns")||$a==""){echo'Nom de la table: -';if($a==""&&!$_POST)echo -script("focus(qs('#form')['name']);");echo($Pb?"".on_help("getTarget(event).value",1).script("qsl('select').onchange = helpClose;"):""),' ',($Pa&&!preg_match("~sqlite|mssql~",$y)?html_select("Collation",array(""=>"(".'interclassement'.")")+$Pa,$L["Collation"]):""),' -';}echo' -';if(support("columns")){echo'

    - -';edit_fields($L["fields"],$Pa,"TABLE",$q);echo'
    -',script("editFields();"),'
    -

    -Incrément automatique: -',checkbox("defaults",1,($_POST?$_POST["defaults"]:adminer_setting("defaults")),'Valeurs par défaut',"columnShow(this.checked, 5)","jsonly"),(support("comment")?checkbox("comments",1,($_POST?$_POST["comments"]:adminer_setting("comments")),'Commentaire',"editingCommentsClick(this, true);","jsonly").' ':''),'

    - +';if(support("columns")||$a==""){echo +lang(181).": \n",($zc?html_select("Engine",array(""=>"(".lang(182).")")+$zc,$K["Engine"]).on_help("event.target.value",1).script("qsl('select').onchange = helpClose;")."\n":"");if($lb)echo"".optionlist($lb)."\n",(preg_match("~sqlite|mssql~",JUSH)?"":"\n");echo"\n";}if(support("columns")){echo"

    \n","\n";edit_fields($K["fields"],$lb,"TABLE",$md);echo"
    \n",script("editFields();"),"
    \n

    \n",lang(52).": \n",checkbox("defaults",1,($_POST?$_POST["defaults"]:get_setting("defaults")),lang(183),"columnShow(this.checked, 5)","jsonly");$sb=($_POST?$_POST["comments"]:get_setting("comments"));echo(support("comment")?checkbox("comments",1,$sb,lang(51),"editingCommentsClick(this, true);","jsonly").' '.(preg_match('~\n~',$K["Comment"])?"":''):''),'

    + ';}echo' -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}if(support("partitioning")){$xe=preg_match('~RANGE|LIST~',$L["partition_by"]);print_fieldset("partition",'Partitionner par',$L["partition_by"]);echo'

    -',"".on_help("getTarget(event).value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),'() -Partitions: - - -';foreach($L["partition_names"]as$z=>$X){echo'',' - -';}echo' -

    -';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$Oc=array("PRIMARY","UNIQUE","INDEX");$S=table_status($a,true);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="SPATIAL";$x=indexes($a);$Oe=array();if($y=="mongo"){$Oe=$x["_id_"];unset($Oc[0]);unset($x["_id_"]);}$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["drop_col"]){$oa=array();foreach($L["indexes"]as$w){$F=$w["name"];if(in_array($w["type"],$Oc)){$e=array();$od=array();$tb=array();$P=array();ksort($w["columns"]);foreach($w["columns"]as$z=>$d){if($d!=""){$nd=$w["lengths"][$z];$sb=$w["descs"][$z];$P[]=idf_escape($d).($nd?"(".(+$nd).")":"").($sb?" DESC":"");$e[]=$d;$od[]=($nd?$nd:null);$tb[]=$sb;}}if($e){$Yb=$x[$F];if($Yb){ksort($Yb["columns"]);ksort($Yb["lengths"]);ksort($Yb["descs"]);if($w["type"]==$Yb["type"]&&array_values($Yb["columns"])===$e&&(!$Yb["lengths"]||array_values($Yb["lengths"])===$od)&&array_values($Yb["descs"])===$tb){unset($x[$F]);continue;}}$oa[]=array($w["type"],$F,$P);}}}foreach($x -as$F=>$Yb)$oa[]=array($Yb["type"],$F,"DROP");if(!$oa)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),'Index modifiés.',alter_indexes($a,$oa));}page_header('Index',$l,array("table"=>$a),h($a));$n=array_keys(fields($a));if($_POST["add"]){foreach($L["indexes"]as$z=>$w){if($w["columns"][count($w["columns"])]!="")$L["indexes"][$z]["columns"][]="";}$w=end($L["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$L["indexes"][]=array("columns"=>array(1=>""));}if(!$L){foreach($x -as$z=>$w){$x[$z]["name"]=$z;$x[$z]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$L["indexes"]=$x;}echo' +';if($a!="")echo'',confirm(lang(184,$a));if($Fg&&(JUSH=='sql'||$a=="")){$Gg=preg_match('~RANGE|LIST~',$K["partition_by"]);print_fieldset("partition",lang(185),$K["partition_by"]);echo"

    ".html_select("partition_by",array_merge(array(""),$Fg),$K["partition_by"]).on_help("event.target.value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),"()\n",lang(186).": \n","\n","\n";foreach($K["partition_names"]as$y=>$X)echo'','\n\n";}echo +input_token(),' +';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$ee=array("PRIMARY","UNIQUE","INDEX");$S=table_status1($a,true);$be=driver()->indexAlgorithms($S);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="SPATIAL";$x=indexes($a);$o=fields($a);$G=array();if(JUSH=="mongo"){$G=$x["_id_"];unset($ee[0]);unset($x["_id_"]);}$K=$_POST;if($K)save_settings(array("index_options"=>$K["options"]));if($_POST&&!$m&&!$_POST["add"]&&!$_POST["drop_col"]){$b=array();foreach($K["indexes"]as$w){$B=$w["name"];if(in_array($w["type"],$ee)){$e=array();$Se=array();$cc=array();$ce=(support("partial_indexes")?$w["partial"]:"");$ae=(in_array($w["algorithm"],$be)?$w["algorithm"]:"");$O=array();ksort($w["columns"]);foreach($w["columns"]as$y=>$d){if($d!=""){$Re=idx($w["lengths"],$y);$ac=idx($w["descs"],$y);$O[]=($o[$d]?idf_escape($d):$d).($Re?"(".(+$Re).")":"").($ac?" DESC":"");$e[]=$d;$Se[]=($Re?:null);$cc[]=$ac;}}$Lc=$x[$B];if($Lc){ksort($Lc["columns"]);ksort($Lc["lengths"]);ksort($Lc["descs"]);if($w["type"]==$Lc["type"]&&array_values($Lc["columns"])===$e&&(!$Lc["lengths"]||array_values($Lc["lengths"])===$Se)&&array_values($Lc["descs"])===$cc&&$Lc["partial"]==$ce&&(!$be||$Lc["algorithm"]==$ae)){unset($x[$B]);continue;}}if($e)$b[]=array($w["type"],$B,$O,$ae,$ce);}}foreach($x +as$B=>$Lc)$b[]=array($Lc["type"],$B,"DROP");if(!$b)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),lang(189),alter_indexes($a,$b));}page_header(lang(141),$m,array("table"=>$a),h($a));$Zc=array_keys($o);if($_POST["add"]){foreach($K["indexes"]as$y=>$w){if($w["columns"][count($w["columns"])]!="")$K["indexes"][$y]["columns"][]="";}$w=end($K["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$K["indexes"][]=array("columns"=>array(1=>""));}if(!$K){foreach($x +as$y=>$w){$x[$y]["name"]=$y;$x[$y]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$K["indexes"]=$x;}$Se=(JUSH=="sql"||JUSH=="mssql");$ei=($_POST?$_POST["options"]:get_setting("index_options"));echo'

    - +
    - -';if($Oe){echo"
    Type d\'index -Colonne (longueur) -Nom - +',lang(190);$Ud=" class='idxopts".($ei?"":" hidden")."'";if($be)echo"".lang(191).doc_link(array('sql'=>'create-index.html#create-index-storage-engine-index-types','mariadb'=>'storage-engine-index-types/','pgsql'=>'indexes-types.html',));echo'',lang(192).($Se?" (".lang(193).")":"");if($Se||support("descidx"))echo +checkbox("options",1,$ei,lang(113),"indexOptionsShow(this.checked)","jsonly")."\n";echo'',lang(194);if(support("partial_indexes"))echo"".lang(195);echo'
    PRIMARY";foreach($Oe["columns"]as$z=>$d){echo -select_input(" disabled",$n,$d)," ";}echo"\n";}$Zc=1;foreach($L["indexes"]as$w){if(!$_POST["drop_col"]||$Zc!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$Zc][type]",array(-1=>"")+$Oc,$w["type"],($Zc==count($L["indexes"])?"indexesAddRow.call(this);":1),"label-type"),"";ksort($w["columns"]);$u=1;foreach($w["columns"]as$z=>$d){echo"".select_input(" name='indexes[$Zc][columns][$u]' title='".'Colonne'."'",($n?array_combine($n,$n):$n),$d,"partial(".($u==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape($y=="sql"?"":$_GET["indexes"]."_")."')"),($y=="sql"||$y=="mssql"?"":""),(support("descidx")?checkbox("indexes[$Zc][descs][$u]",1,$w["descs"][$z],'décroissant'):"")," ";$u++;}echo"\n","".script("qsl('input').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$Zc++;}echo'
    +';if($G){echo"
    PRIMARY";foreach($G["columns"]as$y=>$d)echo +select_input(" disabled",$Zc,$d)," ";echo"\n";}$_e=1;foreach($K["indexes"]as$w){if(!$_POST["drop_col"]||$_e!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$_e][type]",array(-1=>"")+$ee,$w["type"],($_e==count($K["indexes"])?"indexesAddRow.call(this);":""),"label-type");if($be)echo"".html_select("indexes[$_e][algorithm]",array_merge(array(""),$be),$w['algorithm'],"label-algorithm");echo"";ksort($w["columns"]);$t=1;foreach($w["columns"]as$y=>$d){echo"".select_input(" name='indexes[$_e][columns][$t]' title='".lang(49)."'",($o&&($d==""||$o[$d])?array_combine($Zc,$Zc):array()),$d,"partial(".($t==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape(JUSH=="sql"?"":$_GET["indexes"]."_")."')"),"",($Se?"":""),(support("descidx")?checkbox("indexes[$_e][descs][$t]",1,idx($w["descs"],$y),lang(60)):"")," ";$t++;}echo"\n";if(support("partial_indexes"))echo"\n";echo"".icon("cross","drop_col[$_e]","x",lang(117)).script("qsl('button').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$_e++;}echo'

    - - - -';}elseif(isset($_GET["database"])){$L=$_POST;if($_POST&&!$l&&!isset($_POST["add_x"])){$F=trim($L["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),'La base de données a été supprimée.',drop_databases(array(DB)));}elseif(DB!==$F){if(DB!=""){$_GET["db"]=$F;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($F),'La base de données a été renommée.',rename_database($F,$L["collation"]));}else{$i=explode("\n",str_replace("\r","",$F));$Qf=true;$hd="";foreach($i -as$j){if(count($i)==1||$j!=""){if(!create_database($j,$L["collation"]))$Qf=false;$hd=$j;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($hd),'La base de données a été créée.',$Qf);}}else{if(!$L["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($F).(preg_match('~^[a-z0-9_]+$~i',$L["collation"])?" COLLATE $L[collation]":""),substr(ME,0,-1),'La base de données a été modifiée.');}}page_header(DB!=""?'Modifier la base de données':'Créer une base de données',$l,array(),h(DB));$Pa=collations();$F=DB;if($_POST)$F=$L["name"];elseif(DB!="")$L["collation"]=db_collation(DB,$Pa);elseif($y=="sql"){foreach(get_vals("SHOW GRANTS")as$vc){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vc,$C)&&$C[1]){$F=stripcslashes(idf_unescape("`$C[2]`"));break;}}}echo' + +',input_token(),' +';}elseif(isset($_GET["database"])){$K=$_POST;if($_POST&&!$m&&!$_POST["add"]){$B=trim($K["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),lang(196),drop_databases(array(DB)));}elseif(DB!==$B){if(DB!=""){$_GET["db"]=$B;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($B),lang(197),rename_database($B,$K["collation"]));}else{$j=explode("\n",str_replace("\r","",$B));$xi=true;$Le="";foreach($j +as$k){if(count($j)==1||$k!=""){if(!create_database($k,$K["collation"]))$xi=false;$Le=$k;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($Le),lang(198),$xi);}}else{if(!$K["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($B).(preg_match('~^[a-z0-9_]+$~i',$K["collation"])?" COLLATE $K[collation]":""),substr(ME,0,-1),lang(199));}}page_header(DB!=""?lang(68):lang(121),$m,array(),h(DB));$lb=collations();$B=DB;if($_POST)$B=$K["name"];elseif(DB!="")$K["collation"]=db_collation(DB,$lb);elseif(JUSH=="sql"){foreach(get_vals("SHOW GRANTS")as$vd){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vd,$A)&&$A[1]){$B=stripcslashes(idf_unescape("`$A[2]`"));break;}}}echo'

    -',($_POST["add_x"]||strpos($F,"\n")?'
    ':'')."\n".($Pa?html_select("collation",array(""=>"(".'interclassement'.")")+$Pa,$L["collation"]).'':""),script("focus(qs('#name'));"),' -';if(DB!="")echo"".confirm(sprintf('Drop %s?',DB))."\n";elseif(!$_POST["add_x"]&&$_GET["db"]=="")echo"\n";echo' -

    -';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$F=$_GET["name"];$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){$D=($_POST["drop"]?'La clé étrangère a été effacée.':($F!=""?'La clé étrangère a été modifiée.':'La clé étrangère a été créée.'));$B=ME."table=".urlencode($a);if(!$_POST["drop"]){$L["source"]=array_filter($L["source"],'strlen');ksort($L["source"]);$dg=array();foreach($L["source"]as$z=>$X)$dg[$z]=$L["target"][$z];$L["target"]=$dg;}if($y=="sqlite")queries_redirect($B,$D,recreate_table($a,$a,array(),array(),array(" $F"=>($_POST["drop"]?"":" ".format_foreign_key($L)))));else{$oa="ALTER TABLE ".table($a);$_b="\nDROP ".($y=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($F);if($_POST["drop"])query_redirect($oa.$_b,$B,$D);else{query_redirect($oa.($F!=""?"$_b,":"")."\nADD".format_foreign_key($L),$B,$D);$l='Les colonnes de source et de destination doivent être du même type, il doit y avoir un index sur les colonnes de destination et les données référencées doivent exister.'."
    $l";}}}page_header('Clé étrangère',$l,array("table"=>$a),h($a));if($_POST){ksort($L["source"]);if($_POST["add"])$L["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$L["target"]=array();}elseif($F!=""){$q=foreign_keys($a);$L=$q[$F];$L["source"][]="";}else{$L["table"]=$a;$L["source"]=array("");}echo' +',($_POST["add"]||strpos($B,"\n")?'
    ':'')."\n".($lb?html_select("collation",array(""=>"(".lang(107).")")+$lb,$K["collation"]).doc_link(array('sql'=>"charset-charsets.html",'mariadb'=>"supported-character-sets-and-collations/",'mssql'=>"relational-databases/system-functions/sys-fn-helpcollations-transact-sql",)):""),' +';if(DB!="")echo"".confirm(lang(184,DB))."\n";elseif(!$_POST["add"]&&$_GET["db"]=="")echo +icon("plus","add[0]","+",lang(114))."\n";echo +input_token(),' +';}elseif(isset($_GET["scheme"])){$K=$_POST;if($_POST&&!$m){$_=preg_replace('~ns=[^&]*&~','',ME)."ns=";if($_POST["drop"])query_redirect("DROP SCHEMA ".idf_escape($_GET["ns"]),$_,lang(200));else{$B=trim($K["name"]);$_ +.=urlencode($B);if($_GET["ns"]=="")query_redirect("CREATE SCHEMA ".idf_escape($B),$_,lang(201));elseif($_GET["ns"]!=$B)query_redirect("ALTER SCHEMA ".idf_escape($_GET["ns"])." RENAME TO ".idf_escape($B),$_,lang(202));else +redirect($_);}}page_header($_GET["ns"]!=""?lang(69):lang(70),$m);if(!$K)$K["name"]=$_GET["ns"];echo' +
    +

    + +';if($_GET["ns"]!="")echo"".confirm(lang(184,$_GET["ns"]))."\n";echo +input_token(),'

    +';}elseif(isset($_GET["call"])){$ca=($_GET["name"]?:$_GET["call"]);page_header(lang(203).": ".h($ca),$m);$Dh=routine($_GET["call"],(isset($_GET["callf"])?"FUNCTION":"PROCEDURE"));$Xd=array();$ug=array();foreach($Dh["fields"]as$t=>$n){if(substr($n["inout"],-3)=="OUT"&&JUSH=='sql')$ug[$t]="@".idf_escape($n["field"])." AS ".idf_escape($n["field"]);if(!$n["inout"]||substr($n["inout"],0,2)=="IN")$Xd[]=$t;}if(!$m&&$_POST){$Ua=array();foreach($Dh["fields"]as$y=>$n){$X="";if(in_array($y,$Xd)){$X=process_input($n);if($X===false)$X="''";if(isset($ug[$y]))connection()->query("SET @".idf_escape($n["field"])." = $X");}if(isset($ug[$y]))$Ua[]="@".idf_escape($n["field"]);elseif(in_array($y,$Xd))$Ua[]=$X;}$H=(isset($_GET["callf"])?"SELECT ":"CALL ").(idx($Dh["returns"],"type")=="record"?"* FROM ":"").table($ca)."(".implode(", ",$Ua).")";$si=microtime(true);$I=connection()->multi_query($H);$qa=connection()->affected_rows;echo +adminer()->selectQuery($H,$si,!$I);if(!$I)echo"

    ".error()."\n";else{$h=connect();if($h)$h->select_db(DB);do{$I=connection()->store_result();if(is_object($I))print_select_result($I,$h);else +echo"

    ".lang(204,$qa)." ".@date("H:i:s")."\n";}while(connection()->next_result());if($ug)print_select_result(connection()->query("SELECT ".implode(", ",$ug)));}}echo'

    -';$Ff=array_keys(fields($a));if($L["db"]!="")$f->select_db($L["db"]);if($L["ns"]!="")set_schema($L["ns"]);$df=array_keys(array_filter(table_status('',true),'fk_support'));$dg=array_keys(fields(in_array($L["table"],$df)?$L["table"]:reset($df)));$Xd="this.form['change-js'].value = '1'; this.form.submit();";echo"

    ".'Table visée'.": ".html_select("table",$df,$L["table"],$Xd)."\n";if($y=="pgsql")echo'Schéma'.": ".html_select("ns",$b->schemas(),$L["ns"]!=""?$L["ns"]:$_GET["ns"],$Xd);elseif($y!="sqlite"){$mb=array();foreach($b->databases()as$j){if(!information_schema($j))$mb[]=$j;}echo'DB'.": ".html_select("db",$mb,$L["db"]!=""?$L["db"]:$_GET["db"],$Xd);}echo' -

    - - -';$Zc=0;foreach($L["source"]as$z=>$X){echo"","
    SourceCible
    ".html_select("source[".(+$z)."]",array(-1=>"")+$Ff,$X,($Zc==count($L["source"])-1?"foreignAddRow.call(this);":1),"label-source"),"".html_select("target[".(+$z)."]",$dg,$L["target"][$z],1,"label-target");$Zc++;}echo'
    +';if($Xd){echo"\n";foreach($Xd +as$y){$n=$Dh["fields"][$y];$B=$n["field"];echo"
    ".adminer()->fieldName($n);$Y=idx($_POST["fields"],$B);if($Y!=""){if($n["type"]=="set")$Y=implode(",",$Y);}input($n,$Y,idx($_POST["function"],$B,""));echo"\n";}echo"
    \n";}echo'

    + +',input_token(),'

    + +
    +';function
    +pre_tr($Hh){return
    +preg_replace('~^~m','',preg_replace('~\|~','',preg_replace('~\|$~m',"",rtrim($Hh))));}$R='(\+--[-+]+\+\n)';$K='(\| .* \|\n)';echo
    +preg_replace_callback("~^$R?$K$R?($K*)$R?~m",function($A){$dd=pre_tr($A[2]);return"\n".($A[1]?"$dd\n":$dd).pre_tr($A[4])."\n
    ";},preg_replace('~(\n( -|mysql)> )(.+)~',"\\1\\3",preg_replace('~(.+)\n---+\n~',"\\1\n",h($Dh['comment']))));echo'
    +';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$B=$_GET["name"];$K=$_POST;if($_POST&&!$m&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){if(!$_POST["drop"]){$K["source"]=array_filter($K["source"],'strlen');ksort($K["source"]);$Mi=array();foreach($K["source"]as$y=>$X)$Mi[$y]=$K["target"][$y];$K["target"]=$Mi;}if(JUSH=="sqlite")$I=recreate_table($a,$a,array(),array(),array(" $B"=>($K["drop"]?"":" ".format_foreign_key($K))));else{$b="ALTER TABLE ".table($a);$I=($B==""||queries("$b DROP ".(JUSH=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($B)));if(!$K["drop"])$I=queries("$b ADD".format_foreign_key($K));}queries_redirect(ME."table=".urlencode($a),($K["drop"]?lang(205):($B!=""?lang(206):lang(207))),$I);if(!$K["drop"])$m=lang(208);}page_header(lang(209),$m,array("table"=>$a),h($a));if($_POST){ksort($K["source"]);if($_POST["add"])$K["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$K["target"]=array();}elseif($B!=""){$md=foreign_keys($a);$K=$md[$B];$K["source"][]="";}else{$K["table"]=$a;$K["source"]=array("");}echo' +
    +';$ji=array_keys(fields($a));if($K["db"]!="")connection()->select_db($K["db"]);if($K["ns"]!=""){$qg=get_schema();set_schema($K["ns"]);}$ph=array_keys(array_filter(table_status('',true),'Adminer\fk_support'));$Mi=array_keys(fields(in_array($K["table"],$ph)?$K["table"]:reset($ph)));$ag="this.form['change-js'].value = '1'; this.form.submit();";echo"

    \n";if(support("scheme")){$Kh=array_filter(adminer()->schemas(),function($Jh){return!preg_match('~^information_schema$~i',$Jh);});echo"";if($K["ns"]!="")set_schema($qg);}elseif(JUSH!="sqlite"){$Sb=array();foreach(adminer()->databases()as$k){if(!information_schema($k))$Sb[]=$k;}echo"";}echo +input_hidden("change-js"),'

    + + +';$_e=0;foreach($K["source"]as$y=>$X){echo"","
    ',lang(143),'',lang(144),'
    ".html_select("source[".(+$y)."]",array(-1=>"")+$ji,$X,($_e==count($K["source"])-1?"foreignAddRow.call(this);":""),"label-source"),"".html_select("target[".(+$y)."]",$Mi,idx($K["target"],$y),"","label-target");$_e++;}echo'

    -ON DELETE: ',html_select("on_delete",array(-1=>"")+explode("|",$Wd),$L["on_delete"]),' ON UPDATE: ',html_select("on_update",array(-1=>"")+explode("|",$Wd),$L["on_update"]),'','

    - -

    -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["view"])){$a=$_GET["view"];$L=$_POST;$me="VIEW";if($y=="pgsql"&&$a!=""){$Mf=table_status($a);$me=strtoupper($Mf["Engine"]);}if($_POST&&!$l){$F=trim($L["name"]);$pa=" AS\n$L[select]";$B=ME."table=".urlencode($F);$D='La vue a été modifiée.';$V=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$F&&$y!="sqlite"&&$V=="VIEW"&&$me=="VIEW")query_redirect(($y=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($F).$pa,$B,$D);else{$fg=$F."_adminer_".uniqid();drop_create("DROP $me ".table($a),"CREATE $V ".table($F).$pa,"DROP $V ".table($F),"CREATE $V ".table($fg).$pa,"DROP $V ".table($fg),($_POST["drop"]?substr(ME,0,-1):$B),'La vue a été effacée.',$D,'La vue a été créée.',$a,$F);}}if(!$_POST&&$a!=""){$L=view($a);$L["name"]=$a;$L["materialized"]=($me!="VIEW");if(!$l)$l=error();}page_header(($a!=""?'Modifier une vue':'Créer une vue'),$l,array("table"=>$a),h($a));echo' + + +',(DRIVER==='pgsql'?html_select("deferrable",array('NOT DEFERRABLE','DEFERRABLE','DEFERRABLE INITIALLY DEFERRED'),$K["deferrable"]).' ':''),doc_link(array('sql'=>"innodb-foreign-key-constraints.html",'mariadb'=>"foreign-keys/",'pgsql'=>"sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES",'mssql'=>"t-sql/statements/create-table-transact-sql",'oracle'=>"SQLRF01111",)),'

    + +

    +';if($B!="")echo'',confirm(lang(184,$B));echo +input_token(),' +';}elseif(isset($_GET["view"])){$a=$_GET["view"];$K=$_POST;$rg="VIEW";if(JUSH=="pgsql"&&$a!=""){$P=table_status1($a);$rg=strtoupper($P["Engine"]);}if($_POST&&!$m){$B=trim($K["name"]);$ya=" AS\n$K[select]";$We=ME."table=".urlencode($B);$qf=lang(213);$U=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$B&&JUSH!="sqlite"&&$U=="VIEW"&&$rg=="VIEW")query_redirect((JUSH=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($B).$ya,$We,$qf);else{$Oi=$B."_adminer_".uniqid();drop_create("DROP $rg ".table($a),"CREATE $U ".table($B).$ya,"DROP $U ".table($B),"CREATE $U ".table($Oi).$ya,"DROP $U ".table($Oi),($_POST["drop"]?substr(ME,0,-1):$We),lang(214),$qf,lang(215),$a,$B);}}if(!$_POST&&$a!=""){$K=view($a);$K["name"]=$a;$K["materialized"]=($rg!="VIEW");if(!$m)$m=error();}page_header(($a!=""?lang(44):lang(216)),$m,array("table"=>$a),h($a));echo'

    -

    Nom: -',(support("materializedview")?" ".checkbox("materialized",1,$L["materialized"],'Vue matérialisée'):""),'

    ';textarea("select",$L["select"]);echo'

    - -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}echo' -

    -';}elseif(isset($_GET["trigger"])){$a=$_GET["trigger"];$F=$_GET["name"];$_g=trigger_options();$L=(array)trigger($F,$a)+array("Trigger"=>$a."_bi");if($_POST){if(!$l&&in_array($_POST["Timing"],$_g["Timing"])&&in_array($_POST["Event"],$_g["Event"])&&in_array($_POST["Type"],$_g["Type"])){$Vd=" ON ".table($a);$_b="DROP TRIGGER ".idf_escape($F).($y=="pgsql"?$Vd:"");$B=ME."table=".urlencode($a);if($_POST["drop"])query_redirect($_b,$B,'Le déclencheur a été supprimé.');else{if($F!="")queries($_b);queries_redirect($B,($F!=""?'Le déclencheur a été modifié.':'Le déclencheur a été créé.'),queries(create_trigger($Vd,$_POST)));if($F!="")queries(create_trigger($Vd,$L+array("Type"=>reset($_g["Type"]))));}}$L=$_POST;}page_header(($F!=""?'Modifier un déclencheur'.": ".h($F):'Ajouter un déclencheur'),$l,array("table"=>$a));echo' +

    ',lang(194),': +',(support("materializedview")?" ".checkbox("materialized",1,$K["materialized"],lang(137)):""),'

    ';textarea("select",$K["select"]);echo'

    + +';if($a!="")echo'',confirm(lang(184,$a));echo +input_token(),' +';}elseif(isset($_GET["event"])){$aa=$_GET["event"];$re=array("YEAR","QUARTER","MONTH","DAY","HOUR","MINUTE","WEEK","SECOND","YEAR_MONTH","DAY_HOUR","DAY_MINUTE","DAY_SECOND","HOUR_MINUTE","HOUR_SECOND","MINUTE_SECOND");$ti=array("ENABLED"=>"ENABLE","DISABLED"=>"DISABLE","SLAVESIDE_DISABLED"=>"DISABLE ON SLAVE");$K=$_POST;if($_POST&&!$m){if($_POST["drop"])query_redirect("DROP EVENT ".idf_escape($aa),substr(ME,0,-1),lang(217));elseif(in_array($K["INTERVAL_FIELD"],$re)&&isset($ti[$K["STATUS"]])){$Ih="\nON SCHEDULE ".($K["INTERVAL_VALUE"]?"EVERY ".q($K["INTERVAL_VALUE"])." $K[INTERVAL_FIELD]".($K["STARTS"]?" STARTS ".q($K["STARTS"]):"").($K["ENDS"]?" ENDS ".q($K["ENDS"]):""):"AT ".q($K["STARTS"]))." ON COMPLETION".($K["ON_COMPLETION"]?"":" NOT")." PRESERVE";queries_redirect(substr(ME,0,-1),($aa!=""?lang(218):lang(219)),queries(($aa!=""?"ALTER EVENT ".idf_escape($aa).$Ih.($aa!=$K["EVENT_NAME"]?"\nRENAME TO ".idf_escape($K["EVENT_NAME"]):""):"CREATE EVENT ".idf_escape($K["EVENT_NAME"]).$Ih)."\n".$ti[$K["STATUS"]]." COMMENT ".q($K["EVENT_COMMENT"]).rtrim(" DO\n$K[EVENT_DEFINITION]",";").";"));}}page_header(($aa!=""?lang(220).": ".h($aa):lang(221)),$m);if(!$K&&$aa!=""){$L=get_rows("SELECT * FROM information_schema.EVENTS WHERE EVENT_SCHEMA = ".q(DB)." AND EVENT_NAME = ".q($aa));$K=reset($L);}echo' +

    + +
    ',lang(194),' +
    ',lang(222),' +
    ',lang(223),' +
    ',lang(224),' ',html_select("INTERVAL_FIELD",$re,$K["INTERVAL_FIELD"]),'
    ',lang(124),'',html_select("STATUS",$ti,$K["STATUS"]),'
    ',lang(51),' +
    ',checkbox("ON_COMPLETION","PRESERVE",$K["ON_COMPLETION"]=="PRESERVE",lang(225)),'
    +

    ';textarea("EVENT_DEFINITION",$K["EVENT_DEFINITION"]);echo'

    + +';if($aa!="")echo'',confirm(lang(184,$aa));echo +input_token(),'

    +';}elseif(isset($_GET["procedure"])){$ca=($_GET["name"]?:$_GET["procedure"]);$Dh=(isset($_GET["function"])?"FUNCTION":"PROCEDURE");$K=$_POST;$K["fields"]=(array)$K["fields"];if($_POST&&!process_fields($K["fields"])&&!$m){$ng=routine($_GET["procedure"],$Dh);$Oi="$K[name]_adminer_".uniqid();foreach($K["fields"]as$y=>$n){if($n["field"]=="")unset($K["fields"][$y]);}drop_create("DROP $Dh ".routine_id($ca,$ng),create_routine($Dh,$K),"DROP $Dh ".routine_id($K["name"],$K),create_routine($Dh,array("name"=>$Oi)+$K),"DROP $Dh ".routine_id($Oi,$K),substr(ME,0,-1),lang(226),lang(227),lang(228),$ca,$K["name"]);}page_header(($ca!=""?(isset($_GET["function"])?lang(229):lang(230)).": ".h($ca):(isset($_GET["function"])?lang(231):lang(232))),$m);if(!$_POST){if($ca=="")$K["language"]="sql";else{$K=routine($_GET["procedure"],$Dh);$K["name"]=$ca;}}$lb=get_vals("SHOW CHARACTER SET");sort($lb);$Eh=routine_languages();echo($lb?"".optionlist($lb)."":""),'
    - -
    Temps',html_select("Timing",$_g["Timing"],$L["Timing"],"triggerChange(/^".preg_quote($a,"/")."_[ba][iud]$/, '".js_escape($a)."', this.form);"),'
    Évènement',html_select("Event",$_g["Event"],$L["Event"],"this.form['Timing'].onchange();"),(in_array("UPDATE OF",$_g["Event"])?" ":""),'
    Type',html_select("Type",$_g["Type"],$L["Type"]),'
    -

    Nom: -',script("qs('#form')['Timing'].onchange();"),'

    ';textarea("Statement",$L["Statement"]);echo'

    - -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["select"])){$a=$_GET["select"];$S=table_status1($a);$x=indexes($a);$n=fields($a);$q=column_foreign_keys($a);$Td=$S["Oid"];parse_str($_COOKIE["adminer_import"],$ja);$lf=array();$e=array();$ig=null;foreach($n -as$z=>$m){$F=$b->fieldName($m);if(isset($m["privileges"]["select"])&&$F!=""){$e[$z]=html_entity_decode(strip_tags($F),ENT_QUOTES);if(is_shortable($m))$ig=$b->selectLengthProcess();}$lf+=$m["privileges"];}list($N,$t)=$b->selectColumnsProcess($e,$x);$Wc=count($t)selectSearchProcess($n,$x);$fe=$b->selectOrderProcess($n,$x);$_=$b->selectLimitProcess();if($_GET["val"]&&is_ajax()){header("Content-Type: text/plain; charset=utf-8");foreach($_GET["val"]as$Gg=>$L){$pa=convert_field($n[key($L)]);$N=array($pa?$pa:idf_escape(key($L)));$Z[]=where_check($Gg,$n);$K=$k->select($a,$N,$Z,$N);if($K)echo -reset($K->fetch_row());}exit;}$Oe=$Ig=null;foreach($x -as$w){if($w["type"]=="PRIMARY"){$Oe=array_flip($w["columns"]);$Ig=($N?$Oe:array());foreach($Ig -as$z=>$X){if(in_array(idf_escape($z),$N))unset($Ig[$z]);}break;}}if($Td&&!$Oe){$Oe=$Ig=array($Td=>0);$x[]=array("type"=>"PRIMARY","columns"=>array($Td));}if($_POST&&!$l){$fh=$Z;if(!$_POST["all"]&&is_array($_POST["check"])){$Ga=array();foreach($_POST["check"]as$Ea)$Ga[]=where_check($Ea,$n);$fh[]="((".implode(") OR (",$Ga)."))";}$fh=($fh?"\nWHERE ".implode(" AND ",$fh):"");if($_POST["export"]){cookie("adminer_import","output=".urlencode($_POST["output"])."&format=".urlencode($_POST["format"]));dump_headers($a);$b->dumpTable($a,"");$tc=($N?implode(", ",$N):"*").convert_fields($e,$n,$N)."\nFROM ".table($a);$xc=($t&&$Wc?"\nGROUP BY ".implode(", ",$t):"").($fe?"\nORDER BY ".implode(", ",$fe):"");if(!is_array($_POST["check"])||$Oe)$I="SELECT $tc$fh$xc";else{$Eg=array();foreach($_POST["check"]as$X)$Eg[]="(SELECT".limit($tc,"\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n).$xc,1).")";$I=implode(" UNION ALL ",$Eg);}$b->dumpData($a,"table",$I);exit;}if(!$b->selectEmailProcess($Z,$q)){if($_POST["save"]||$_POST["delete"]){$J=true;$ka=0;$P=array();if(!$_POST["delete"]){foreach($e -as$F=>$X){$X=process_input($n[$F]);if($X!==null&&($_POST["clone"]||$X!==false))$P[idf_escape($F)]=($X!==false?$X:idf_escape($F));}}if($_POST["delete"]||$P){if($_POST["clone"])$I="INTO ".table($a)." (".implode(", ",array_keys($P)).")\nSELECT ".implode(", ",$P)."\nFROM ".table($a);if($_POST["all"]||($Oe&&is_array($_POST["check"]))||$Wc){$J=($_POST["delete"]?$k->delete($a,$fh):($_POST["clone"]?queries("INSERT $I$fh"):$k->update($a,$P,$fh)));$ka=$f->affected_rows;}else{foreach((array)$_POST["check"]as$X){$eh="\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n);$J=($_POST["delete"]?$k->delete($a,$eh,1):($_POST["clone"]?queries("INSERT".limit1($a,$I,$eh)):$k->update($a,$P,$eh,1)));if(!$J)break;$ka+=$f->affected_rows;}}}$D=lang(array('%d élément a été modifié.','%d éléments ont été modifiés.'),$ka);if($_POST["clone"]&&$J&&$ka==1){$id=last_id();if($id)$D=sprintf('L\'élément%s a été inséré.'," $id");}queries_redirect(remove_from_uri($_POST["all"]&&$_POST["delete"]?"page":""),$D,$J);if(!$_POST["delete"]){edit_form($a,$n,(array)$_POST["fields"],!$_POST["clone"]);page_footer();exit;}}elseif(!$_POST["import"]){if(!$_POST["val"])$l='Ctrl+cliquez sur une valeur pour la modifier.';else{$J=true;$ka=0;foreach($_POST["val"]as$Gg=>$L){$P=array();foreach($L -as$z=>$X){$z=bracket_escape($z,1);$P[idf_escape($z)]=(preg_match('~char|text~',$n[$z]["type"])||$X!=""?$b->processInput($n[$z],$X):"NULL");}$J=$k->update($a,$P," WHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($Gg,$n),!$Wc&&!$Oe," ");if(!$J)break;$ka+=$f->affected_rows;}queries_redirect(remove_from_uri(),lang(array('%d élément a été modifié.','%d éléments ont été modifiés.'),$ka),$J);}}elseif(!is_string($jc=get_file("csv_file",true)))$l=upload_error($jc);elseif(!preg_match('~~u',$jc))$l='Les fichiers doivent être encodés en UTF-8.';else{cookie("adminer_import","output=".urlencode($ja["output"])."&format=".urlencode($_POST["separator"]));$J=true;$Qa=array_keys($n);preg_match_all('~(?>"[^"]*"|[^"\r\n]+)+~',$jc,$ud);$ka=count($ud[0]);$k->begin();$xf=($_POST["separator"]=="csv"?",":($_POST["separator"]=="tsv"?"\t":";"));$M=array();foreach($ud[0]as$z=>$X){preg_match_all("~((?>\"[^\"]*\")+|[^$xf]*)$xf~",$X.$xf,$vd);if(!$z&&!array_diff($vd[1],$Qa)){$Qa=$vd[1];$ka--;}else{$P=array();foreach($vd[1]as$u=>$Ma)$P[idf_escape($Qa[$u])]=($Ma==""&&$n[$Qa[$u]]["null"]?"NULL":q(str_replace('""','"',preg_replace('~^"|"$~','',$Ma))));$M[]=$P;}}$J=(!$M||$k->insertUpdate($a,$M,$Oe));if($J)$J=$k->commit();queries_redirect(remove_from_uri("page"),lang(array('%d ligne a été importée.','%d lignes ont été importées.'),$ka),$J);$k->rollback();}}}$Wf=$b->tableName($S);if(is_ajax()){page_headers();ob_start();}else -page_header('Sélectionner'.": $Wf",$l);$P=null;if(isset($lf["insert"])||!support("table")){$P="";foreach((array)$_GET["where"]as$X){if($q[$X["col"]]&&count($q[$X["col"]])==1&&($X["op"]=="="||(!$X["op"]&&!preg_match('~[_%]~',$X["val"]))))$P.="&set".urlencode("[".bracket_escape($X["col"])."]")."=".urlencode($X["val"]);}}$b->selectLinks($S,$P);if(!$e&&support("table"))echo"

    ".'Impossible de sélectionner la table'.($n?".":": ".error())."\n";else{echo"

    \n","
    ";hidden_fields_get();echo(DB!=""?''.(isset($_GET["ns"])?'':""):"");echo'',"
    \n";$b->selectColumnsPrint($N,$e);$b->selectSearchPrint($Z,$e,$x);$b->selectOrderPrint($fe,$e,$x);$b->selectLimitPrint($_);$b->selectLengthPrint($ig);$b->selectActionPrint($x);echo"
    \n";$G=$_GET["page"];if($G=="last"){$sc=$f->result(count_rows($a,$Z,$Wc,$t));$G=floor(max(0,$sc-1)/$_);}$sf=$N;$wc=$t;if(!$sf){$sf[]="*";$ab=convert_fields($e,$n,$N);if($ab)$sf[]=substr($ab,2);}foreach($N -as$z=>$X){$m=$n[idf_unescape($X)];if($m&&($pa=convert_field($m)))$sf[$z]="$pa AS $X";}if(!$Wc&&$Ig){foreach($Ig -as$z=>$X){$sf[]=idf_escape($z);if($wc)$wc[]=idf_escape($z);}}$J=$k->select($a,$sf,$Z,$wc,$fe,$_,$G,true);if(!$J)echo"

    ".error()."\n";else{if($y=="mssql"&&$G)$J->seek($_*$G);$Mb=array();echo"

    \n";$M=array();while($L=$J->fetch_assoc()){if($G&&$y=="oracle")unset($L["RNUM"]);$M[]=$L;}if($_GET["page"]!="last"&&$_!=""&&$t&&$Wc&&$y=="sql")$sc=$f->result(" SELECT FOUND_ROWS()");if(!$M)echo"

    ".'Aucun résultat.'."\n";else{$wa=$b->backwardKeys($a,$Wf);echo"

    ","",script("mixin(qs('#table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true), onkeydown: editingKeydown});"),"".(!$t&&$N?"":"\n";if(is_ajax()){if($_%2==1&&$G%2==1)odd();ob_end_clean();}foreach($b->rowDescriptions($M,$q)as$E=>$L){$Fg=unique_array($M[$E],$x);if(!$Fg){$Fg=array();foreach($M[$E]as$z=>$X){if(!preg_match('~^(COUNT\((\*|(DISTINCT )?`(?:[^`]|``)+`)\)|(AVG|GROUP_CONCAT|MAX|MIN|SUM)\(`(?:[^`]|``)+`\))$~',$z))$Fg[$z]=$X;}}$Gg="";foreach($Fg -as$z=>$X){if(($y=="sql"||$y=="pgsql")&&preg_match('~char|text|enum|set~',$n[$z]["type"])&&strlen($X)>64){$z=(strpos($z,'(')?$z:idf_escape($z));$z="MD5(".($y!='sql'||preg_match("~^utf8~",$n[$z]["collation"])?$z:"CONVERT($z USING ".charset($f).")").")";$X=md5($X);}$Gg.="&".($X!==null?urlencode("where[".bracket_escape($z)."]")."=".urlencode($X):"null%5B%5D=".urlencode($z));}echo"".(!$t&&$N?"":"";}}}if($wa)echo"\n";}if(is_ajax())exit;echo"
    ".script("qs('#all-page').onclick = partial(formCheck, /check/);","")." ".'Modification'."");$Kd=array();$uc=array();reset($N);$af=1;foreach($M[0]as$z=>$X){if(!isset($Ig[$z])){$X=$_GET["columns"][key($N)];$m=$n[$N?($X?$X["col"]:current($N)):$z];$F=($m?$b->fieldName($m,$af):($X["fun"]?"*":$z));if($F!=""){$af++;$Kd[$z]=$F;$d=idf_escape($z);$Ic=remove_from_uri('(order|desc)[^=]*|page').'&order%5B0%5D='.urlencode($z);$sb="&desc%5B0%5D=1";echo"".script("mixin(qsl('th'), {onmouseover: partial(columnMouse), onmouseout: partial(columnMouse, ' hidden')});",""),'';echo -apply_sql_function($X["fun"],$F)."";echo"";}$uc[$z]=$X["fun"];next($N);}}$od=array();if($_GET["modify"]){foreach($M -as$L){foreach($L -as$z=>$X)$od[$z]=max($od[$z],min(40,strlen(utf8_decode($X))));}}echo($wa?"".'Relations':"")."
    ".checkbox("check[]",substr($Gg,1),in_array(substr($Gg,1),(array)$_POST["check"])).($Wc||information_schema(DB)?"":" ".'modifier'.""));foreach($L -as$z=>$X){if(isset($Kd[$z])){$m=$n[$z];$X=$k->value($X,$m);if($X!=""&&(!isset($Mb[$z])||$Mb[$z]!=""))$Mb[$z]=(is_mail($X)?$Kd[$z]:"");$A="";if(preg_match('~blob|bytea|raw|file~',$m["type"])&&$X!="")$A=ME.'download='.urlencode($a).'&field='.urlencode($z).$Gg;if(!$A&&$X!==null){foreach((array)$q[$z]as$p){if(count($q[$z])==1||end($p["source"])==$z){$A="";foreach($p["source"]as$u=>$Ff)$A.=where_link($u,$p["target"][$u],$M[$E][$Ff]);$A=($p["db"]!=""?preg_replace('~([?&]db=)[^&]+~','\1'.urlencode($p["db"]),ME):ME).'select='.urlencode($p["table"]).$A;if($p["ns"])$A=preg_replace('~([?&]ns=)[^&]+~','\1'.urlencode($p["ns"]),$A);if(count($p["source"])==1)break;}}}if($z=="COUNT(*)"){$A=ME."select=".urlencode($a);$u=0;foreach((array)$_GET["where"]as$W){if(!array_key_exists($W["col"],$Fg))$A.=where_link($u++,$W["col"],$W["val"],$W["op"]);}foreach($Fg -as$ad=>$W)$A.=where_link($u++,$ad,$W);}$X=select_value($X,$A,$m,$ig);$v=h("val[$Gg][".bracket_escape($z)."]");$Y=$_POST["val"][$Gg][bracket_escape($z)];$Hb=!is_array($L[$z])&&is_utf8($X)&&$M[$E][$z]==$L[$z]&&!$uc[$z];$hg=preg_match('~text|lob~',$m["type"]);echo"".($hg?"":"");}else{$sd=strpos($X,"…");echo" data-text='".($sd?2:($hg?1:0))."'".($Hb?"":" data-warning='".h('Utilisez le lien "modifier" pour modifier cette valeur.')."'").">$X";$b->backwardKeysPrint($wa,$M[$E]);echo"
    \n","
    \n";}if(!is_ajax()){if($M||$G){$Wb=true;if($_GET["page"]!="last"){if($_==""||(count($M)<$_&&($M||!$G)))$sc=($G?$G*$_:0)+count($M);elseif($y!="sql"||!$Wc){$sc=($Wc?false:found_rows($S,$Z));if($sc$_||$G));if($se){echo(($sc===false?count($M)+1:$sc-$G*$_)>$_?'

    '.'Charger plus de données'.''.script("qsl('a').onclick = partial(selectLoadMore, ".(+$_).", '".'Chargement'."…');",""):''),"\n";}}echo"

    \n";}if(adminer()->selectImportPrint())echo"

    ","".lang(76)."",script("qsl('a').onclick = partial(toggle, 'import');",""),"";echo +input_token(),"\n",(!$xd&&$M?"":script("tableCheck();"));}}}if(is_ajax()){ob_end_clean();exit;}}elseif(isset($_GET["variables"])){$P=isset($_GET["status"]);page_header($P?lang(124):lang(123));$Oj=($P?adminer()->showStatus():adminer()->showVariables());if(!$Oj)echo"

    ".lang(14)."\n";else{echo"\n";foreach($Oj +as$K){echo"";$y=array_shift($K);echo"
    ".h($y)."";foreach($K +as$X)echo"".nl_br(h($X));}echo"
    \n";}}elseif(isset($_GET["script"])){header("Content-Type: text/javascript; charset=utf-8");if($_GET["script"]=="db"){$_i=array("Data_length"=>0,"Index_length"=>0,"Data_free"=>0);foreach(table_status()as$B=>$S){json_row("Comment-$B",h($S["Comment"]));if(!is_view($S)||preg_match('~materialized~i',$S["Engine"])){foreach(array("Engine","Collation")as$y)json_row("$y-$B",h($S[$y]));foreach($_i+array("Auto_increment"=>0,"Rows"=>0)as$y=>$X){if($S[$y]!=""){$X=format_number($S[$y]);if($X>=0)json_row("$y-$B",($y=="Rows"&&$X&&$S["Engine"]==(JUSH=="pgsql"?"table":"InnoDB")?"~ $X":$X));if(isset($_i[$y]))$_i[$y]+=($S["Engine"]!="InnoDB"||$y!="Data_free"?$S[$y]:0);}elseif(array_key_exists($y,$S))json_row("$y-$B","?");}}}foreach($_i +as$y=>$X)json_row("sum-$y",format_number($X));json_row("");}elseif($_GET["script"]=="kill")connection()->query("KILL ".number($_POST["kill"]));else{foreach(count_tables(adminer()->databases())as$k=>$X){json_row("tables-$k",$X);json_row("size-$k",db_size($k));}json_row("");}exit;}else{$Ki=array_merge((array)$_POST["tables"],(array)$_POST["views"]);if($Ki&&!$m&&!$_POST["search"]){$I=true;$qf="";if(JUSH=="sql"&&$_POST["tables"]&&count($_POST["tables"])>1&&($_POST["drop"]||$_POST["truncate"]||$_POST["copy"]))queries("SET foreign_key_checks = 0");if($_POST["truncate"]){if($_POST["tables"])$I=truncate_tables($_POST["tables"]);$qf=lang(279);}elseif($_POST["move"]){$I=move_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(280);}elseif($_POST["copy"]){$I=copy_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(281);}elseif($_POST["drop"]){if($_POST["views"])$I=drop_views($_POST["views"]);if($I&&$_POST["tables"])$I=drop_tables($_POST["tables"]);$qf=lang(282);}elseif(JUSH=="sqlite"&&$_POST["check"]){foreach((array)$_POST["tables"]as$R){foreach(get_rows("PRAGMA integrity_check(".q($R).")")as$K)$qf +.="".h($R).": ".h($K["integrity_check"])."
    ";}}elseif(JUSH!="sql"){$I=(JUSH=="sqlite"?queries("VACUUM"):apply_queries("VACUUM".($_POST["optimize"]?"":" ANALYZE"),$_POST["tables"]));$qf=lang(283);}elseif(!$_POST["tables"])$qf=lang(11);elseif($I=queries(($_POST["optimize"]?"OPTIMIZE":($_POST["check"]?"CHECK":($_POST["repair"]?"REPAIR":"ANALYZE")))." TABLE ".implode(", ",array_map('Adminer\idf_escape',$_POST["tables"])))){while($K=$I->fetch_assoc())$qf +.="".h($K["Table"]).": ".h($K["Msg_text"])."
    ";}queries_redirect(substr(ME,0,-1),$qf,$I);}page_header(($_GET["ns"]==""?lang(38).": ".h(DB):lang(80).": ".h($_GET["ns"])),$m,true);if(adminer()->homepage()){if($_GET["ns"]!==""){echo"

    ".lang(284)."

    \n";$Ji=tables_list();if(!$Ji)echo"

    ".lang(11)."\n";else{echo"

    \n";if(support("table")){echo"
    ".lang(285)."
    ",html_select("op",adminer()->operators(),idx($_POST,"op",JUSH=="elastic"?"should":"LIKE %%"))," ",script("qsl('input').onkeydown = partialArg(bodyKeydown, 'search');","")," \n","
    \n";if($_POST["search"]&&$_POST["query"]!=""){$_GET["where"][0]["op"]=$_POST["op"];search_tables();}}echo"
    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),'','\n";$T=0;foreach($Ji +as$B=>$U){$Rj=($U!==null&&!preg_match('~table|sequence~i',$U));$u=h("Table-".$B);echo'
    '.script("qs('#check-all').onclick = partial(formCheck, /^(tables|views)\[/);",""),''.lang(139);$e=array("Engine"=>array(lang(286).doc_link(array('sql'=>'storage-engines.html'))));if(collations())$e["Collation"]=array(lang(128).doc_link(array('sql'=>'charset-charsets.html','mariadb'=>'supported-character-sets-and-collations/')));if(function_exists('Adminer\alter_table'))$e["Data_length"]=array(lang(287).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT','oracle'=>'REFRN20286')),"create",lang(45));if(support('indexes'))$e["Index_length"]=array(lang(288).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT')),"indexes",lang(142));$e["Data_free"]=array(lang(289).doc_link(array('sql'=>'show-table-status.html')),"edit",lang(46));if(function_exists('Adminer\alter_table'))$e["Auto_increment"]=array(lang(52).doc_link(array('sql'=>'example-auto-increment.html','mariadb'=>'auto_increment/')),"auto_increment=1&create",lang(45));$e["Rows"]=array(lang(290).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'catalog-pg-class.html#CATALOG-PG-CLASS','oracle'=>'REFRN20286')),"select",lang(42));if(support("comment"))$e["Comment"]=array(lang(51).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-info.html#FUNCTIONS-INFO-COMMENT-TABLE')));foreach($e +as$d)echo"$d[0]";echo"
    '.checkbox(($Rj?"views[]":"tables[]"),$B,in_array("$B",$Ki,true),"","","",$u),''.(support("table")||support("indexes")?"".h($B).'':h($B));if($Rj&&!preg_match('~materialized~i',$U)){$Wi=lang(138);echo''.(support("view")?"$Wi":$Wi),'?';}else{foreach($e +as$y=>$d){$u=" id='$y-".h($B)."'";echo($d[1]?"?":"");}$T++;}echo"\n";}echo"
    ".lang(263,count($Ji)),"".h(JUSH=="sql"?get_val("SELECT @@default_storage_engine"):""),"".h(db_collation(DB,collations()));foreach(array("Data_length","Index_length","Data_free")as$y)echo($e[$y]?"":"");echo"\n","
    \n",script("ajaxSetHtml('".js_escape(ME)."script=db');"),"
    \n";if(!information_schema(DB)){$Lj=" ".on_help("'VACUUM'");$eg=" ".on_help(JUSH=="sql"?"'OPTIMIZE TABLE'":"'VACUUM OPTIMIZE'");$bh=(JUSH=="sqlite"?$Lj." ".on_help("'PRAGMA integrity_check'"):(JUSH=="pgsql"?$Lj.$eg:(JUSH=="sql"?" ".on_help("'ANALYZE TABLE'").$eg." ".on_help("'CHECK TABLE'")." ".on_help("'REPAIR TABLE'"):""))).(function_exists('Adminer\truncate_tables')?" ".on_help(JUSH=="sqlite"?"'DELETE'":"'TRUNCATE".(JUSH=="pgsql"?"'":" TABLE'")).confirm():"").(function_exists('Adminer\drop_tables')?"".on_help("'DROP TABLE'").confirm():"");echo($bh?"\n";}echo"
    \n",script("tableCheck();");}echo(function_exists('Adminer\alter_table')?"

    ".lang(73)."

    \n";$Fh=routines();if($Fh){echo"\n",'\n";foreach($Fh +as$K){$B=($K["SPECIFIC_NAME"]==$K["ROUTINE_NAME"]?"":"&name=".urlencode($K["ROUTINE_NAME"]));echo'','
    '.lang(194).''.lang(50).''.lang(233)."
    '.h($K["ROUTINE_NAME"]).'',''.h($K["ROUTINE_TYPE"]),''.h($K["DTD_IDENTIFIER"]),''.lang(145)."";}echo"
    \n";}echo'

    ".lang(74)."

    \n";$Yh=get_vals("SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = current_schema() ORDER BY sequence_name");if($Yh){echo"\n","\n";foreach($Yh +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(6)."

    \n";$Ij=types();if($Ij){echo"\n","\n";foreach($Ij +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(75)."

    \n";$L=get_rows("SHOW EVENTS");if($L){echo"\n","\n";foreach($L +as$K)echo"","
    ".lang(194)."".lang(301)."".lang(222)."".lang(223)."
    ".h($K["Name"]),"".($K["Execute at"]?lang(302)."".$K["Execute at"]:lang(224)." ".$K["Interval value"]." ".$K["Interval field"]."$K[Starts]"),"$K[Ends]",''.lang(145).'';echo"
    \n";$Hc=get_val("SELECT @@event_scheduler");if($Hc&&$Hc!="ON")echo"

    event_scheduler: ".h($Hc)."\n";}echo'

    \n";return -true;}function -login($rd,$_e){return -true;}}function -adminer_object(){$Ge=array(new -FCSqliteConnectionWithoutCredentials());return -new -AdminerPlugin($Ge);}function -adminer_errors($Rb,$Tb){return!!preg_match('~^(Trying to access array offset on value of type null|Undefined array key)~',$Tb);}error_reporting(6135);set_error_handler('adminer_errors',E_WARNING);$kc=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($kc||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$Hg=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($Hg)$$X=$Hg;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function -connection(){global$f;return$f;}function -adminer(){global$b;return$b;}function -version(){global$da;return$da;}function -idf_unescape($Kc){if(!preg_match('~^[`\'"]~',$Kc))return$Kc;$hd=substr($Kc,-1);return -str_replace($hd.$hd,$hd,substr($Kc,1,-1));}function +* @version 5.4.2 +*/namespace +Adminer;const +VERSION="5.4.2";error_reporting(24575);set_error_handler(function($Dc,$Fc){return!!preg_match('~^Undefined (array key|offset|index)~',$Fc);},E_WARNING|E_NOTICE);$bd=!preg_match('~^(unsafe_raw)?$~',ini_get("filter.default"));if($bd||ini_get("filter.default_flags")){foreach(array('_GET','_POST','_COOKIE','_SERVER')as$X){$xj=filter_input_array(constant("INPUT$X"),FILTER_UNSAFE_RAW);if($xj)$$X=$xj;}}if(function_exists("mb_internal_encoding"))mb_internal_encoding("8bit");function +connection($h=null){return($h?:Db::$instance);}function +adminer(){return +Adminer::$instance;}function +driver(){return +Driver::$instance;}function +connect(){$Hb=adminer()->credentials();$J=Driver::connect($Hb[0],$Hb[1],$Hb[2]);return(is_object($J)?$J:null);}function +idf_unescape($v){if(!preg_match('~^[`\'"[]~',$v))return$v;$Le=substr($v,-1);return +str_replace($Le.$Le,$Le,substr($v,1,-1));}function +q($Q){return +connection()->quote($Q);}function escape_string($X){return substr(q($X),1,-1);}function +idx($xa,$y,$l=null){return($xa&&array_key_exists($y,$xa)?$xa[$y]:$l);}function number($X){return preg_replace('~[^0-9]+~','',$X);}function number_type(){return'((?$W){unset($Te[$z][$ad]);if(is_array($W)){$Te[$z][stripslashes($ad)]=$W;$Te[]=&$Te[$z][stripslashes($ad)];}else$Te[$z][stripslashes($ad)]=($kc?$W:stripslashes($W));}}}}function -bracket_escape($Kc,$ua=false){static$vg=array(':'=>':1',']'=>':2','['=>':3','"'=>':4');return -strtr($Kc,($ua?array_flip($vg):$vg));}function -min_version($Xg,$td="",$g=null){global$f;if(!$g)$g=$f;$yf=$g->server_info;if($td&&preg_match('~([\d.]+)-MariaDB~',$yf,$C)){$yf=$C[1];$Xg=$td;}return(version_compare($yf,$Xg)>=0);}function -charset($f){return(min_version("5.5.3",0,$f)?"utf8mb4":"utf8");}function -script($Ff,$ug="\n"){return"$Ff$ug";}function -script_src($Mg){return"\n";}function -nonce(){return' nonce="'.get_nonce().'"';}function -target_blank(){return' target="_blank" rel="noreferrer noopener"';}function -h($Q){return -str_replace("\0","�",htmlspecialchars($Q,ENT_QUOTES,'utf-8'));}function -nl_br($Q){return -str_replace("\n","
    ",$Q);}function -checkbox($F,$Y,$Fa,$ed="",$Yd="",$Ja="",$fd=""){$K="".($Yd?script("qsl('input').onclick = function () { $Yd };",""):"");return($ed!=""||$Ja?"$K".h($ed)."":$K);}function -optionlist($de,$tf=null,$Qg=false){$K="";foreach($de -as$ad=>$W){$ee=array($ad=>$W);if(is_array($W)){$K.='';$ee=$W;}foreach($ee -as$z=>$X)$K.=''.h($X);if(is_array($W))$K.='';}return$K;}function -html_select($F,$de,$Y="",$Xd=true,$fd=""){if($Xd)return"".(is_string($Xd)?script("qsl('select').onchange = function () { $Xd };",""):"");$K="";foreach($de -as$z=>$X)$K.="";return$K;}function -select_input($ra,$de,$Y="",$Xd="",$Ee=""){$cg=($de?"select":"input");return"<$cg$ra".($de?">

    ","$md",script("qsl('a').onclick = partial(toggle, 'fieldset-$v');",""),"","
    \n";}function -selectOrderPrint($fe,$e,$x){print_fieldset("sort",'Sort',$fe);$u=0;foreach((array)$_GET["order"]as$z=>$X){if($X!=""){echo"
    ".select_input(" name='order[$u]'",$e,$X,"selectFieldChange"),checkbox("desc[$u]",1,isset($_GET["desc"][$z]),'descending')."
    \n";$u++;}}echo"
    ".select_input(" name='order[$u]'",$e,"","selectAddRow"),checkbox("desc[$u]",1,false,'descending')."
    \n","\n";}function -selectLimitPrint($_){echo"
    ".'Limit'."
    ";echo"",script("qsl('input').oninput = selectFieldChange;",""),"
    \n";}function -selectLengthPrint($ig){if($ig!==null){echo"
    ".'Text length'."
    ","","
    \n";}}function -selectActionPrint($x){echo"
    ".'Action'."
    ",""," ","\n","var indexColumns = ";$e=array();foreach($x -as$w){$gb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$gb)$e[$gb]=1;}$e[""]=1;foreach($e -as$z=>$X)json_row($z);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
    \n";}function +rowDescriptions(array$L,array$ld){return$L;}function +selectLink($X,array$n){}function +selectVal($X,$_,array$n,$sg){$J=($X===null?"NULL":(preg_match("~char|binary|boolean~",$n["type"])&&!preg_match("~var~",$n["type"])?"$X":(preg_match('~json~',$n["type"])?"$X":$X)));if(is_blob($n)&&!is_utf8($X))$J="".lang(48,strlen($sg))."";return($_?"$J":$J);}function +editVal($X,array$n){return$X;}function +config(){return +array();}function +tableStructurePrint(array$o,$Bi=null){echo"
    \n","\n","\n";$vi=driver()->structuredTypes();foreach($o +as$n){echo"
    ".lang(49)."".lang(50).(support("comment")?"".lang(51):"")."
    ".h($n["field"]);$U=h($n["full_type"]);$c=h($n["collation"]);echo"".(in_array($U,(array)$vi[lang(6)])?"$U":$U.($c&&isset($Bi["Collation"])&&$c!=$Bi["Collation"]?" $c":""))."",($n["null"]?" NULL":""),($n["auto_increment"]?" ".lang(52)."":"");$l=h($n["default"]);echo(isset($n["default"])?" [".($n["generated"]?"$l":$l)."]":""),(support("comment")?"".h($n["comment"]):""),"\n";}echo"
    \n","
    \n";}function +tableIndexesPrint(array$x,array$Bi){$Cg=false;foreach($x +as$B=>$w)$Cg|=!!$w["partial"];echo"\n";$Ub=first(driver()->indexAlgorithms($Bi));foreach($x +as$B=>$w){ksort($w["columns"]);$bh=array();foreach($w["columns"]as$y=>$X)$bh[]="".h($X)."".($w["lengths"][$y]?"(".$w["lengths"][$y].")":"").($w["descs"][$y]?" DESC":"");echo"","
    $w[type]".($Ub&&$w['algorithm']!=$Ub?" ($w[algorithm])":""),"".implode(", ",$bh);if($Cg)echo"".($w['partial']?"WHERE ".h($w['partial']):"");echo"\n";}echo"
    \n";}function +selectColumnsPrint(array$M,array$e){print_fieldset("select",lang(54),$M);$t=0;$M[""]=array();foreach($M +as$y=>$X){$X=idx($_GET["columns"],$y,array());$d=select_input(" name='columns[$t][col]'",$e,$X["col"],($y!==""?"selectFieldChange":"selectAddRow"));echo"
    ".(driver()->functions||driver()->grouping?html_select("columns[$t][fun]",array(-1=>"")+array_filter(array(lang(55)=>driver()->functions,lang(56)=>driver()->grouping)),$X["fun"]).on_help("event.target.value && event.target.value.replace(/ |\$/, '(') + ')'",1).script("qsl('select').onchange = function () { helpClose();".($y!==""?"":" qsl('select, input', this.parentNode).onchange();")." };","")."($d)":$d)."
    \n";$t++;}echo"\n";}function +selectSearchPrint(array$Z,array$e,array$x){print_fieldset("search",lang(57),$Z);foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT")echo"
    (".implode(", ",array_map('Adminer\h',$w["columns"])).") AGAINST"," ",script("qsl('input').oninput = selectFieldChange;",""),(JUSH=='sql'?checkbox("boolean[$t]",1,isset($_GET["boolean"][$t]),"BOOL"):''),"
    \n";}$Va="this.parentNode.firstChild.onchange();";foreach(array_merge((array)$_GET["where"],array(array()))as$t=>$X){if(!$X||("$X[col]$X[val]"!=""&&in_array($X["op"],adminer()->operators())))echo"
    ".select_input(" name='where[$t][col]'",$e,$X["col"],($X?"selectFieldChange":"selectAddRow"),"(".lang(58).")"),html_select("where[$t][op]",adminer()->operators(),$X["op"],$Va),"",script("mixin(qsl('input'), {oninput: function () { $Va }, onkeydown: selectSearchKeydown, onsearch: selectSearchSearch});",""),"
    \n";}echo"\n";}function +selectOrderPrint(array$ig,array$e,array$x){print_fieldset("sort",lang(59),$ig);$t=0;foreach((array)$_GET["order"]as$y=>$X){if($X!=""){echo"
    ".select_input(" name='order[$t]'",$e,$X,"selectFieldChange"),checkbox("desc[$t]",1,isset($_GET["desc"][$y]),lang(60))."
    \n";$t++;}}echo"
    ".select_input(" name='order[$t]'",$e,"","selectAddRow"),checkbox("desc[$t]",1,false,lang(60))."
    \n","\n";}function +selectLimitPrint($z){echo"
    ".lang(61)."
    ","",script("qsl('input').oninput = selectFieldChange;",""),"
    \n";}function +selectLengthPrint($Si){if($Si!==null)echo"
    ".lang(62)."
    ","","
    \n";}function +selectActionPrint(array$x){echo"
    ".lang(63)."
    ",""," ","\n","const indexColumns = ";$e=array();foreach($x +as$w){$Lb=reset($w["columns"]);if($w["type"]!="FULLTEXT"&&$Lb)$e[$Lb]=1;}$e[""]=1;foreach($e +as$y=>$X)json_row($y);echo";\n","selectFieldChange.call(qs('#form')['select']);\n","\n","
    \n";}function selectCommandPrint(){return!information_schema(DB);}function selectImportPrint(){return!information_schema(DB);}function -selectEmailPrint($Lb,$e){}function -selectColumnsProcess($e,$x){global$uc,$yc;$N=array();$t=array();foreach((array)$_GET["columns"]as$z=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],$uc)||in_array($X["fun"],$yc)))){$N[$z]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],$yc))$t[]=$N[$z];}}return -array($N,$t);}function -selectSearchProcess($n,$x){global$f,$k;$K=array();foreach($x -as$u=>$w){if($w["type"]=="FULLTEXT"&&$_GET["fulltext"][$u]!="")$K[]="MATCH (".implode(", ",array_map('idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$u]).(isset($_GET["boolean"][$u])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$z=>$X){if("$X[col]$X[val]"!=""&&in_array($X["op"],$this->operators)){$Me="";$Va=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Nc=process_length($X["val"]);$Va.=" ".($Nc!=""?$Nc:"(NULL)");}elseif($X["op"]=="SQL")$Va=" $X[val]";elseif($X["op"]=="LIKE %%")$Va=" LIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="ILIKE %%")$Va=" ILIKE ".$this->processInput($n[$X["col"]],"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Me="$X[op](".q($X["val"]).", ";$Va=")";}elseif(!preg_match('~NULL$~',$X["op"]))$Va.=" ".$this->processInput($n[$X["col"]],$X["val"]);if($X["col"]!="")$K[]=$Me.$k->convertSearch(idf_escape($X["col"]),$X,$n[$X["col"]]).$Va;else{$Qa=array();foreach($n -as$F=>$m){if((preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$m["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$m["type"]))&&(!preg_match('~date|timestamp~',$m["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"])))$Qa[]=$Me.$k->convertSearch(idf_escape($F),$X,$m).$Va;}$K[]=($Qa?"(".implode(" OR ",$Qa).")":"1 = 0");}}}return$K;}function -selectOrderProcess($n,$x){$K=array();foreach((array)$_GET["order"]as$z=>$X){if($X!="")$K[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$z])?" DESC":"");}return$K;}function -selectLimitProcess(){return(isset($_GET["limit"])?$_GET["limit"]:"50");}function -selectLengthProcess(){return(isset($_GET["text_length"])?$_GET["text_length"]:"100");}function -selectEmailProcess($Z,$pc){return +selectEmailPrint(array$vc,array$e){}function +selectColumnsProcess(array$e,array$x){$M=array();$xd=array();foreach((array)$_GET["columns"]as$y=>$X){if($X["fun"]=="count"||($X["col"]!=""&&(!$X["fun"]||in_array($X["fun"],driver()->functions)||in_array($X["fun"],driver()->grouping)))){$M[$y]=apply_sql_function($X["fun"],($X["col"]!=""?idf_escape($X["col"]):"*"));if(!in_array($X["fun"],driver()->grouping))$xd[]=$M[$y];}}return +array($M,$xd);}function +selectSearchProcess(array$o,array$x){$J=array();foreach($x +as$t=>$w){if($w["type"]=="FULLTEXT"&&idx($_GET["fulltext"],$t)!="")$J[]="MATCH (".implode(", ",array_map('Adminer\idf_escape',$w["columns"])).") AGAINST (".q($_GET["fulltext"][$t]).(isset($_GET["boolean"][$t])?" IN BOOLEAN MODE":"").")";}foreach((array)$_GET["where"]as$y=>$X){$jb=$X["col"];if("$jb$X[val]"!=""&&in_array($X["op"],adminer()->operators())){$ub=array();foreach(($jb!=""?array($jb=>$o[$jb]):$o)as$B=>$n){$Xg="";$tb=" $X[op]";if(preg_match('~IN$~',$X["op"])){$Xd=process_length($X["val"]);$tb +.=" ".($Xd!=""?$Xd:"(NULL)");}elseif($X["op"]=="SQL")$tb=" $X[val]";elseif(preg_match('~^(I?LIKE) %%$~',$X["op"],$A))$tb=" $A[1] ".adminer()->processInput($n,"%$X[val]%");elseif($X["op"]=="FIND_IN_SET"){$Xg="$X[op](".q($X["val"]).", ";$tb=")";}elseif(!preg_match('~NULL$~',$X["op"]))$tb +.=" ".adminer()->processInput($n,$X["val"]);if($jb!=""||(isset($n["privileges"]["where"])&&(preg_match('~^[-\d.'.(preg_match('~IN$~',$X["op"])?',':'').']+$~',$X["val"])||!preg_match('~'.number_type().'|bit~',$n["type"]))&&(!preg_match("~[\x80-\xFF]~",$X["val"])||preg_match('~char|text|enum|set~',$n["type"]))&&(!preg_match('~date|timestamp~',$n["type"])||preg_match('~^\d+-\d+-\d+~',$X["val"]))))$ub[]=$Xg.driver()->convertSearch(idf_escape($B),$X,$n).$tb;}$J[]=(count($ub)==1?$ub[0]:($ub?"(".implode(" OR ",$ub).")":"1 = 0"));}}return$J;}function +selectOrderProcess(array$o,array$x){$J=array();foreach((array)$_GET["order"]as$y=>$X){if($X!="")$J[]=(preg_match('~^((COUNT\(DISTINCT |[A-Z0-9_]+\()(`(?:[^`]|``)+`|"(?:[^"]|"")+")\)|COUNT\(\*\))$~',$X)?$X:idf_escape($X)).(isset($_GET["desc"][$y])?" DESC":"");}return$J;}function +selectLimitProcess(){return(isset($_GET["limit"])?intval($_GET["limit"]):50);}function +selectLengthProcess(){return(isset($_GET["text_length"])?"$_GET[text_length]":"100");}function +selectEmailProcess(array$Z,array$ld){return false;}function -selectQueryBuild($N,$Z,$t,$fe,$_,$G){return"";}function -messageQuery($I,$jg,$fc=false){global$y,$k;restart_session();$Fc=&get_session("queries");if(!$Fc[$_GET["db"]])$Fc[$_GET["db"]]=array();if(strlen($I)>1e6)$I=preg_replace('~[\x80-\xFF]+$~','',substr($I,0,1e6))."\n…";$Fc[$_GET["db"]][]=array($I,time(),$jg);$Jf="sql-".count($Fc[$_GET["db"]]);$K="".'SQL command'."\n";if(!$fc&&($ch=$k->warnings())){$v="warnings-".count($Fc[$_GET["db"]]);$K="".'Warnings'.", $K\n";}return" ".@date("H:i:s").""." $K';}function -editRowPrint($R,$n,$L,$Kg){}function -editFunctions($m){global$Gb;$K=($m["null"]?"NULL/":"");$Kg=isset($_GET["select"])||where($_GET);foreach($Gb -as$z=>$uc){if(!$z||(!isset($_GET["call"])&&$Kg)){foreach($uc -as$Be=>$X){if(!$Be||preg_match("~$Be~",$m["type"]))$K.="/$X";}}if($z&&!preg_match('~set|blob|bytea|raw|file|bool~',$m["type"]))$K.="/SQL";}if($m["auto_increment"]&&!$Kg)$K='Auto Increment';return -explode("/",$K);}function -editInput($R,$m,$ra,$Y){if($m["type"]=="enum")return(isset($_GET["select"])?" ":"").($m["null"]?" ":"").enum_input("radio",$ra,$m,$Y,0);return"";}function -editHint($R,$m,$Y){return"";}function -processInput($m,$Y,$s=""){if($s=="SQL")return$Y;$F=$m["field"];$K=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$K="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$K=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$K=idf_escape($F)." $s $K";elseif(preg_match('~^[+-] interval$~',$s))$K=idf_escape($F)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)?$Y:$K);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$K="$s(".idf_escape($F).", $K)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$K="$s($K)";return -unconvert_field($m,$K);}function -dumpOutput(){$K=array('text'=>'open','file'=>'save');if(function_exists('gzencode'))$K['gz']='gzip';return$K;}function -dumpFormat(){return -array('sql'=>'SQL','csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function -dumpDatabase($j){}function -dumpTable($R,$Pf,$Yc=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($Pf)dump_csv(array_keys(fields($R)));}else{if($Yc==2){$n=array();foreach(fields($R)as$F=>$m)$n[]=idf_escape($F)." $m[full_type]";$h="CREATE TABLE ".table($R)." (".implode(", ",$n).")";}else$h=create_sql($R,$_POST["auto_increment"],$Pf);set_utf8mb4($h);if($Pf&&$h){if($Pf=="DROP+CREATE"||$Yc==1)echo"DROP ".($Yc==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($Yc==1)$h=remove_definer($h);echo"$h;\n\n";}}}function -dumpData($R,$Pf,$I){global$f,$y;$wd=($y=="sqlite"?0:1048576);if($Pf){if($_POST["format"]=="sql"){if($Pf=="TRUNCATE+INSERT")echo -truncate_sql($R).";\n";$n=fields($R);}$J=$f->query($I,1);if($J){$Sc="";$Ca="";$cd=array();$Rf="";$ic=($R!=''?'fetch_assoc':'fetch_row');while($L=$J->$ic()){if(!$cd){$Ug=array();foreach($L -as$X){$m=$J->fetch_field();$cd[]=$m->name;$z=idf_escape($m->name);$Ug[]="$z = VALUES($z)";}$Rf=($Pf=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Ug):"").";\n";}if($_POST["format"]!="sql"){if($Pf=="table"){dump_csv($cd);$Pf="INSERT";}dump_csv($L);}else{if(!$Sc)$Sc="INSERT INTO ".table($R)." (".implode(", ",array_map('idf_escape',$cd)).") VALUES";foreach($L -as$z=>$X){$m=$n[$z];$L[$z]=($X!==null?unconvert_field($m,preg_match(number_type(),$m["type"])&&!preg_match('~\[~',$m["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$pf=($wd?"\n":" ")."(".implode(",\t",$L).")";if(!$Ca)$Ca=$Sc.$pf;elseif(strlen($Ca)+4+strlen($pf)+strlen($Rf)<$wd)$Ca.=",$pf";else{echo$Ca.$Rf;$Ca=$Sc.$pf;}}}if($Ca)echo$Ca.$Rf;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",$f->error)."\n";}}function -dumpFilename($Jc){return -friendly_url($Jc!=""?$Jc:(SERVER!=""?SERVER:"localhost"));}function -dumpHeaders($Jc,$Id=false){$qe=$_POST["output"];$bc=(preg_match('~sql~',$_POST["format"])?"sql":($Id?"tar":"csv"));header("Content-Type: ".($qe=="gz"?"application/x-gzip":($bc=="tar"?"application/x-tar":($bc=="sql"||$qe!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($qe=="gz")ob_start('ob_gzencode',1e6);return$bc;}function +selectQueryBuild(array$M,array$Z,array$xd,array$ig,$z,$D){return"";}function +messageQuery($H,$Ti,$Tc=false){restart_session();$Kd=&get_session("queries");if(!idx($Kd,$_GET["db"]))$Kd[$_GET["db"]]=array();if(strlen($H)>1e6)$H=preg_replace('~[\x80-\xFF]+$~','',substr($H,0,1e6))."\n…";$Kd[$_GET["db"]][]=array($H,time(),$Ti);$oi="sql-".count($Kd[$_GET["db"]]);$J="".lang(65)." �\n";if(!$Tc&&($Vj=driver()->warnings())){$u="warnings-".count($Kd[$_GET["db"]]);$J="".lang(47).", $J\n";}return" ".@date("H:i:s").""." $J';}function +editRowPrint($R,array$o,$K,$_j){}function +editFunctions(array$n){$J=($n["null"]?"NULL/":"");$_j=isset($_GET["select"])||where($_GET);foreach(array(driver()->insertFunctions,driver()->editFunctions)as$y=>$sd){if(!$y||(!isset($_GET["call"])&&$_j)){foreach($sd +as$Lg=>$X){if(!$Lg||preg_match("~$Lg~",$n["type"]))$J +.="/$X";}}if($y&&$sd&&!preg_match('~set|bool~',$n["type"])&&!is_blob($n))$J +.="/SQL";}if($n["auto_increment"]&&!$_j)$J=lang(52);return +explode("/",$J);}function +editInput($R,array$n,$_a,$Y){if($n["type"]=="enum")return(isset($_GET["select"])?" ":"").enum_input("radio",$_a,$n,$Y,"NULL");return"";}function +editHint($R,array$n,$Y){return"";}function +processInput(array$n,$Y,$s=""){if($s=="SQL")return$Y;$B=$n["field"];$J=q($Y);if(preg_match('~^(now|getdate|uuid)$~',$s))$J="$s()";elseif(preg_match('~^current_(date|timestamp)$~',$s))$J=$s;elseif(preg_match('~^([+-]|\|\|)$~',$s))$J=idf_escape($B)." $s $J";elseif(preg_match('~^[+-] interval$~',$s))$J=idf_escape($B)." $s ".(preg_match("~^(\\d+|'[0-9.: -]') [A-Z_]+\$~i",$Y)&&JUSH!="pgsql"?$Y:$J);elseif(preg_match('~^(addtime|subtime|concat)$~',$s))$J="$s(".idf_escape($B).", $J)";elseif(preg_match('~^(md5|sha1|password|encrypt)$~',$s))$J="$s($J)";return +unconvert_field($n,$J);}function +dumpOutput(){$J=array('text'=>lang(66),'file'=>lang(67));if(function_exists('gzencode'))$J['gz']='gzip';return$J;}function +dumpFormat(){return(support("dump")?array('sql'=>'SQL'):array())+array('csv'=>'CSV,','csv;'=>'CSV;','tsv'=>'TSV');}function +dumpDatabase($k){}function +dumpTable($R,$wi,$ze=0){if($_POST["format"]!="sql"){echo"\xef\xbb\xbf";if($wi)dump_csv(array_keys(fields($R)));}else{if($ze==2){$o=array();foreach(fields($R)as$B=>$n)$o[]=idf_escape($B)." $n[full_type]";$i="CREATE TABLE ".table($R)." (".implode(", ",$o).")";}else$i=create_sql($R,$_POST["auto_increment"],$wi);set_utf8mb4($i);if($wi&&$i){if($wi=="DROP+CREATE"||$ze==1)echo"DROP ".($ze==2?"VIEW":"TABLE")." IF EXISTS ".table($R).";\n";if($ze==1)$i=remove_definer($i);echo"$i;\n\n";}}}function +dumpData($R,$wi,$H){if($wi){$hf=(JUSH=="sqlite"?0:1048576);$o=array();$Td=false;if($_POST["format"]=="sql"){if($wi=="TRUNCATE+INSERT")echo +truncate_sql($R).";\n";$o=fields($R);if(JUSH=="mssql"){foreach($o +as$n){if($n["auto_increment"]){echo"SET IDENTITY_INSERT ".table($R)." ON;\n";$Td=true;break;}}}}$I=connection()->query($H,1);if($I){$oe="";$Pa="";$Ee=array();$td=array();$yi="";$Wc=($R!=''?'fetch_assoc':'fetch_row');$Eb=0;while($K=$I->$Wc()){if(!$Ee){$Nj=array();foreach($K +as$X){$n=$I->fetch_field();if(idx($o[$n->name],'generated')){$td[$n->name]=true;continue;}$Ee[]=$n->name;$y=idf_escape($n->name);$Nj[]="$y = VALUES($y)";}$yi=($wi=="INSERT+UPDATE"?"\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj):"").";\n";}if($_POST["format"]!="sql"){if($wi=="table"){dump_csv($Ee);$wi="INSERT";}dump_csv($K);}else{if(!$oe)$oe="INSERT INTO ".table($R)." (".implode(", ",array_map('Adminer\idf_escape',$Ee)).") VALUES";foreach($K +as$y=>$X){if($td[$y]){unset($K[$y]);continue;}$n=$o[$y];$K[$y]=($X!==null?unconvert_field($n,preg_match(number_type(),$n["type"])&&!preg_match('~\[~',$n["full_type"])&&is_numeric($X)?$X:q(($X===false?0:$X))):"NULL");}$Hh=($hf?"\n":" ")."(".implode(",\t",$K).")";if(!$Pa)$Pa=$oe.$Hh;elseif(JUSH=='mssql'?$Eb%1000!=0:strlen($Pa)+4+strlen($Hh)+strlen($yi)<$hf)$Pa +.=",$Hh";else{echo$Pa.$yi;$Pa=$oe.$Hh;}}$Eb++;}if($Pa)echo$Pa.$yi;}elseif($_POST["format"]=="sql")echo"-- ".str_replace("\n"," ",connection()->error)."\n";if($Td)echo"SET IDENTITY_INSERT ".table($R)." OFF;\n";}}function +dumpFilename($Rd){return +friendly_url($Rd!=""?$Rd:(SERVER?:"localhost"));}function +dumpHeaders($Rd,$Af=false){$vg=$_POST["output"];$Oc=(preg_match('~sql~',$_POST["format"])?"sql":($Af?"tar":"csv"));header("Content-Type: ".($vg=="gz"?"application/x-gzip":($Oc=="tar"?"application/x-tar":($Oc=="sql"||$vg!="file"?"text/plain":"text/csv")."; charset=utf-8")));if($vg=="gz"){ob_start(function($Q){return +gzencode($Q);},1e6);}return$Oc;}function +dumpFooter(){if($_POST["format"]=="sql")echo"-- ".gmdate("Y-m-d H:i:s e")."\n";}function importServerPath(){return"adminer.sql";}function -homepage(){echo'

    -',$this->name(),' ',$da,' -',(version_compare($da,$_COOKIE["adminer_version"])<0?h($_COOKIE["adminer_version"]):""),' -

    -';if($Hd=="auth"){$qe="";foreach((array)$_SESSION["pwds"]as$Wg=>$zf){foreach($zf -as$O=>$Sg){foreach($Sg -as$Rg=>$_e){if($_e!==null){$mb=$_SESSION["db"][$Wg][$O][$Rg];foreach(($mb?array_keys($mb):array(""))as$j)$qe.="
  • ($zb[$Wg]) ".h($Rg.($O!=""?"@".$this->serverName($O):"").($j!=""?" - $j":""))."\n";}}}}if($qe)echo"
      \n$qe
    \n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$Hd&&DB!=""){$f->select_db(DB);$T=table_status('',true);}echo -script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=4.8.1");if(support("sql")){echo' -';if($T){$qd=array();foreach($T -as$R=>$V)$qd[]=preg_quote($R,'/');echo"var jushLinks = { $y: [ '".js_escape(ME).(support("table")?"table=":"select=")."\$&', /\\b(".implode("|",$qd).")\\b/g ] };\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.$y;\n";}$yf=$f->server_info;echo'bodyLoad(\'',(is_object($f)?preg_replace('~^(\d\.?\d).*~s','\1',$yf):""),'\'',(preg_match('~MariaDB~',$yf)?", true":""),'); - -';}$this->databasesPrint($Hd);if(DB==""||!$Hd){echo"

    ".'No tables.'."\n";else$this->tablesPrint($T);}}}function -databasesPrint($Hd){global$b,$f;$i=$this->databases();if(DB&&$i&&!in_array(DB,$i))array_unshift($i,DB);echo'

    -

    -';hidden_fields_get();$kb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"".'DB'.": ".($i?"$kb":"\n"),"\n";foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo"";break;}}echo"

    \n";}function -tablesPrint($T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T -as$R=>$Mf){$F=$this->tableName($Mf);if($F!=""){echo'
    • ".'select'." ",(support("table")||support("indexes")?'$F":"$F")."\n";}}echo"
    \n";}}$b=(function_exists('adminer_object')?adminer_object():new -Adminer);$Wa=driver_config();$Le=$Wa['possible_drivers'];$y=$Wa['jush'];$Cg=$Wa['types'];$Of=$Wa['structured_types'];$Jg=$Wa['unsigned'];$ae=$Wa['operators'];$uc=$Wa['functions'];$yc=$Wa['grouping'];$Gb=$Wa['edit_functions'];if($b->operators===null)$b->operators=$ae;define("SERVER",$_GET[DRIVER]);define("DB",$_GET["db"]);define("ME",preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));$da="4.8.1";function -page_header($mg,$l="",$Ba=array(),$ng=""){global$ba,$da,$b,$zb,$y;page_headers();if(is_ajax()&&$l){page_messages($l);exit;}$og=$mg.($ng!=""?": $ng":"");$pg=strip_tags($og.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".$b->name());echo' - +navigation($xf){echo"

    ".adminer()->name()." ".VERSION;$If=$_COOKIE["adminer_version"];echo" ".(version_compare(VERSION,$If)<0?h($If):"")."","

    \n";switch_lang();if($xf=="auth"){$vg="";foreach((array)$_SESSION["pwds"]as$Pj=>$ai){foreach($ai +as$N=>$Jj){$B=h(get_setting("vendor-$Pj-$N")?:get_driver($Pj));foreach($Jj +as$V=>$F){if($F!==null){$Sb=$_SESSION["db"][$Pj][$N][$V];foreach(($Sb?array_keys($Sb):array(""))as$k)$vg +.="
  • ($B) ".h("$V@".($N!=""?adminer()->serverName($N):"").($k!=""?" - $k":""))."\n";}}}}if($vg)echo"
      \n$vg
    \n".script("mixin(qs('#logins'), {onmouseover: menuOver, onmouseout: menuOut});");}else{$T=array();if($_GET["ns"]!==""&&!$xf&&DB!=""){connection()->select_db(DB);$T=table_status('',true);}adminer()->syntaxHighlighting($T);adminer()->databasesPrint($xf);$ka=array();if(DB==""||!$xf){if(support("sql")){$ka[]="".lang(65)."";$ka[]="".lang(76)."";}$ka[]="".lang(77)."";}$Yd=$_GET["ns"]!==""&&!$xf&&DB!="";if($Yd&&function_exists('Adminer\alter_table'))$ka[]='".lang(78)."";echo($ka?"

    ".lang(11)."

    \n";}}}function +syntaxHighlighting(array$T){echo +script_src(preg_replace("~\\?.*~","",ME)."?file=jush.js&version=5.4.2",true);if(support("sql")){echo"\n";if($T){$Ve=array();foreach($T +as$R=>$U)$Ve[]=preg_quote($R,'/');echo"var jushLinks = { ".JUSH.":";json_row(js_escape(ME).(support("table")?"table":"select").'=$&','/\b('.implode('|',$Ve).')\b/g',false);if(support('routine')){foreach(routines()as$K)json_row(js_escape(ME).'function='.urlencode($K["SPECIFIC_NAME"]).'&name=$&','/\b'.preg_quote($K["ROUTINE_NAME"],'/').'(?=["`]?\()/g',false);}json_row('');echo"};\n";foreach(array("bac","bra","sqlite_quo","mssql_bra")as$X)echo"jushLinks.$X = jushLinks.".JUSH.";\n";if(isset($_GET["sql"])||isset($_GET["trigger"])||isset($_GET["check"])){$Ii=array_fill_keys(array_keys($T),array());foreach(driver()->allFields()as$R=>$o){foreach($o +as$n)$Ii[$R][]=$n["field"];}echo"addEventListener('DOMContentLoaded', () => { autocompleter = jush.autocompleteSql('".idf_escape("")."', ".json_encode($Ii)."); });\n";}}echo"\n";}echo +script("syntaxHighlighting('".preg_replace('~^(\d\.?\d).*~s','\1',connection()->server_info)."', '".connection()->flavor."');");}function +databasesPrint($xf){$j=adminer()->databases();if(DB&&$j&&!in_array(DB,$j))array_unshift($j,DB);echo"
    \n

    \n";hidden_fields_get();$Qb=script("mixin(qsl('select'), {onmousedown: dbMouseDown, onchange: dbChange});");echo"","\n";if(support("scheme")){if($xf!="db"&&DB!=""&&connection()->select_db(DB)){echo"
    ";if($_GET["ns"]!="")set_schema($_GET["ns"]);}}foreach(array("import","sql","schema","dump","privileges")as$X){if(isset($_GET[$X])){echo +input_hidden($X);break;}}echo"

    \n";}function +tablesPrint(array$T){echo"
      ".script("mixin(qs('#tables'), {onmouseover: menuOver, onmouseout: menuOut});");foreach($T +as$R=>$P){$R="$R";$B=adminer()->tableName($P);if($B!=""&&!$P["partition"])echo'
    • ".lang(81)." ",(support("table")||support("indexes")?'$B":"$B")."\n";}echo"
    \n";}function +showVariables(){return +show_variables();}function +showStatus(){return +show_status();}function +processList(){return +process_list();}function +killProcess($u){return +kill_process($u);}}class +Plugins{private +static$append=array('dumpFormat'=>true,'dumpOutput'=>true,'editRowPrint'=>true,'editFunctions'=>true,'config'=>true);var$plugins;var$error='';private$hooks=array();function +__construct($Qg){if($Qg===null){$Qg=array();$Ja="adminer-plugins";if(is_dir($Ja)){foreach(glob("$Ja/*.php")as$p)$this->includeOnce($p);}$Jd=" href='https://www.adminer.org/plugins/#use'".target_blank();if(file_exists("$Ja.php")){$Zd=$this->includeOnce("$Ja.php");if(is_array($Zd)){foreach($Zd +as$Pg)$Qg[get_class($Pg)]=$Pg;}else$this->error +.=lang(82,"$Ja.php",$Jd)."
    ";}foreach(get_declared_classes()as$fb){if(!$Qg[$fb]&&(preg_match('~^Adminer\w~i',$fb)||is_subclass_of($fb,'Adminer\Plugin'))){$sh=new +\ReflectionClass($fb);$zb=$sh->getConstructor();if($zb&&$zb->getNumberOfRequiredParameters())$this->error +.=lang(83,$Jd,"$fb","$Ja.php")."
    ";else$Qg[$fb]=new$fb;}}}$this->plugins=$Qg;$na=new +Adminer;$Qg[]=$na;$sh=new +\ReflectionObject($na);foreach($sh->getMethods()as$vf){foreach($Qg +as$Pg){$B=$vf->getName();if(method_exists($Pg,$B))$this->hooks[$B][]=$Pg;}}}function +includeOnce($p){return +include_once"./$p";}function +__call($B,array$_g){$wa=array();foreach($_g +as$y=>$X)$wa[]=&$_g[$y];$J=null;foreach($this->hooks[$B]as$Pg){$Y=call_user_func_array(array($Pg,$B),$wa);if($Y!==null){if(!self::$append[$B])return$Y;$J=$Y+(array)$J;}}return$J;}}abstract +class +Plugin{protected$translations=array();function +description(){return$this->lang('');}function +screenshot(){return"";}protected +function +lang($v,$Of=null){$wa=func_get_args();$wa[0]=idx($this->translations[LANG],$v)?:$v;return +call_user_func_array('Adminer\lang_format',$wa);}}Adminer::$instance=(function_exists('adminer_object')?adminer_object():(is_dir("adminer-plugins")||file_exists("adminer-plugins.php")?new +Plugins(null):new +Adminer));SqlDriver::$drivers=array("server"=>"MySQL / MariaDB")+SqlDriver::$drivers;if(!defined('Adminer\DRIVER')){define('Adminer\DRIVER',"server");if(extension_loaded("mysqli")&&$_GET["ext"]!="pdo"){class +Db +extends +\MySQLi{static$instance;var$extension="MySQLi",$flavor='';function +__construct(){parent::init();}function +attach($N,$V,$F){mysqli_report(MYSQLI_REPORT_OFF);list($Nd,$Rg)=host_port($N);$ri=adminer()->connectSsl();if($ri)$this->ssl_set($ri['key'],$ri['cert'],$ri['ca'],'','');$J=@$this->real_connect(($N!=""?$Nd:ini_get("mysqli.default_host")),($N.$V!=""?$V:ini_get("mysqli.default_user")),($N.$V.$F!=""?$F:ini_get("mysqli.default_pw")),null,(is_numeric($Rg)?intval($Rg):ini_get("mysqli.default_port")),(is_numeric($Rg)?null:$Rg),($ri?($ri['verify']!==false?2048:64):0));$this->options(MYSQLI_OPT_LOCAL_INFILE,0);return($J?'':$this->error);}function +set_charset($Xa){if(parent::set_charset($Xa))return +true;parent::set_charset('utf8');return$this->query("SET NAMES $Xa");}function +next_result(){return +self::more_results()&&parent::next_result();}function +quote($Q){return"'".$this->escape_string($Q)."'";}}}elseif(extension_loaded("mysql")&&!((ini_bool("sql.safe_mode")||ini_bool("mysql.allow_local_infile"))&&extension_loaded("pdo_mysql"))){class +Db +extends +SqlDb{private$link;function +attach($N,$V,$F){if(ini_bool("mysql.allow_local_infile"))return +lang(84,"'mysql.allow_local_infile'","MySQLi","PDO_MySQL");$this->link=@mysql_connect(($N!=""?$N:ini_get("mysql.default_host")),($N.$V!=""?$V:ini_get("mysql.default_user")),($N.$V.$F!=""?$F:ini_get("mysql.default_password")),true,131072);if(!$this->link)return +mysql_error();$this->server_info=mysql_get_server_info($this->link);return'';}function +set_charset($Xa){if(function_exists('mysql_set_charset')){if(mysql_set_charset($Xa,$this->link))return +true;mysql_set_charset('utf8',$this->link);}return$this->query("SET NAMES $Xa");}function +quote($Q){return"'".mysql_real_escape_string($Q,$this->link)."'";}function +select_db($Pb){return +mysql_select_db($Pb,$this->link);}function +query($H,$sj=false){$I=@($sj?mysql_unbuffered_query($H,$this->link):mysql_query($H,$this->link));$this->error="";if(!$I){$this->errno=mysql_errno($this->link);$this->error=mysql_error($this->link);return +false;}if($I===true){$this->affected_rows=mysql_affected_rows($this->link);$this->info=mysql_info($this->link);return +true;}return +new +Result($I);}}class +Result{var$num_rows;private$result;private$offset=0;function +__construct($I){$this->result=$I;$this->num_rows=mysql_num_rows($I);}function +fetch_assoc(){return +mysql_fetch_assoc($this->result);}function +fetch_row(){return +mysql_fetch_row($this->result);}function +fetch_field(){$J=mysql_fetch_field($this->result,$this->offset++);$J->orgtable=$J->table;$J->charsetnr=($J->blob?63:0);return$J;}function +__destruct(){mysql_free_result($this->result);}}}elseif(extension_loaded("pdo_mysql")){class +Db +extends +PdoDb{var$extension="PDO_MySQL";function +attach($N,$V,$F){$gg=array(\PDO::MYSQL_ATTR_LOCAL_INFILE=>false);$ri=adminer()->connectSsl();if($ri){if($ri['key'])$gg[\PDO::MYSQL_ATTR_SSL_KEY]=$ri['key'];if($ri['cert'])$gg[\PDO::MYSQL_ATTR_SSL_CERT]=$ri['cert'];if($ri['ca'])$gg[\PDO::MYSQL_ATTR_SSL_CA]=$ri['ca'];if(isset($ri['verify']))$gg[\PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT]=$ri['verify'];}list($Nd,$Rg)=host_port($N);return$this->dsn("mysql:charset=utf8;host=$Nd".($Rg?(is_numeric($Rg)?";port=":";unix_socket=").$Rg:""),$V,$F,$gg);}function +set_charset($Xa){return$this->query("SET NAMES $Xa");}function +select_db($Pb){return$this->query("USE ".idf_escape($Pb));}function +query($H,$sj=false){$this->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,!$sj);return +parent::query($H,$sj);}}}class +Driver +extends +SqlDriver{static$extensions=array("MySQLi","MySQL","PDO_MySQL");static$jush="sql";var$unsigned=array("unsigned","zerofill","unsigned zerofill");var$operators=array("=","<",">","<=",">=","!=","LIKE","LIKE %%","REGEXP","IN","FIND_IN_SET","IS NULL","NOT LIKE","NOT REGEXP","NOT IN","IS NOT NULL","SQL");var$functions=array("char_length","date","from_unixtime","lower","round","floor","ceil","sec_to_time","time_to_sec","upper");var$grouping=array("avg","count","count distinct","group_concat","max","min","sum");static +function +connect($N,$V,$F){$g=parent::connect($N,$V,$F);if(is_string($g)){if(function_exists('iconv')&&!is_utf8($g)&&strlen($Hh=iconv("windows-1250","utf-8",$g))>strlen($g))$g=$Hh;return$g;}$g->set_charset(charset($g));$g->query("SET sql_quote_show_create = 1, autocommit = 1");$g->flavor=(preg_match('~MariaDB~',$g->server_info)?'maria':'mysql');add_driver(DRIVER,($g->flavor=='maria'?"MariaDB":"MySQL"));return$g;}function +__construct(Db$g){parent::__construct($g);$this->types=array(lang(27)=>array("tinyint"=>3,"smallint"=>5,"mediumint"=>8,"int"=>10,"bigint"=>20,"decimal"=>66,"float"=>12,"double"=>21),lang(28)=>array("date"=>10,"datetime"=>19,"timestamp"=>19,"time"=>10,"year"=>4),lang(29)=>array("char"=>255,"varchar"=>65535,"tinytext"=>255,"text"=>65535,"mediumtext"=>16777215,"longtext"=>4294967295),lang(85)=>array("enum"=>65535,"set"=>64),lang(30)=>array("bit"=>20,"binary"=>255,"varbinary"=>65535,"tinyblob"=>255,"blob"=>65535,"mediumblob"=>16777215,"longblob"=>4294967295),lang(32)=>array("geometry"=>0,"point"=>0,"linestring"=>0,"polygon"=>0,"multipoint"=>0,"multilinestring"=>0,"multipolygon"=>0,"geometrycollection"=>0),);$this->insertFunctions=array("char"=>"md5/sha1/password/encrypt/uuid","binary"=>"md5/sha1","date|time"=>"now",);$this->editFunctions=array(number_type()=>"+/-","date"=>"+ interval/- interval","time"=>"addtime/subtime","char|text"=>"concat",);if(min_version('5.7.8',10.2,$g))$this->types[lang(29)]["json"]=4294967295;if(min_version('',10.7,$g)){$this->types[lang(29)]["uuid"]=128;$this->insertFunctions['uuid']='uuid';}if(min_version(9,'',$g)){$this->types[lang(27)]["vector"]=16383;$this->insertFunctions['vector']='string_to_vector';}if(min_version(5.1,'',$g))$this->partitionBy=array("HASH","LINEAR HASH","KEY","LINEAR KEY","RANGE","LIST");if(min_version(5.7,10.2,$g))$this->generated=array("STORED","VIRTUAL");}function +unconvertFunction(array$n){return(preg_match("~binary~",$n["type"])?"UNHEX":($n["type"]=="bit"?doc_link(array('sql'=>'bit-value-literals.html'),"b''"):(preg_match("~geometry|point|linestring|polygon~",$n["type"])?"GeomFromText":"")));}function +insert($R,array$O){return($O?parent::insert($R,$O):queries("INSERT INTO ".table($R)." ()\nVALUES ()"));}function +insertUpdate($R,array$L,array$G){$e=array_keys(reset($L));$Xg="INSERT INTO ".table($R)." (".implode(", ",$e).") VALUES\n";$Nj=array();foreach($e +as$y)$Nj[$y]="$y = VALUES($y)";$yi="\nON DUPLICATE KEY UPDATE ".implode(", ",$Nj);$Nj=array();$Re=0;foreach($L +as$O){$Y="(".implode(", ",$O).")";if($Nj&&(strlen($Xg)+$Re+strlen($Y)+strlen($yi)>1e6)){if(!queries($Xg.implode(",\n",$Nj).$yi))return +false;$Nj=array();$Re=0;}$Nj[]=$Y;$Re+=strlen($Y)+2;}return +queries($Xg.implode(",\n",$Nj).$yi);}function +slowQuery($H,$Ui){if(min_version('5.7.8','10.1.2')){if($this->conn->flavor=='maria')return"SET STATEMENT max_statement_time=$Ui FOR $H";elseif(preg_match('~^(SELECT\b)(.+)~is',$H,$A))return"$A[1] /*+ MAX_EXECUTION_TIME(".($Ui*1000).") */ $A[2]";}}function +convertSearch($v,array$X,array$n){return(preg_match('~char|text|enum|set~',$n["type"])&&!preg_match("~^utf8~",$n["collation"])&&preg_match('~[\x80-\xFF]~',$X['val'])?"CONVERT($v USING ".charset($this->conn).")":$v);}function +warnings(){$I=$this->conn->query("SHOW WARNINGS");if($I&&$I->num_rows){ob_start();print_select_result($I);return +ob_get_clean();}}function +tableHelp($B,$ze=false){$Ze=($this->conn->flavor=='maria');if(information_schema(DB))return +strtolower("information-schema-".($Ze?"$B-table/":str_replace("_","-",$B)."-table.html"));if(DB=="mysql")return($Ze?"mysql$B-table/":"system-schema.html");}function +partitionsInfo($R){$qd="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($R);$I=$this->conn->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $qd ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");$J=array();list($J["partition_by"],$J["partition"],$J["partitions"])=$I->fetch_row();$Hg=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $qd AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$J["partition_names"]=array_keys($Hg);$J["partition_values"]=array_values($Hg);return$J;}function +hasCStyleEscapes(){static$Sa;if($Sa===null){$pi=get_val("SHOW VARIABLES LIKE 'sql_mode'",1,$this->conn);$Sa=(strpos($pi,'NO_BACKSLASH_ESCAPES')===false);}return$Sa;}function +engines(){$J=array();foreach(get_rows("SHOW ENGINES")as$K){if(preg_match("~YES|DEFAULT~",$K["Support"]))$J[]=$K["Engine"];}return$J;}function +indexAlgorithms(array$Bi){return(preg_match('~^(MEMORY|NDB)$~',$Bi["Engine"])?array("HASH","BTREE"):array());}}function +idf_escape($v){return"`".str_replace("`","``",$v)."`";}function +table($v){return +idf_escape($v);}function +get_databases($id){$J=get_session("dbs");if($J===null){$H="SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME";$J=($id?slow_query($H):get_vals($H));restart_session();set_session("dbs",$J);stop_session();}return$J;}function +limit($H,$Z,$z,$C=0,$Vh=" "){return" $H$Z".($z?$Vh."LIMIT $z".($C?" OFFSET $C":""):"");}function +limit1($R,$H,$Z,$Vh="\n"){return +limit($H,$Z,1,0,$Vh);}function +db_collation($k,array$lb){$J=null;$i=get_val("SHOW CREATE DATABASE ".idf_escape($k),1);if(preg_match('~ COLLATE ([^ ]+)~',$i,$A))$J=$A[1];elseif(preg_match('~ CHARACTER SET ([^ ]+)~',$i,$A))$J=$lb[$A[1]][-1];return$J;}function +logged_user(){return +get_val("SELECT USER()");}function +tables_list(){return +get_key_vals("SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ORDER BY TABLE_NAME");}function +count_tables(array$j){$J=array();foreach($j +as$k)$J[$k]=count(get_vals("SHOW TABLES IN ".idf_escape($k)));return$J;}function +table_status($B="",$Uc=false){$J=array();foreach(get_rows($Uc?"SELECT TABLE_NAME AS Name, ENGINE AS Engine, TABLE_COMMENT AS Comment FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() ".($B!=""?"AND TABLE_NAME = ".q($B):"ORDER BY Name"):"SHOW TABLE STATUS".($B!=""?" LIKE ".q(addcslashes($B,"%_\\")):""))as$K){if($K["Engine"]=="InnoDB")$K["Comment"]=preg_replace('~(?:(.+); )?InnoDB free: .*~','\1',$K["Comment"]);if(!isset($K["Engine"]))$K["Comment"]="";if($B!="")$K["Name"]=$B;$J[$K["Name"]]=$K;}return$J;}function +is_view(array$S){return$S["Engine"]===null;}function +fk_support(array$S){return +preg_match('~InnoDB|IBMDB2I'.(min_version(5.6)?'|NDB':'').'~i',$S["Engine"]);}function +fields($R){$Ze=(connection()->flavor=='maria');$J=array();foreach(get_rows("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ".q($R)." ORDER BY ORDINAL_POSITION")as$K){$n=$K["COLUMN_NAME"];$U=$K["COLUMN_TYPE"];$ud=$K["GENERATION_EXPRESSION"];$Rc=$K["EXTRA"];preg_match('~^(VIRTUAL|PERSISTENT|STORED)~',$Rc,$td);preg_match('~^([^( ]+)(?:\((.+)\))?( unsigned)?( zerofill)?$~',$U,$cf);$l=$K["COLUMN_DEFAULT"];if($l!=""){$ye=preg_match('~text|json~',$cf[1]);if(!$Ze&&$ye)$l=preg_replace("~^(_\w+)?('.*')$~",'\2',stripslashes($l));if($Ze||$ye){$l=($l=="NULL"?null:preg_replace_callback("~^'(.*)'$~",function($A){return +stripslashes(str_replace("''","'",$A[1]));},$l));}if(!$Ze&&preg_match('~binary~',$cf[1])&&preg_match('~^0x(\w*)$~',$l,$A))$l=pack("H*",$A[1]);}$J[$n]=array("field"=>$n,"full_type"=>$U,"type"=>$cf[1],"length"=>$cf[2],"unsigned"=>ltrim($cf[3].$cf[4]),"default"=>($td?($Ze?$ud:stripslashes($ud)):$l),"null"=>($K["IS_NULLABLE"]=="YES"),"auto_increment"=>($Rc=="auto_increment"),"on_update"=>(preg_match('~\bon update (\w+)~i',$Rc,$A)?$A[1]:""),"collation"=>$K["COLLATION_NAME"],"privileges"=>array_flip(explode(",","$K[PRIVILEGES],where,order")),"comment"=>$K["COLUMN_COMMENT"],"primary"=>($K["COLUMN_KEY"]=="PRI"),"generated"=>($td[1]=="PERSISTENT"?"STORED":$td[1]),);}return$J;}function +indexes($R,$h=null){$J=array();foreach(get_rows("SHOW INDEX FROM ".table($R),$h)as$K){$B=$K["Key_name"];$J[$B]["type"]=($B=="PRIMARY"?"PRIMARY":($K["Index_type"]=="FULLTEXT"?"FULLTEXT":($K["Non_unique"]?($K["Index_type"]=="SPATIAL"?"SPATIAL":"INDEX"):"UNIQUE")));$J[$B]["columns"][]=$K["Column_name"];$J[$B]["lengths"][]=($K["Index_type"]=="SPATIAL"?null:$K["Sub_part"]);$J[$B]["descs"][]=null;$J[$B]["algorithm"]=$K["Index_type"];}return$J;}function +foreign_keys($R){static$Lg='(?:`(?:[^`]|``)+`|"(?:[^"]|"")+")';$J=array();$Fb=get_val("SHOW CREATE TABLE ".table($R),1);if($Fb){preg_match_all("~CONSTRAINT ($Lg) FOREIGN KEY ?\\(((?:$Lg,? ?)+)\\) REFERENCES ($Lg)(?:\\.($Lg))? \\(((?:$Lg,? ?)+)\\)(?: ON DELETE (".driver()->onActions."))?(?: ON UPDATE (".driver()->onActions."))?~",$Fb,$df,PREG_SET_ORDER);foreach($df +as$A){preg_match_all("~$Lg~",$A[2],$ji);preg_match_all("~$Lg~",$A[5],$Mi);$J[idf_unescape($A[1])]=array("db"=>idf_unescape($A[4]!=""?$A[3]:$A[4]),"table"=>idf_unescape($A[4]!=""?$A[4]:$A[3]),"source"=>array_map('Adminer\idf_unescape',$ji[0]),"target"=>array_map('Adminer\idf_unescape',$Mi[0]),"on_delete"=>($A[6]?:"RESTRICT"),"on_update"=>($A[7]?:"RESTRICT"),);}}return$J;}function +view($B){return +array("select"=>preg_replace('~^(?:[^`]|`[^`]*`)*\s+AS\s+~isU','',get_val("SHOW CREATE VIEW ".table($B),1)));}function +collations(){$J=array();foreach(get_rows("SHOW COLLATION")as$K){if($K["Default"])$J[$K["Charset"]][-1]=$K["Collation"];else$J[$K["Charset"]][]=$K["Collation"];}ksort($J);foreach($J +as$y=>$X)sort($J[$y]);return$J;}function +information_schema($k){return($k=="information_schema")||(min_version(5.5)&&$k=="performance_schema");}function +error(){return +h(preg_replace('~^You have an error.*syntax to use~U',"Syntax error",connection()->error));}function +create_database($k,$c){return +queries("CREATE DATABASE ".idf_escape($k).($c?" COLLATE ".q($c):""));}function +drop_databases(array$j){$J=apply_queries("DROP DATABASE",$j,'Adminer\idf_escape');restart_session();set_session("dbs",null);return$J;}function +rename_database($B,$c){$J=false;if(create_database($B,$c)){$T=array();$Sj=array();foreach(tables_list()as$R=>$U){if($U=='VIEW')$Sj[]=$R;else$T[]=$R;}$J=(!$T&&!$Sj)||move_tables($T,$Sj,$B);drop_databases($J?array(DB):array());}return$J;}function +auto_increment(){$Ca=" PRIMARY KEY";if($_GET["create"]!=""&&$_POST["auto_increment_col"]){foreach(indexes($_GET["create"])as$w){if(in_array($_POST["fields"][$_POST["auto_increment_col"]]["orig"],$w["columns"],true)){$Ca="";break;}if($w["type"]=="PRIMARY")$Ca=" UNIQUE";}}return" AUTO_INCREMENT$Ca";}function +alter_table($R,$B,array$o,array$kd,$qb,$yc,$c,$Ba,$E){$b=array();foreach($o +as$n){if($n[1]){$l=$n[1][3];if(preg_match('~ GENERATED~',$l)){$n[1][3]=(connection()->flavor=='maria'?"":$n[1][2]);$n[1][2]=$l;}$b[]=($R!=""?($n[0]!=""?"CHANGE ".idf_escape($n[0]):"ADD"):" ")." ".implode($n[1]).($R!=""?$n[2]:"");}else$b[]="DROP ".idf_escape($n[0]);}$b=array_merge($b,$kd);$P=($qb!==null?" COMMENT=".q($qb):"").($yc?" ENGINE=".q($yc):"").($c?" COLLATE ".q($c):"").($Ba!=""?" AUTO_INCREMENT=$Ba":"");if($E){$Hg=array();if($E["partition_by"]=='RANGE'||$E["partition_by"]=='LIST'){foreach($E["partition_names"]as$y=>$X){$Y=$E["partition_values"][$y];$Hg[]="\n PARTITION ".idf_escape($X)." VALUES ".($E["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$P +.="\nPARTITION BY $E[partition_by]($E[partition])";if($Hg)$P +.=" (".implode(",",$Hg)."\n)";elseif($E["partitions"])$P +.=" PARTITIONS ".(+$E["partitions"]);}elseif($E===null)$P +.="\nREMOVE PARTITIONING";if($R=="")return +queries("CREATE TABLE ".table($B)." (\n".implode(",\n",$b)."\n)$P");if($R!=$B)$b[]="RENAME TO ".table($B);if($P)$b[]=ltrim($P);return($b?queries("ALTER TABLE ".table($R)."\n".implode(",\n",$b)):true);}function +alter_indexes($R,$b){$Wa=array();foreach($b +as$X)$Wa[]=($X[2]=="DROP"?"\nDROP INDEX ".idf_escape($X[1]):"\nADD $X[0] ".($X[0]=="PRIMARY"?"KEY ":"").($X[1]!=""?idf_escape($X[1])." ":"")."(".implode(", ",$X[2]).")");return +queries("ALTER TABLE ".table($R).implode(",",$Wa));}function +truncate_tables(array$T){return +apply_queries("TRUNCATE TABLE",$T);}function +drop_views(array$Sj){return +queries("DROP VIEW ".implode(", ",array_map('Adminer\table',$Sj)));}function +drop_tables(array$T){return +queries("DROP TABLE ".implode(", ",array_map('Adminer\table',$T)));}function +move_tables(array$T,array$Sj,$Mi){$wh=array();foreach($T +as$R)$wh[]=table($R)." TO ".idf_escape($Mi).".".table($R);if(!$wh||queries("RENAME TABLE ".implode(", ",$wh))){$Yb=array();foreach($Sj +as$R)$Yb[table($R)]=view($R);connection()->select_db($Mi);$k=idf_escape(DB);foreach($Yb +as$B=>$Rj){if(!queries("CREATE VIEW $B AS ".str_replace(" $k."," ",$Rj["select"]))||!queries("DROP VIEW $k.$B"))return +false;}return +true;}return +false;}function +copy_tables(array$T,array$Sj,$Mi){queries("SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'");foreach($T +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));if(($_POST["overwrite"]&&!queries("\nDROP TABLE IF EXISTS $B"))||!queries("CREATE TABLE $B LIKE ".table($R))||!queries("INSERT INTO $B SELECT * FROM ".table($R)))return +false;foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K){$lj=$K["Trigger"];if(!queries("CREATE TRIGGER ".($Mi==DB?idf_escape("copy_$lj"):idf_escape($Mi).".".idf_escape($lj))." $K[Timing] $K[Event] ON $B FOR EACH ROW\n$K[Statement];"))return +false;}}foreach($Sj +as$R){$B=($Mi==DB?table("copy_$R"):idf_escape($Mi).".".table($R));$Rj=view($R);if(($_POST["overwrite"]&&!queries("DROP VIEW IF EXISTS $B"))||!queries("CREATE VIEW $B AS $Rj[select]"))return +false;}return +true;}function +trigger($B,$R){if($B=="")return +array();$L=get_rows("SHOW TRIGGERS WHERE `Trigger` = ".q($B));return +reset($L);}function +triggers($R){$J=array();foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")))as$K)$J[$K["Trigger"]]=array($K["Timing"],$K["Event"]);return$J;}function +trigger_options(){return +array("Timing"=>array("BEFORE","AFTER"),"Event"=>array("INSERT","UPDATE","DELETE"),"Type"=>array("FOR EACH ROW"),);}function +routine($B,$U){$o=get_rows("SELECT + PARAMETER_NAME field, + DATA_TYPE type, + CHARACTER_MAXIMUM_LENGTH length, + REGEXP_REPLACE(DTD_IDENTIFIER, '^[^ ]+ ', '') `unsigned`, + 1 `null`, + DTD_IDENTIFIER full_type, + PARAMETER_MODE `inout`, + CHARACTER_SET_NAME collation +FROM information_schema.PARAMETERS +WHERE SPECIFIC_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND SPECIFIC_NAME = ".q($B)." +ORDER BY ORDINAL_POSITION");$J=connection()->query("SELECT ROUTINE_COMMENT comment, ROUTINE_DEFINITION definition, 'SQL' language +FROM information_schema.ROUTINES +WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_TYPE = '$U' AND ROUTINE_NAME = ".q($B))->fetch_assoc();if($o&&$o[0]['field']=='')$J['returns']=array_shift($o);$J['fields']=$o;return$J;}function +routines(){return +get_rows("SELECT SPECIFIC_NAME, ROUTINE_NAME, ROUTINE_TYPE, DTD_IDENTIFIER FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE()");}function +routine_languages(){return +array();}function +routine_id($B,array$K){return +idf_escape($B);}function +last_id($I){return +get_val("SELECT LAST_INSERT_ID()");}function +explain(Db$g,$H){return$g->query("EXPLAIN ".(min_version(5.1)&&!min_version(5.7)?"PARTITIONS ":"").$H);}function +found_rows(array$S,array$Z){return($Z||$S["Engine"]!="InnoDB"?null:$S["Rows"]);}function +create_sql($R,$Ba,$wi){$J=get_val("SHOW CREATE TABLE ".table($R),1);if(!$Ba)$J=preg_replace('~ AUTO_INCREMENT=\d+~','',$J);return$J;}function +truncate_sql($R){return"TRUNCATE ".table($R);}function +use_sql($Pb,$wi=""){$B=idf_escape($Pb);$J="";if(preg_match('~CREATE~',$wi)&&($i=get_val("SHOW CREATE DATABASE $B",1))){set_utf8mb4($i);if($wi=="DROP+CREATE")$J="DROP DATABASE IF EXISTS $B;\n";$J +.="$i;\n";}return$J."USE $B";}function +trigger_sql($R){$J="";foreach(get_rows("SHOW TRIGGERS LIKE ".q(addcslashes($R,"%_\\")),null,"-- ")as$K)$J +.="\nCREATE TRIGGER ".idf_escape($K["Trigger"])." $K[Timing] $K[Event] ON ".table($K["Table"])." FOR EACH ROW\n$K[Statement];;\n";return$J;}function +show_variables(){return +get_rows("SHOW VARIABLES");}function +show_status(){return +get_rows("SHOW STATUS");}function +process_list(){return +get_rows("SHOW FULL PROCESSLIST");}function +convert_field(array$n){if(preg_match("~binary~",$n["type"]))return"HEX(".idf_escape($n["field"]).")";if($n["type"]=="bit")return"BIN(".idf_escape($n["field"])." + 0)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"]))return(min_version(8)?"ST_":"")."AsWKT(".idf_escape($n["field"]).")";}function +unconvert_field(array$n,$J){if(preg_match("~binary~",$n["type"]))$J="UNHEX($J)";if($n["type"]=="bit")$J="CONVERT(b$J, UNSIGNED)";if(preg_match("~geometry|point|linestring|polygon~",$n["type"])){$Xg=(min_version(8)?"ST_":"");$J=$Xg."GeomFromText($J, $Xg"."SRID($n[field]))";}return$J;}function +support($Vc){return +preg_match('~^(comment|columns|copy|database|drop_col|dump|indexes|kill|privileges|move_col|procedure|processlist|routine|sql|status|table|trigger|variables|view'.(min_version(5.1)?'|event':'').(min_version(8)?'|descidx':'').(min_version('8.0.16','10.2.1')?'|check':'').')$~',$Vc);}function +kill_process($u){return +queries("KILL ".number($u));}function +connection_id(){return"SELECT CONNECTION_ID()";}function +max_connections(){return +get_val("SELECT @@max_connections");}function +types(){return +array();}function +type_values($u){return"";}function +schemas(){return +array();}function +get_schema(){return"";}function +set_schema($Jh,$h=null){return +true;}}define('Adminer\JUSH',Driver::$jush);define('Adminer\SERVER',"".$_GET[DRIVER]);define('Adminer\DB',"$_GET[db]");define('Adminer\ME',preg_replace('~\?.*~','',relative_uri()).'?'.(sid()?SID.'&':'').(SERVER!==null?DRIVER."=".urlencode(SERVER).'&':'').($_GET["ext"]?"ext=".urlencode($_GET["ext"]).'&':'').(isset($_GET["username"])?"username=".urlencode($_GET["username"]).'&':'').(DB!=""?'db='.urlencode(DB).'&'.(isset($_GET["ns"])?"ns=".urlencode($_GET["ns"])."&":""):''));function +page_header($Wi,$m="",$Oa=array(),$Xi=""){page_headers();if(is_ajax()&&$m){page_messages($m);exit;}if(!ob_get_level())ob_start('ob_gzhandler',4096);$Yi=$Wi.($Xi!=""?": $Xi":"");$Zi=strip_tags($Yi.(SERVER!=""&&SERVER!="localhost"?h(" - ".SERVER):"")." - ".adminer()->name());echo' + -',$pg,' - -',script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=4.8.1");if($b->head()){echo' - -';foreach($b->css()as$eb){echo' -';}}echo' - -';$o=get_temp_dir()."/adminer.version";if(!$_COOKIE["adminer_version"]&&function_exists('openssl_verify')&&file_exists($o)&&filemtime($o)+86400>time()){$Xg=unserialize(file_get_contents($o));$Ve="-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwqWOVuF5uw7/+Z70djoK -RlHIZFZPO0uYRezq90+7Amk+FDNd7KkL5eDve+vHRJBLAszF/7XKXe11xwliIsFs -DFWQlsABVZB3oisKCBEuI71J4kPH8dKGEWR9jDHFw3cWmoH3PmqImX6FISWbG3B8 -h7FIx3jEaw5ckVPVTeo5JRm/1DZzJxjyDenXvBQ/6o9DgZKeNDgxwKzH+sw9/YCO -jHnq1cFpOIISzARlrHMa/43YfeNRAm/tsBXjSxembBPo7aQZLAWHmaj5+K19H10B -nCpz9Y++cipkVEiKRGih4ZEvjoFysEOdRLj6WiD/uUNky4xGeA6LaJqh5XpkFkcQ -fQIDAQAB ------END PUBLIC KEY----- -";if(openssl_verify($Xg["version"],base64_decode($Xg["signature"]),$Ve)==1)$_COOKIE["adminer_version"]=$Xg["version"];}echo' -mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick',(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '$da', '".js_escape(ME)."', '".get_token()."')");?>}); -document.body.className = document.body.className.replace(/ nojs/, ' js'); -var offlineMessage = ' - - -',script("mixin(qs('#help'), {onmouseover: function () { helpOpen = 1; }, onmouseout: helpMouseout});"),' -
    -';if($Ba!==null){$A=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $og

    \n","\n";restart_session();page_messages($l);$i=&get_session("dbs");if(DB!=""&&$i&&!in_array(DB,$i,true))$i=null;stop_session();define("PAGE_HEADER",1);}function -page_headers(){global$b;header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: SAMEORIGIN");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach($b->csp()as$db){$Dc=array();foreach($db -as$z=>$X)$Dc[]="$z $X";header("Content-Security-Policy: ".implode("; ",$Dc));}$b->headers();}function + +',$Zi,' + +';$Jb=adminer()->css();if(is_int(key($Jb)))$Jb=array_fill_keys($Jb,'light');$Fd=in_array('light',$Jb)||in_array('',$Jb);$Dd=in_array('dark',$Jb)||in_array('',$Jb);$Mb=($Fd?($Dd?null:false):($Dd?:null));$nf=" media='(prefers-color-scheme: dark)'";if($Mb!==false)echo"\n";echo"\n",script_src(preg_replace("~\\?.*~","",ME)."?file=functions.js&version=5.4.2");if(adminer()->head($Mb))echo"\n","\n";foreach($Jb +as$Dj=>$yf){$_a=($yf=='dark'&&!$Mb?$nf:($yf=='light'&&$Dd?" media='(prefers-color-scheme: light)'":""));echo"\n";}echo"\n\n";$p=get_temp_dir()."/adminer.version";echo +script("mixin(document.body, {onkeydown: bodyKeydown, onclick: bodyClick".(isset($_COOKIE["adminer_version"])?"":", onload: partial(verifyVersion, '".VERSION."')")."}); +document.body.classList.replace('nojs', 'js'); +const offlineMessage = '".js_escape(lang(87))."'; +const thousandsSeparator = '".js_escape(lang(4))."';"),"\n",script("mixin(qs('#help'), {onmouseover: () => { helpOpen = 1; }, onmouseout: helpMouseout});"),"
    \n","".icon("move","","menu","")."".script("qs('#menuopen').onclick = event => { qs('#foot').classList.toggle('foot'); event.stopPropagation(); }");if($Oa!==null){$_=substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1);echo'

    $Yi

    \n","\n";restart_session();page_messages($m);$j=&get_session("dbs");if(DB!=""&&$j&&!in_array(DB,$j,true))$j=null;stop_session();define('Adminer\PAGE_HEADER',1);}function +page_headers(){header("Content-Type: text/html; charset=utf-8");header("Cache-Control: no-cache");header("X-Frame-Options: deny");header("X-XSS-Protection: 0");header("X-Content-Type-Options: nosniff");header("Referrer-Policy: origin-when-cross-origin");foreach(adminer()->csp(csp())as$Ib){$Hd=array();foreach($Ib +as$y=>$X)$Hd[]="$y $X";header("Content-Security-Policy: ".implode("; ",$Hd));}adminer()->headers();}function csp(){return -array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self'","frame-src"=>"https://www.adminer.org","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function -get_nonce(){static$Nd;if(!$Nd)$Nd=base64_encode(rand_string());return$Nd;}function -page_messages($l){$Lg=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$Ed=$_SESSION["messages"][$Lg];if($Ed){echo"
    ".implode("
    \n
    ",$Ed)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Lg]);}if($l)echo"
    $l
    \n";}function -page_footer($Hd=""){global$b,$U;echo'
    - -';if($Hd!="auth"){echo'
    +array(array("script-src"=>"'self' 'unsafe-inline' 'nonce-".get_nonce()."' 'strict-dynamic'","connect-src"=>"'self' https://www.adminer.org","frame-src"=>"'none'","object-src"=>"'none'","base-uri"=>"'none'","form-action"=>"'self'",),);}function +get_nonce(){static$Kf;if(!$Kf)$Kf=base64_encode(rand_string());return$Kf;}function +page_messages($m){$Cj=preg_replace('~^[^?]*~','',$_SERVER["REQUEST_URI"]);$uf=idx($_SESSION["messages"],$Cj);if($uf){echo"
    ".implode("
    \n
    ",$uf)."
    ".script("messagesPrint();");unset($_SESSION["messages"][$Cj]);}if($m)echo"
    $m
    \n";if(adminer()->error)echo"
    ".adminer()->error."
    \n";}function +page_footer($xf=""){echo"
    \n\n\n\n",script("setupSubmitHighlight(document);");}function +int32($Cf){while($Cf>=2147483648)$Cf-=4294967296;while($Cf<=-2147483649)$Cf+=4294967296;return(int)$Cf;}function +long2str(array$W,$Uj){$Hh='';foreach($W +as$X)$Hh +.=pack('V',$X);if($Uj)return +substr($Hh,0,end($W));return$Hh;}function +str2long($Hh,$Uj){$W=array_values(unpack('V*',str_pad($Hh,4*ceil(strlen($Hh)/4),"\0")));if($Uj)$W[]=strlen($Hh);return$W;}function +xxtea_mx($bk,$ak,$zi,$Ce){return +int32((($bk>>5&0x7FFFFFF)^$ak<<2)+(($ak>>3&0x1FFFFFFF)^$bk<<4))^int32(($zi^$ak)+($Ce^$bk));}function +encrypt_string($ui,$y){if($ui=="")return"";$y=array_values(unpack("V*",pack("H*",md5($y))));$W=str2long($ui,true);$Cf=count($W)-1;$bk=$W[$Cf];$ak=$W[0];$hh=floor(6+52/($Cf+1));$zi=0;while($hh-->0){$zi=int32($zi+0x9E3779B9);$pc=$zi>>2&3;for($xg=0;$xg<$Cf;$xg++){$ak=$W[$xg+1];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$xg]+$Bf);$W[$xg]=$bk;}$ak=$W[0];$Bf=xxtea_mx($bk,$ak,$zi,$y[$xg&3^$pc]);$bk=int32($W[$Cf]+$Bf);$W[$Cf]=$bk;}return long2str($W,false);}function -decrypt_string($Nf,$z){if($Nf=="")return"";if(!$z)return -false;$z=array_values(unpack("V*",pack("H*",md5($z))));$W=str2long($Nf,false);$E=count($W)-1;$ih=$W[$E];$hh=$W[0];$H=floor(6+52/($E+1));$Sf=int32($H*0x9E3779B9);while($Sf){$Fb=$Sf>>2&3;for($re=$E;$re>0;$re--){$ih=$W[$re-1];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[$re]-$Jd);$W[$re]=$hh;}$ih=$W[$E];$Jd=xxtea_mx($ih,$hh,$Sf,$z[$re&3^$Fb]);$hh=int32($W[0]-$Jd);$W[0]=$hh;$Sf=int32($Sf-0x9E3779B9);}return -long2str($W,true);}$f='';$Cc=$_SESSION["token"];if(!$Cc)$_SESSION["token"]=rand(1,1e6);$U=get_token();$De=array();if($_COOKIE["adminer_permanent"]){foreach(explode(" ",$_COOKIE["adminer_permanent"])as$X){list($z)=explode(":",$X);$De[$z]=$X;}}function -add_invalid_login(){global$b;$r=file_open_lock(get_temp_dir()."/adminer.invalid");if(!$r)return;$Uc=unserialize(stream_get_contents($r));$jg=time();if($Uc){foreach($Uc -as$Vc=>$X){if($X[0]<$jg)unset($Uc[$Vc]);}}$Tc=&$Uc[$b->bruteForceKey()];if(!$Tc)$Tc=array($jg+30*60,0);$Tc[1]++;file_write_unlock($r,serialize($Uc));}function -check_invalid_login(){global$b;$Uc=unserialize(@file_get_contents(get_temp_dir()."/adminer.invalid"));$Tc=($Uc?$Uc[$b->bruteForceKey()]:array());$Md=($Tc[1]>29?$Tc[0]-time():0);if($Md>0)auth_error(lang(array('Too many unsuccessful logins, try again in %d minute.','Too many unsuccessful logins, try again in %d minutes.'),ceil($Md/60)));}$sa=$_POST["auth"];if($sa){session_regenerate_id();$Wg=$sa["driver"];$O=$sa["server"];$Rg=$sa["username"];$_e=(string)$sa["password"];$j=$sa["db"];set_password($Wg,$O,$Rg,$_e);$_SESSION["db"][$Wg][$O][$Rg][$j]=true;if($sa["permanent"]){$z=base64_encode($Wg)."-".base64_encode($O)."-".base64_encode($Rg)."-".base64_encode($j);$Re=$b->permanentLogin(true);$De[$z]="$z:".base64_encode($Re?encrypt_string($_e,$Re):"");cookie("adminer_permanent",implode(" ",$De));}if(count($_POST)==1||DRIVER!=$Wg||SERVER!=$O||$_GET["username"]!==$Rg||DB!=$j)redirect(auth_url($Wg,$O,$Rg,$j));}elseif($_POST["logout"]&&(!$Cc||verify_token())){foreach(array("pwds","db","dbs","queries")as$z)set_session($z,null);unset_permanent();redirect(substr(preg_replace('~\b(username|db|ns)=[^&]*&~','',ME),0,-1),'Logout successful.'.' '.'Thanks for using Adminer, consider donating.');}elseif($De&&!$_SESSION["pwds"]){session_regenerate_id();$Re=$b->permanentLogin();foreach($De -as$z=>$X){list(,$Ia)=explode(":",$X);list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));set_password($Wg,$O,$Rg,decrypt_string(base64_decode($Ia),$Re));$_SESSION["db"][$Wg][$O][$Rg][$j]=true;}}function -unset_permanent(){global$De;foreach($De -as$z=>$X){list($Wg,$O,$Rg,$j)=array_map('base64_decode',explode("-",$z));if($Wg==DRIVER&&$O==SERVER&&$Rg==$_GET["username"]&&$j==DB)unset($De[$z]);}cookie("adminer_permanent",implode(" ",$De));}function -auth_error($l){global$b,$Cc;$_f=session_name();if(isset($_GET["username"])){header("HTTP/1.1 403 Forbidden");if(($_COOKIE[$_f]||$_GET[$_f])&&!$Cc)$l='Session expired, please login again.';else{restart_session();add_invalid_login();$_e=get_password();if($_e!==null){if($_e===false)$l.=($l?'
    ':'').sprintf('Master password expired. Implement %s method to make it permanent.',target_blank(),'permanentLogin()');set_password(DRIVER,SERVER,$_GET["username"],null);}unset_permanent();}}if(!$_COOKIE[$_f]&&$_GET[$_f]&&ini_bool("session.use_only_cookies"))$l='Session support must be enabled.';$ue=session_get_cookie_params();cookie("adminer_key",($_COOKIE["adminer_key"]?$_COOKIE["adminer_key"]:rand_string()),$ue["lifetime"]);page_header('Login',$l,null);echo"
    \n","
    ";if(hidden_fields($_POST,array("auth")))echo"

    ".'The action will be performed after successful login with the same credentials.'."\n";echo"

    \n";$b->loginForm();echo"
    \n";page_footer("auth");exit;}if(isset($_GET["username"])&&!class_exists("Min_DB")){unset($_SESSION["pwds"][DRIVER]);unset_permanent();page_header('No extension',sprintf('None of the supported PHP extensions (%s) are available.',implode(", ",$Le)),false);page_footer("auth");exit;}stop_session(true);if(isset($_GET["username"])&&is_string(get_password())){list($Hc,$He)=explode(":",SERVER,2);if(preg_match('~^\s*([-+]?\d+)~',$He,$C)&&($C[1]<1024||$C[1]>65535))auth_error('Connecting to privileged ports is not allowed.');check_invalid_login();$f=connect();$k=new -Min_Driver($f);}$rd=null;if(!is_object($f)||($rd=$b->login($_GET["username"],get_password()))!==true){$l=(is_string($f)?h($f):(is_string($rd)?$rd:'Invalid credentials.'));auth_error($l.(preg_match('~^ | $~',get_password())?'
    '.'There is a space in the input password which might be the cause.':''));}if($_POST["logout"]&&$Cc&&!verify_token()){page_header('Logout','Invalid CSRF token. Send the form again.');page_footer("db");exit;}if($sa&&$_POST["token"])$_POST["token"]=$U;$l='';if($_POST){if(!verify_token()){$Pc="max_input_vars";$_d=ini_get($Pc);if(extension_loaded("suhosin")){foreach(array("suhosin.request.max_vars","suhosin.post.max_vars")as$z){$X=ini_get($z);if($X&&(!$_d||$X<$_d)){$Pc=$z;$_d=$X;}}}$l=(!$_POST["token"]&&$_d?sprintf('Maximum number of allowed fields exceeded. Please increase %s.',"'$Pc'"):'Invalid CSRF token. Send the form again.'.' '.'If you did not send this request from Adminer then close this page.');}}elseif($_SERVER["REQUEST_METHOD"]=="POST"){$l=sprintf('Too big POST data. Reduce the data or increase the %s configuration directive.',"'post_max_size'");if(isset($_GET["sql"]))$l.=' '.'You can upload a big SQL file via FTP and import it from server.';}function -select($J,$g=null,$ie=array(),$_=0){global$y;$qd=array();$x=array();$e=array();$_a=array();$Cg=array();$K=array();odd('');for($u=0;(!$_||$u<$_)&&($L=$J->fetch_row());$u++){if(!$u){echo"
    \n","\n","";for($Zc=0;$Zcfetch_field();$F=$m->name;$he=$m->orgtable;$ge=$m->orgname;$K[$m->table]=$he;if($ie&&$y=="sql")$qd[$Zc]=($F=="table"?"table=":($F=="possible_keys"?"indexes=":null));elseif($he!=""){if(!isset($x[$he])){$x[$he]=array();foreach(indexes($he,$g)as$w){if($w["type"]=="PRIMARY"){$x[$he]=array_flip($w["columns"]);break;}}$e[$he]=$x[$he];}if(isset($e[$he][$ge])){unset($e[$he][$ge]);$x[$he][$ge]=$Zc;$qd[$Zc]=$he;}}if($m->charsetnr==63)$_a[$Zc]=true;$Cg[$Zc]=$m->type;echo"name!=$ge?" title='".h(($he!=""?"$he.":"").$ge)."'":"").">".h($F).($ie?'':"");}echo"\n";}echo"";foreach($L -as$z=>$X){$A="";if(isset($qd[$z])&&!$e[$qd[$z]]){if($ie&&$y=="sql"){$R=$L[array_search("table=",$qd)];$A=ME.$qd[$z].urlencode($ie[$R]!=""?$ie[$R]:$R);}else{$A=ME."edit=".urlencode($qd[$z]);foreach($x[$qd[$z]]as$Ma=>$Zc)$A.="&where".urlencode("[".bracket_escape($Ma)."]")."=".urlencode($L[$Zc]);}}elseif(is_url($X))$A=$X;if($X===null)$X="NULL";elseif($_a[$z]&&!is_utf8($X))$X="".lang(array('%d byte','%d bytes'),strlen($X))."";else{$X=h($X);if($Cg[$z]==254)$X="$X";}if($A)$X="$X";echo"
    $X";}}echo($u?"
    \n
    ":"

    ".'No rows.')."\n";return$K;}function -referencable_primary($vf){$K=array();foreach(table_status('',true)as$Wf=>$R){if($Wf!=$vf&&fk_support($R)){foreach(fields($Wf)as$m){if($m["primary"]){if($K[$Wf]){unset($K[$Wf]);break;}$K[$Wf]=$m;}}}}return$K;}function -adminer_settings(){parse_str($_COOKIE["adminer_settings"],$Bf);return$Bf;}function -adminer_setting($z){$Bf=adminer_settings();return$Bf[$z];}function -set_adminer_settings($Bf){return -cookie("adminer_settings",http_build_query($Bf+adminer_settings()));}function -textarea($F,$Y,$M=10,$Qa=80){global$y;echo"";}function -edit_type($z,$m,$Pa,$q=array(),$ec=array()){global$Of,$Cg,$Jg,$Wd;$V=$m["type"];echo'',"',($Jg?"':''),(isset($m['on_update'])?"':''),($q?" ":" ");}function -process_length($nd){global$Qb;return(preg_match("~^\\s*\\(?\\s*$Qb(?:\\s*,\\s*$Qb)*+\\s*\\)?\\s*\$~",$nd)&&preg_match_all("~$Qb~",$nd,$ud)?"(".implode(",",$ud[0]).")":preg_replace('~^[0-9].*~','(\0)',preg_replace('~[^-0-9,+()[\]]~','',$nd)));}function -process_type($m,$Na="COLLATE"){global$Jg;return" $m[type]".process_length($m["length"]).(preg_match(number_type(),$m["type"])&&in_array($m["unsigned"],$Jg)?" $m[unsigned]":"").(preg_match('~char|text|enum|set~',$m["type"])&&$m["collation"]?" $Na ".q($m["collation"]):"");}function -process_field($m,$Bg){return -array(idf_escape(trim($m["field"])),process_type($Bg),($m["null"]?" NULL":" NOT NULL"),default_value($m),(preg_match('~timestamp|datetime~',$m["type"])&&$m["on_update"]?" ON UPDATE $m[on_update]":""),(support("comment")&&$m["comment"]!=""?" COMMENT ".q($m["comment"]):""),($m["auto_increment"]?auto_increment():null),);}function -default_value($m){$ob=$m["default"];return($ob===null?"":" DEFAULT ".(preg_match('~char|binary|text|enum|set~',$m["type"])||preg_match('~^(?![a-z])~i',$ob)?q($ob):$ob));}function -type_class($V){foreach(array('char'=>'text','date'=>'time|year','binary'=>'blob','enum'=>'set',)as$z=>$X){if(preg_match("~$z|$X~",$V))return" class='$z'";}}function -edit_fields($n,$Pa,$V="TABLE",$q=array()){global$Qc;$n=array_values($n);$pb=(($_POST?$_POST["defaults"]:adminer_setting("defaults"))?"":" class='hidden'");$Ua=(($_POST?$_POST["comments"]:adminer_setting("comments"))?"":" class='hidden'");echo' -';if($V=="PROCEDURE"){echo'';}echo'',($V=="TABLE"?'Column name':'Parameter name'),'Type',script("qs('#enum-edit').onblur = editingLengthBlur;"),'Length -','Options';if($V=="TABLE"){echo'NULL -AI',doc_link(array('sqlite'=>"autoinc.html",)),'Default value -',(support("comment")?"".'Comment':"");}echo'',"".script("row_count = ".count($n).";"),' - -',script("mixin(qsl('tbody'), {onclick: editingClick, onkeydown: editingKeydown, oninput: editingInput});");foreach($n -as$u=>$m){$u++;$je=$m[($_POST?"orig":"field")];$wb=(isset($_POST["add"][$u-1])||(isset($m["field"])&&!$_POST["drop_col"][$u]))&&(support("drop_col")||$je=="");echo' -',($V=="PROCEDURE"?"".html_select("fields[$u][inout]",explode("|",$Qc),$m["inout"]):""),'';if($wb){echo'';}echo'';edit_type("fields[$u]",$m,$Pa,$q);if($V=="TABLE"){echo'',checkbox("fields[$u][null]",1,$m["null"],"","","block","label-null"),'',checkbox("fields[$u][has_default]",1,$m["has_default"],"","","","label-default"),'',(support("comment")?"":"");}echo"",(support("move_col")?" "." "." ":""),($je==""||support("drop_col")?"":"");}}function -process_fields(&$n){$Sd=0;if($_POST["up"]){$hd=0;foreach($n -as$z=>$m){if(key($_POST["up"])==$z){unset($n[$z]);array_splice($n,$hd,0,array($m));break;}if(isset($m["field"]))$hd=$Sd;$Sd++;}}elseif($_POST["down"]){$rc=false;foreach($n -as$z=>$m){if(isset($m["field"])&&$rc){unset($n[key($_POST["down"])]);array_splice($n,$Sd,0,array($rc));break;}if(key($_POST["down"])==$z)$rc=$m;$Sd++;}}elseif($_POST["add"]){$n=array_values($n);array_splice($n,key($_POST["add"]),0,array(array()));}elseif(!$_POST["drop_col"])return +select_input($_a,array$gg,$Y="",$ag="",$Og=""){$Li=($gg?"select":"input");return"<$Li$_a".($gg?">

    ".sprintf('%s version: %s through PHP extension %s',$zb[DRIVER],"".h($f->server_info)."","$f->extension")."\n","

    ".sprintf('Logged as: %s',"".h(logged_user())."")."\n";$i=$b->databases();if($i){$rf=support("scheme");$Pa=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$i=($_GET["dbsize"]?count_tables($i):array_flip($i));foreach($i -as$j=>$T){$mf=h(ME)."db=".urlencode($j);$v=h("Db-".$j);echo"".(support("database")?"
    ":"")."".'Database'." - ".'Refresh'.""."".'Collation'."".'Tables'."".'Size'." - ".'Compute'."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$j,in_array($j,(array)$_POST["db"]),"","","",$v):""),"".h($j)."";$Oa=h(db_collation($j,$Pa));echo"".(support("database")?"$Oa":$Oa),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($j):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),"\n","
    \n",script("tableCheck();");}}page_footer("db");}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?$f->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}connect_error();exit;}$Wd="RESTRICT|NO ACTION|CASCADE|SET NULL|SET DEFAULT";class -TmpFile{var$handler;var$size;function +normalize_enum(array$A){$X=$A[0];return"'".str_replace("'","''",addcslashes(stripcslashes(str_replace($X[0].$X[0],$X[0],substr($X,1,-1))),'\\'))."'";}function +grant($vd,array$eh,$e,$Xf){if(!$eh)return +true;if($eh==array("ALL PRIVILEGES","GRANT OPTION"))return($vd=="GRANT"?queries("$vd ALL PRIVILEGES$Xf WITH GRANT OPTION"):queries("$vd ALL PRIVILEGES$Xf")&&queries("$vd GRANT OPTION$Xf"));return +queries("$vd ".preg_replace('~(GRANT OPTION)\([^)]*\)~','\1',implode("$e, ",$eh).$e).$Xf);}function +drop_create($jc,$i,$lc,$Pi,$nc,$We,$tf,$rf,$sf,$Uf,$Gf){if($_POST["drop"])query_redirect($jc,$We,$tf);elseif($Uf=="")query_redirect($i,$We,$sf);elseif($Uf!=$Gf){$Gb=queries($i);queries_redirect($We,$rf,$Gb&&queries($jc));if($Gb)queries($lc);}else +queries_redirect($We,$rf,queries($Pi)&&queries($nc)&&queries($jc)&&queries($i));}function +create_trigger($Xf,array$K){$Vi=" $K[Timing] $K[Event]".(preg_match('~ OF~',$K["Event"])?" $K[Of]":"");return"CREATE TRIGGER ".idf_escape($K["Trigger"]).(JUSH=="mssql"?$Xf.$Vi:$Vi.$Xf).rtrim(" $K[Type]\n$K[Statement]",";").";";}function +create_routine($Dh,array$K){$O=array();$o=(array)$K["fields"];ksort($o);foreach($o +as$n){if($n["field"]!="")$O[]=(preg_match("~^(".driver()->inout.")\$~",$n["inout"])?"$n[inout] ":"").idf_escape($n["field"]).process_type($n,"CHARACTER SET");}$Xb=rtrim($K["definition"],";");return"CREATE $Dh ".idf_escape(trim($K["name"]))." (".implode(", ",$O).")".($Dh=="FUNCTION"?" RETURNS".process_type($K["returns"],"CHARACTER SET"):"").($K["language"]?" LANGUAGE $K[language]":"").(JUSH=="pgsql"?" AS ".q($Xb):"\n$Xb;");}function +remove_definer($H){return +preg_replace('~^([A-Z =]+) DEFINER=`'.preg_replace('~@(.*)~','`@`(%|\1)',logged_user()).'`~','\1',$H);}function +format_foreign_key(array$q){$k=$q["db"];$Lf=$q["ns"];return" FOREIGN KEY (".implode(", ",array_map('Adminer\idf_escape',$q["source"])).") REFERENCES ".($k!=""&&$k!=$_GET["db"]?idf_escape($k).".":"").($Lf!=""&&$Lf!=$_GET["ns"]?idf_escape($Lf).".":"").idf_escape($q["table"])." (".implode(", ",array_map('Adminer\idf_escape',$q["target"])).")".(preg_match("~^(".driver()->onActions.")\$~",$q["on_delete"])?" ON DELETE $q[on_delete]":"").(preg_match("~^(".driver()->onActions.")\$~",$q["on_update"])?" ON UPDATE $q[on_update]":"").($q["deferrable"]?" $q[deferrable]":"");}function +tar_file($p,$aj){$J=pack("a100a8a8a8a12a12",$p,644,0,0,decoct($aj->size),decoct(time()));$db=8*32;for($t=0;$tsend();echo +str_repeat("\0",511-($aj->size+511)%512);}function +doc_link(array$Kg,$Qi="?"){$Zh=connection()->server_info;$Qj=preg_replace('~^(\d\.?\d).*~s','\1',$Zh);$Ej=array('sql'=>"https://dev.mysql.com/doc/refman/$Qj/en/",'sqlite'=>"https://www.sqlite.org/",'pgsql'=>"https://www.postgresql.org/docs/".(connection()->flavor=='cockroach'?"current":$Qj)."/",'mssql'=>"https://learn.microsoft.com/en-us/sql/",'oracle'=>"https://www.oracle.com/pls/topic/lookup?ctx=db".preg_replace('~^.* (\d+)\.(\d+)\.\d+\.\d+\.\d+.*~s','\1\2',$Zh)."&id=",);if(connection()->flavor=='maria'){$Ej['sql']="https://mariadb.com/kb/en/";$Kg['sql']=(isset($Kg['mariadb'])?$Kg['mariadb']:str_replace(".html","/",$Kg['sql']));}return($Kg[JUSH]?"$Qi":"");}function +db_size($k){if(!connection()->select_db($k))return"?";$J=0;foreach(table_status()as$S)$J+=$S["Data_length"]+$S["Index_length"];return +format_number($J);}function +set_utf8mb4($i){static$O=false;if(!$O&&preg_match('~\butf8mb4~i',$i)){$O=true;echo"SET NAMES ".charset(connection()).";\n\n";}}if(isset($_GET["status"]))$_GET["variables"]=$_GET["status"];if(isset($_GET["import"]))$_GET["sql"]=$_GET["import"];if(!(DB!=""?connection()->select_db(DB):isset($_GET["sql"])||isset($_GET["dump"])||isset($_GET["database"])||isset($_GET["processlist"])||isset($_GET["privileges"])||isset($_GET["user"])||isset($_GET["variables"])||$_GET["script"]=="connect"||$_GET["script"]=="kill")){if(DB!=""||$_GET["refresh"]){restart_session();set_session("dbs",null);}if(DB!=""){header("HTTP/1.1 404 Not Found");page_header(lang(38).": ".h(DB),lang(118),true);}else{if($_POST["db"]&&!$m)queries_redirect(substr(ME,0,-1),lang(119),drop_databases($_POST["db"]));page_header(lang(120),$m,false);echo"

    ".lang(125,get_driver(DRIVER),"".h(connection()->server_info)."","".connection()->extension."")."\n","

    ".lang(126,"".h(logged_user())."")."\n";$j=adminer()->databases();if($j){$Lh=support("scheme");$lb=collations();echo"

    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),"".(support("database")?"\n";$j=($_GET["dbsize"]?count_tables($j):array_flip($j));foreach($j +as$k=>$T){$Ch=h(ME)."db=".urlencode($k);$u=h("Db-".$k);echo"".(support("database")?"
    ":"")."".lang(38).(get_session("dbs")!==null?" - ".lang(127)."":"")."".lang(128)."".lang(129)."".lang(130)." - ".lang(131)."".script("qsl('a').onclick = partial(ajaxSetHtml, '".js_escape(ME)."script=connect');","")."
    ".checkbox("db[]",$k,in_array($k,(array)$_POST["db"]),"","","",$u):""),"".h($k)."";$c=h(db_collation($k,$lb));echo"".(support("database")?"$c":$c),"".($_GET["dbsize"]?$T:"?")."","".($_GET["dbsize"]?db_size($k):"?"),"\n";}echo"
    \n",(support("database")?"\n":""),input_token(),"
    \n",script("tableCheck();");}if(!empty(adminer()->plugins)){echo"
    \n","

    ".lang(134)."

    \n
      \n";foreach(adminer()->plugins +as$Pg){$bc=(method_exists($Pg,'description')?$Pg->description():"");if(!$bc){$sh=new +\ReflectionObject($Pg);if(preg_match('~^/[\s*]+(.+)~',$sh->getDocComment(),$A))$bc=$A[1];}$Mh=(method_exists($Pg,'screenshot')?$Pg->screenshot():"");echo"
    • ".get_class($Pg)."".h($bc?": $bc":"").($Mh?" (".lang(135).")":"")."\n";}echo"
    \n";adminer()->pluginsLinks();echo"
    \n";}}page_footer("db");exit;}if(support("scheme")){if(DB!=""&&$_GET["ns"]!==""){if(!isset($_GET["ns"]))redirect(preg_replace('~ns=[^&]*&~','',ME)."ns=".get_schema());if(!set_schema($_GET["ns"])){header("HTTP/1.1 404 Not Found");page_header(lang(80).": ".h($_GET["ns"]),lang(136),true);page_footer("ns");exit;}}}adminer()->afterConnect();class +TmpFile{private$handler;var$size;function __construct(){$this->handler=tmpfile();}function -write($Za){$this->size+=strlen($Za);fwrite($this->handler,$Za);}function -send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}$Qb="'(?:''|[^'\\\\]|\\\\.)*'";$Qc="IN|OUT|INOUT";if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["download"])){$a=$_GET["download"];$n=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$N=array(idf_escape($_GET["field"]));$J=$k->select($a,$N,array(where($_GET,$n)),$N);$L=($J?$J->fetch_row():array());echo$k->value($L[0],$n[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$n=fields($a);if(!$n)$l=error();$S=table_status1($a,true);$F=$b->tableName($S);page_header(($n&&is_view($S)?$S['Engine']=='materialized view'?'Materialized view':'View':'Table').": ".($F!=""?$F:h($a)),$l);$b->selectLinks($S);$Ta=$S["Comment"];if($Ta!="")echo"

    ".'Comment'.": ".h($Ta)."\n";if($n)$b->tableStructurePrint($n);if(!is_view($S)){if(support("indexes")){echo"

    ".'Indexes'."

    \n";$x=indexes($a);if($x)$b->tableIndexesPrint($x);echo'

    ".'Foreign keys'."

    \n";$q=foreign_keys($a);if($q){echo"\n","\n";foreach($q -as$F=>$p){echo"","
    ".'Source'."".'Target'."".'ON DELETE'."".'ON UPDATE'."
    ".implode(", ",array_map('h',$p["source"]))."","".($p["db"]!=""?"".h($p["db"]).".":"").($p["ns"]!=""?"".h($p["ns"]).".":"").h($p["table"])."","(".implode(", ",array_map('h',$p["target"])).")","".h($p["on_delete"])."\n","".h($p["on_update"])."\n",''.'Alter'.'';}echo"
    \n";}echo'

    ".'Triggers'."

    \n";$Ag=triggers($a);if($Ag){echo"\n";foreach($Ag -as$z=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($z)."".'Alter'."\n";echo"
    \n";}echo'
    +write($Ab){$this->size+=strlen($Ab);fwrite($this->handler,$Ab);}function +send(){fseek($this->handler,0);fpassthru($this->handler);fclose($this->handler);}}if(isset($_GET["select"])&&($_POST["edit"]||$_POST["clone"])&&!$_POST["save"])$_GET["edit"]=$_GET["select"];if(isset($_GET["callf"]))$_GET["call"]=$_GET["callf"];if(isset($_GET["function"]))$_GET["procedure"]=$_GET["function"];if(isset($_GET["download"])){$a=$_GET["download"];$o=fields($a);header("Content-Type: application/octet-stream");header("Content-Disposition: attachment; filename=".friendly_url("$a-".implode("_",$_GET["where"])).".".friendly_url($_GET["field"]));$M=array(idf_escape($_GET["field"]));$I=driver()->select($a,$M,array(where($_GET,$o)),$M);$K=($I?$I->fetch_row():array());echo +driver()->value($K[0],$o[$_GET["field"]]);exit;}elseif(isset($_GET["table"])){$a=$_GET["table"];$o=fields($a);if(!$o)$m=error()?:lang(11);$S=table_status1($a);$B=adminer()->tableName($S);page_header(($o&&is_view($S)?$S['Engine']=='materialized view'?lang(137):lang(138):lang(139)).": ".($B!=""?$B:h($a)),$m);$Bh=array();foreach($o +as$y=>$n)$Bh+=$n["privileges"];adminer()->selectLinks($S,(isset($Bh["insert"])||!support("table")?"":null));$qb=$S["Comment"];if($qb!="")echo"

    ".lang(51).": ".h($qb)."\n";if($o)adminer()->tableStructurePrint($o,$S);function +tables_links(array$T){echo"

    \n";}$ke=driver()->inheritsFrom($a);if($ke){echo"

    ".lang(140)."

    \n";tables_links($ke);}if(support("indexes")&&driver()->supportsIndex($S)){echo"

    ".lang(141)."

    \n";$x=indexes($a);if($x)adminer()->tableIndexesPrint($x,$S);echo'

    ".lang(106)."

    \n";$md=foreign_keys($a);if($md){echo"\n","\n";foreach($md +as$B=>$q){echo"","
    ".lang(143)."".lang(144)."".lang(109)."".lang(108)."
    ".implode(", ",array_map('Adminer\h',$q["source"]))."";$_=($q["db"]!=""?preg_replace('~db=[^&]*~',"db=".urlencode($q["db"]),ME):($q["ns"]!=""?preg_replace('~ns=[^&]*~',"ns=".urlencode($q["ns"]),ME):ME));echo"".($q["db"]!=""&&$q["db"]!=DB?"".h($q["db"]).".":"").($q["ns"]!=""&&$q["ns"]!=$_GET["ns"]?"".h($q["ns"]).".":"").h($q["table"])."","(".implode(", ",array_map('Adminer\h',$q["target"])).")","".h($q["on_delete"]),"".h($q["on_update"]),''.lang(145).'',"\n";}echo"
    \n";}echo'

    ".lang(147)."

    \n";$Za=driver()->checkConstraints($a);if($Za){echo"\n";foreach($Za +as$y=>$X)echo"","
    ".h($X),"".lang(145)."","\n";echo"
    \n";}echo'

    ".lang(149)."

    \n";$oj=triggers($a);if($oj){echo"\n";foreach($oj +as$y=>$X)echo"
    ".h($X[0])."".h($X[1])."".h($y)."".lang(145)."\n";echo"
    \n";}echo'

    ".lang(151)."

    \n";$Dg=driver()->partitionsInfo($a);if($Dg)echo"

    BY ".h("$Dg[partition_by]($Dg[partition])")."\n";tables_links($je);}}elseif(isset($_GET["schema"])){page_header(lang(71),"",array(),h(DB.($_GET["ns"]?".$_GET[ns]":"")));$Fi=array();$Gi=array();$da=($_GET["schema"]?:$_COOKIE["adminer_schema-".str_replace(".","_",DB)]);preg_match_all('~([^:]+):([-0-9.]+)x([-0-9.]+)(_|$)~',$da,$df,PREG_SET_ORDER);foreach($df +as$t=>$A){$Fi[$A[1]]=array($A[2],$A[3]);$Gi[]="\n\t'".js_escape($A[1])."': [ $A[2], $A[3] ]";}$dj=0;$Ia=-1;$Jh=array();$rh=array();$Pe=array();$ua=driver()->allFields();foreach(table_status('',true)as$R=>$S){if(is_view($S))continue;$Sg=0;$Jh[$R]["fields"]=array();foreach($ua[$R]as$n){$Sg+=1.25;$n["pos"]=$Sg;$Jh[$R]["fields"][$n["field"]]=$n;}$Jh[$R]["pos"]=($Fi[$R]?:array($dj,0));foreach(adminer()->foreignKeys($R)as$X){if(!$X["db"]){$Ne=$Ia;if(idx($Fi[$R],1)||idx($Fi[$X["table"]],1))$Ne=min(idx($Fi[$R],1,0),idx($Fi[$X["table"]],1,0))-1;else$Ia-=.1;while($Pe[(string)$Ne])$Ne-=.0001;$Jh[$R]["references"][$X["table"]][(string)$Ne]=array($X["source"],$X["target"]);$rh[$X["table"]][$R][(string)$Ne]=$X["target"];$Pe[(string)$Ne]=true;}}$dj=max($dj,$Jh[$R]["pos"][0]+2.5+$Sg);}echo'

    -qs(\'#schema\').onselectstart = function () { return false; }; -var tablePos = {',implode(",",$Yf)."\n",'}; -var em = qs(\'#schema\').offsetHeight / ',$sg,'; +qs(\'#schema\').onselectstart = () => false; +const tablePos = {',implode(",",$Gi)."\n",'}; +const em = qs(\'#schema\').offsetHeight / ',$dj,'; document.onmousemove = schemaMousemove; document.onmouseup = partialArg(schemaMouseup, \'',js_escape(DB),'\'); -';foreach($qf -as$F=>$R){echo"
    ",''.h($F)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$m){$X=''.h($m["field"]).'';echo"
    ".($m["primary"]?"$X":$X);}foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$kd=$jd-$Xf[$F][1];$u=0;foreach($cf[0]as$Ff)echo"\n
    ";}}foreach((array)$ff[$F]as$eg=>$gf){foreach($gf -as$jd=>$e){$kd=$jd-$Xf[$F][1];$u=0;foreach($e -as$dg)echo"\n
    ";}}echo"\n
    \n";}foreach($qf -as$F=>$R){foreach((array)$R["references"]as$eg=>$gf){foreach($gf -as$jd=>$cf){$Gd=$sg;$yd=-10;foreach($cf[0]as$z=>$Ff){$Je=$R["pos"][0]+$R["fields"][$Ff]["pos"];$Ke=$qf[$eg]["pos"][0]+$qf[$eg]["fields"][$cf[1][$z]]["pos"];$Gd=min($Gd,$Je,$Ke);$yd=max($yd,$Je,$Ke);}echo"
    \n";}}}echo'
    -
    ",''.h($B)."",script("qsl('div').onmousedown = schemaMousedown;");foreach($R["fields"]as$n){$X=''.h($n["field"]).'';echo"
    ".($n["primary"]?"$X":$X);}foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($oh[0]as$ji)echo"\n
    "."
    ";}}foreach((array)$rh[$B]as$Ni=>$th){foreach($th +as$Ne=>$e){$Oe=$Ne-idx($Fi[$B],1);$t=0;foreach($e +as$Mi)echo"\n
    "."
    "."
    ";}}echo"\n
    \n";}foreach($Jh +as$B=>$R){foreach((array)$R["references"]as$Ni=>$th){foreach($th +as$Ne=>$oh){$wf=$dj;$jf=-10;foreach($oh[0]as$y=>$ji){$Tg=$R["pos"][0]+$R["fields"][$ji]["pos"];$Ug=$Jh[$Ni]["pos"][0]+$Jh[$Ni]["fields"][$oh[1][$y]]["pos"];$wf=min($wf,$Tg,$Ug);$jf=max($jf,$Tg,$Ug);}echo"
    \n";}}}echo'
    +
    - -';$lb=array('','USE','DROP+CREATE','CREATE');$Zf=array('','DROP+CREATE','CREATE');$ib=array('','TRUNCATE+INSERT','INSERT');if($y=="sql")$ib[]='INSERT+UPDATE';parse_str($_COOKIE["adminer_export"],$L);if(!$L)$L=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($L["events"])){$L["routines"]=$L["events"]=($_GET["dump"]=="");$L["triggers"]=$L["table_style"];}echo"
    ".'Output'."".html_select("output",$b->dumpOutput(),$L["output"],0)."\n";echo"
    ".'Format'."".html_select("format",$b->dumpFormat(),$L["format"],0)."\n";echo($y=="sqlite"?"":"
    ".'Database'."".html_select('db_style',$lb,$L["db_style"]).(support("routine")?checkbox("routines",1,$L["routines"],'Routines'):"").(support("event")?checkbox("events",1,$L["events"],'Events'):"")),"
    ".'Tables'."".html_select('table_style',$Zf,$L["table_style"]).checkbox("auto_increment",1,$L["auto_increment"],'Auto Increment').(support("trigger")?checkbox("triggers",1,$L["triggers"],'Triggers'):""),"
    ".'Data'."".html_select('data_style',$ib,$L["data_style"]),'
    -

    - - - -',script("qsl('table').onclick = dumpClick;");$Ne=array();if(DB!=""){$Fa=($a!=""?"":" checked");echo"","\n";$Zg="";$ag=tables_list();foreach($ag -as$F=>$V){$Me=preg_replace('~_.*~','',$F);$Fa=($a==""||$a==(substr($a,-1)=="%"?"$Me%":$F));$Qe="\n";$i=$b->databases();if($i){foreach($i -as$j){if(!information_schema($j)){$Me=preg_replace('~_.*~','',$j);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$F,$Fa,$F,"","block");if($V!==null&&!preg_match('~table~i',$V))$Zg.="$Qe\n";else -echo"$Qe\n";$Ne[$Me]++;}echo$Zg;if($ag)echo -script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$j,$a==""||$a=="$Me%",$j,"","block")."\n";$Ne[$Me]++;}}}else + +';$Rb=array('','USE','DROP+CREATE','CREATE');$Hi=array('','DROP+CREATE','CREATE');$Ob=array('','TRUNCATE+INSERT','INSERT');if(JUSH=="sql")$Ob[]='INSERT+UPDATE';$K=get_settings("adminer_export");if(!$K)$K=array("output"=>"text","format"=>"sql","db_style"=>(DB!=""?"":"CREATE"),"table_style"=>"DROP+CREATE","data_style"=>"INSERT");if(!isset($K["events"])){$K["routines"]=$K["events"]=($_GET["dump"]=="");$K["triggers"]=$K["table_style"];}echo"
    ".lang(153)."".html_radios("output",adminer()->dumpOutput(),$K["output"])."\n","
    ".lang(154)."".html_radios("format",adminer()->dumpFormat(),$K["format"])."\n",(JUSH=="sqlite"?"":"
    ".lang(38)."".html_select('db_style',$Rb,$K["db_style"]).(support("type")?checkbox("types",1,$K["types"],lang(6)):"").(support("routine")?checkbox("routines",1,$K["routines"],lang(73)):"").(support("event")?checkbox("events",1,$K["events"],lang(75)):"")),"
    ".lang(129)."".html_select('table_style',$Hi,$K["table_style"]).checkbox("auto_increment",1,$K["auto_increment"],lang(52)).(support("trigger")?checkbox("triggers",1,$K["triggers"],lang(149)):""),"
    ".lang(155)."".html_select('data_style',$Ob,$K["data_style"]),'
    +

    +',input_token(),' + +',script("qsl('table').onclick = dumpClick;");$Yg=array();if(DB!=""){$bb=($a!=""?"":" checked");echo"","\n";$Sj="";$Ji=tables_list();foreach($Ji +as$B=>$U){$Xg=preg_replace('~_.*~','',$B);$bb=($a==""||$a==(substr($a,-1)=="%"?"$Xg%":$B));$bh="\n";$j=adminer()->databases();if($j){foreach($j +as$k){if(!information_schema($k)){$Xg=preg_replace('~_.*~','',$k);echo"
    ".script("qs('#check-tables').onclick = partial(formCheck, /^tables\\[/);",""),"".script("qs('#check-data').onclick = partial(formCheck, /^data\\[/);",""),"
    ".checkbox("tables[]",$B,$bb,$B,"","block");if($U!==null&&!preg_match('~table~i',$U))$Sj +.="$bh\n";else +echo"$bh\n";$Yg[$Xg]++;}echo$Sj;if($Ji)echo +script("ajaxSetHtml('".js_escape(ME)."script=db');");}else{echo"
    ","",script("qs('#check-databases').onclick = partial(formCheck, /^databases\\[/);",""),"
    ".checkbox("databases[]",$k,$a==""||$a=="$Xg%",$k,"","block")."\n";$Yg[$Xg]++;}}}else echo"
    ";}echo'
    -';$lc=true;foreach($Ne -as$z=>$X){if($z!=""&&$X>1){echo($lc?"

    ":" ")."".h($z)."";$lc=false;}}}elseif(isset($_GET["sql"])){if(!$l&&$_POST["export"]){dump_headers("sql");$b->dumpTable("","");$b->dumpData("","table",$_POST["query"]);exit;}restart_session();$Gc=&get_session("queries");$Fc=&$Gc[DB];if(!$l&&$_POST["clear"]){$Fc=array();redirect(remove_from_uri("history"));}page_header((isset($_GET["import"])?'Import':'SQL command'),$l);if(!$l&&$_POST){$r=false;if(!isset($_GET["import"]))$I=$_POST["query"];elseif($_POST["webfile"]){$If=$b->importServerPath();$r=@fopen((file_exists($If)?$If:"compress.zlib://$If.gz"),"rb");$I=($r?fread($r,1e6):false);}else$I=get_file("sql_file",true);if(is_string($I)){if(function_exists('memory_get_usage'))@ini_set("memory_limit",max(ini_bytes("memory_limit"),2*strlen($I)+memory_get_usage()+8e6));if($I!=""&&strlen($I)<1e6){$H=$I.(preg_match("~;[ \t\r\n]*\$~",$I)?"":";");if(!$Fc||reset(end($Fc))!=$H){restart_session();$Fc[]=array($H,time());set_session("queries",$Gc);stop_session();}}$Gf="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|-- )[^\n]*\n?|--\r?\n)";$rb=";";$Sd=0;$Nb=true;$g=connect();if(is_object($g)&&DB!=""){$g->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$g);}$Sa=0;$Sb=array();$ve='[\'"'.($y=="sql"?'`#':($y=="sqlite"?'`[':($y=="mssql"?'[':''))).']|/\*|-- |$'.($y=="pgsql"?'|\$[^$]*\$':'');$tg=microtime(true);parse_str($_COOKIE["adminer_export"],$ia);$Eb=$b->dumpFormat();unset($Eb["sql"]);while($I!=""){if(!$Sd&&preg_match("~^$Gf*+DELIMITER\\s+(\\S+)~i",$I,$C)){$rb=$C[1];$I=substr($I,strlen($C[0]));}else{preg_match('('.preg_quote($rb)."\\s*|$ve)",$I,$C,PREG_OFFSET_CAPTURE,$Sd);list($rc,$Ie)=$C[0];if(!$rc&&$r&&!feof($r))$I.=fread($r,1e5);else{if(!$rc&&rtrim($I)=="")break;$Sd=$Ie+strlen($rc);if($rc&&rtrim($rc)!=$rb){while(preg_match('('.($rc=='/*'?'\*/':($rc=='['?']':(preg_match('~^-- |^#~',$rc)?"\n":preg_quote($rc)."|\\\\."))).'|$)s',$I,$C,PREG_OFFSET_CAPTURE,$Sd)){$pf=$C[0][0];if(!$pf&&$r&&!feof($r))$I.=fread($r,1e5);else{$Sd=$C[0][1]+strlen($pf);if($pf[0]!="\\")break;}}}else{$Nb=false;$H=substr($I,0,$Ie);$Sa++;$Qe="

    ".$b->sqlCommandQuery($H)."
    \n";if($y=="sqlite"&&preg_match("~^$Gf*+ATTACH\\b~i",$H,$C)){echo$Qe,"

    ".'ATTACH queries are not supported.'."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$Qe;ob_flush();flush();}$Lf=microtime(true);if($f->multi_query($H)&&is_object($g)&&preg_match("~^$Gf*+USE\\b~i",$H))$g->query($H);do{$J=$f->store_result();if($f->error){echo($_POST["only_errors"]?$Qe:""),"

    ".'Error in query'.($f->errno?" ($f->errno)":"").": ".error()."\n";$Sb[]=" $Sa";if($_POST["error_stops"])break -2;}else{$jg=" (".format_time($Lf).")".(strlen($H)<1000?" ".'Edit'."":"");$ka=$f->affected_rows;$ch=($_POST["only_errors"]?"":$k->warnings());$dh="warnings-$Sa";if($ch)$jg.=", ".'Warnings'."".script("qsl('a').onclick = partial(toggle, '$dh');","");$Zb=null;$ac="explain-$Sa";if(is_object($J)){$_=$_POST["limit"];$ie=select($J,$g,array(),$_);if(!$_POST["only_errors"]){echo"

    \n";$Pd=$J->num_rows;echo"

    ".($Pd?($_&&$Pd>$_?sprintf('%d / ',$_):"").lang(array('%d row','%d rows'),$Pd):""),$jg;if($g&&preg_match("~^($Gf|\\()*+SELECT\\b~i",$H)&&($Zb=explain($g,$H)))echo", Explain".script("qsl('a').onclick = partial(toggle, '$ac');","");$v="export-$Sa";echo", ".'Export'."".script("qsl('a').onclick = partial(toggle, '$v');","")."\n"."

    \n";}}else{if(preg_match("~^$Gf*+(CREATE|DROP|ALTER)$Gf++(DATABASE|SCHEMA)\\b~i",$H)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(array('Query executed OK, %d row affected.','Query executed OK, %d rows affected.'),$ka)."$jg\n";}echo($ch?"

    \n":"");if($Zb){echo"\n";}}$Lf=microtime(true);}while($f->next_result());}$I=substr($I,$Sd);$Sd=0;}}}}if($Nb)echo"

    ".'No commands to execute.'."\n";elseif($_POST["only_errors"]){echo"

    ".lang(array('%d query executed OK.','%d queries executed OK.'),$Sa-count($Sb))," (".format_time($tg).")\n";}elseif($Sb&&$Sa>1)echo"

    ".'Error in query'.": ".implode("",$Sb)."\n";}else -echo"

    ".upload_error($I)."\n";}echo' +';$cd=true;foreach($Yg +as$y=>$X){if($y!=""&&$X>1){echo($cd?"

    ":" ")."".h($y)."";$cd=false;}}}elseif(isset($_GET["privileges"])){page_header(lang(72));echo'

    \n";hidden_fields_get();echo +input_hidden("db",DB),($vd?"":input_hidden("grant")),"\n","\n";while($K=$I->fetch_assoc())echo'
    ".lang(36)."".lang(34)."
    '.h($K["User"])."".h($K["Host"]).''.lang(12)."\n";if(!$vd||DB!="")echo"
    \n";echo"
    \n","

    \n";}elseif(isset($_GET["sql"])){if(!$m&&$_POST["export"]){save_settings(array("output"=>$_POST["output"],"format"=>$_POST["format"]),"adminer_import");dump_headers("sql");if($_POST["format"]=="sql")echo"$_POST[query]\n";else{adminer()->dumpTable("","");adminer()->dumpData("","table",$_POST["query"]);adminer()->dumpFooter();}exit;}restart_session();$Ld=&get_session("queries");$Kd=&$Ld[DB];if(!$m&&$_POST["clear"]){$Kd=array();redirect(remove_from_uri("history"));}stop_session();page_header((isset($_GET["import"])?lang(76):lang(65)),$m);$Ue='--'.(JUSH=='sql'?' ':'');if(!$m&&$_POST){$r=false;if(!isset($_GET["import"]))$H=$_POST["query"];elseif($_POST["webfile"]){$ni=adminer()->importServerPath();$r=@fopen((file_exists($ni)?$ni:"compress.zlib://$ni.gz"),"rb");$H=($r?fread($r,1e6):false);}else$H=get_file("sql_file",true,";");if(is_string($H)){if(function_exists('memory_get_usage')&&($of=ini_bytes("memory_limit"))!="-1")@ini_set("memory_limit",max($of,strval(2*strlen($H)+memory_get_usage()+8e6)));if($H!=""&&strlen($H)<1e6){$hh=$H.(preg_match("~;[ \t\r\n]*\$~",$H)?"":";");if(!$Kd||first(end($Kd))!=$hh){restart_session();$Kd[]=array($hh,time());set_session("queries",$Ld);stop_session();}}$ki="(?:\\s|/\\*[\s\S]*?\\*/|(?:#|$Ue)[^\n]*\n?|--\r?\n)";$Zb=driver()->delimiter;$C=0;$xc=true;$h=connect();if($h&&DB!=""){$h->select_db(DB);if($_GET["ns"]!="")set_schema($_GET["ns"],$h);}$pb=0;$Ec=array();$Ag='[\'"'.(JUSH=="sql"?'`#':(JUSH=="sqlite"?'`[':(JUSH=="mssql"?'[':''))).']|/\*|'.$Ue.'|$'.(JUSH=="pgsql"?'|\$([a-zA-Z]\w*)?\$':'');$ej=microtime(true);$oa=get_settings("adminer_import");while($H!=""){if(!$C&&preg_match("~^$ki*+DELIMITER\\s+(\\S+)~i",$H,$A)){$Zb=preg_quote($A[1]);$H=substr($H,strlen($A[0]));}elseif(!$C&&JUSH=='pgsql'&&preg_match("~^($ki*+COPY\\s+)[^;]+\\s+FROM\\s+stdin;~i",$H,$A)){$Zb="\n\\\\\\.\r?\n";$C=strlen($A[0]);}else{preg_match("($Zb\\s*|$Ag)",$H,$A,PREG_OFFSET_CAPTURE,$C);list($od,$Sg)=$A[0];if(!$od&&$r&&!feof($r))$H +.=fread($r,1e5);else{if(!$od&&rtrim($H)=="")break;$C=$Sg+strlen($od);if($od&&!preg_match("(^$Zb)",$od)){$Ta=driver()->hasCStyleEscapes()||(JUSH=="pgsql"&&($Sg>0&&strtolower($H[$Sg-1])=="e"));$Lg=($od=='/*'?'\*/':($od=='['?']':(preg_match("~^$Ue|^#~",$od)?"\n":preg_quote($od).($Ta?'|\\\\.':''))));while(preg_match("($Lg|\$)s",$H,$A,PREG_OFFSET_CAPTURE,$C)){$Hh=$A[0][0];if(!$Hh&&$r&&!feof($r))$H +.=fread($r,1e5);else{$C=$A[0][1]+strlen($Hh);if(!$Hh||$Hh[0]!="\\")break;}}}else{$xc=false;$hh=substr($H,0,$Sg+($Zb[0]=="\n"?3:0));$pb++;$bh="
    ".adminer()->sqlCommandQuery($hh)."
    \n";if(JUSH=="sqlite"&&preg_match("~^$ki*+ATTACH\\b~i",$hh,$A)){echo$bh,"

    ".lang(157)."\n";$Ec[]=" $pb";if($_POST["error_stops"])break;}else{if(!$_POST["only_errors"]){echo$bh;ob_flush();flush();}$si=microtime(true);if(connection()->multi_query($hh)&&$h&&preg_match("~^$ki*+USE\\b~i",$hh))$h->query($hh);do{$I=connection()->store_result();if(connection()->error){echo($_POST["only_errors"]?$bh:""),"

    ".lang(158).(connection()->errno?" (".connection()->errno.")":"").": ".error()."\n";$Ec[]=" $pb";if($_POST["error_stops"])break +2;}else{$Ti=" (".format_time($si).")".(strlen($hh)<1000?" ".lang(12)."":"");$qa=connection()->affected_rows;$Vj=($_POST["only_errors"]?"":driver()->warnings());$Wj="warnings-$pb";if($Vj)$Ti +.=", ".lang(47)."".script("qsl('a').onclick = partial(toggle, '$Wj');","");$Mc=null;$mg=null;$Nc="explain-$pb";if(is_object($I)){$z=$_POST["limit"];$mg=print_select_result($I,$h,array(),$z);if(!$_POST["only_errors"]){echo"

    \n";$Nf=$I->num_rows;echo"
    \n";}}else{if(preg_match("~^$ki*+(CREATE|DROP|ALTER)$ki++(DATABASE|SCHEMA)\\b~i",$hh)){restart_session();set_session("dbs",null);stop_session();}if(!$_POST["only_errors"])echo"

    ".lang(161,$qa)."$Ti\n";}echo($Vj?"

    \n":"");if($Mc){echo"\n";}}$si=microtime(true);}while(connection()->next_result());}$H=substr($H,$C);$C=0;}}}}if($xc)echo"

    ".lang(162)."\n";elseif($_POST["only_errors"])echo"

    ".lang(163,$pb-count($Ec))," (".format_time($ej).")\n";elseif($Ec&&$pb>1)echo"

    ".lang(158).": ".implode("",$Ec)."\n";}else +echo"

    ".upload_error($H)."\n";}echo'

    -';$Xb="";if(!isset($_GET["import"])){$H=$_GET["sql"];if($_POST)$H=$_POST["query"];elseif($_GET["history"]=="all")$H=$Fc;elseif($_GET["history"]!="")$H=$Fc[$_GET["history"]][0];echo"

    ";textarea("query",$H,20);echo -script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    $Xb\n",'Limit rows'.": \n";}else{echo"

    ".'File upload'."
    ";$zc=(extension_loaded("zlib")?"[.gz]":"");echo(ini_bool("file_uploads")?"SQL$zc (< ".ini_get("upload_max_filesize")."B): \n$Xb":'File uploads are disabled.'),"
    \n";$Mc=$b->importServerPath();if($Mc){echo"
    ".'From server'."
    ",sprintf('Webserver file %s',"".h($Mc)."$zc"),' ',"
    \n";}echo"

    ";}echo -checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),'Stop on error')."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),'Show only errors')."\n","\n";if(!isset($_GET["import"])&&$Fc){print_fieldset("history",'History',$_GET["history"]!="");for($X=end($Fc);$X;$X=prev($Fc)){$z=key($Fc);list($H,$jg,$Ib)=$X;echo''.'Edit'.""." ".@date("H:i:s",$jg).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace('~^(#|-- ).*~m','',$H)))),80,"").($Ib?" ($Ib)":"")."
    \n";}echo"\n","".'Edit all'."\n","\n";}echo'

    -';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$n=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$n):""):where($_GET,$n));$Kg=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($n -as$F=>$m){if(!isset($m["privileges"][$Kg?"update":"insert"])||$b->fieldName($m)==""||$m["generated"])unset($n[$F]);}if($_POST&&!$l&&!isset($_GET["select"])){$B=$_POST["referer"];if($_POST["insert"])$B=($Kg?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$B))$B=ME."select=".urlencode($a);$x=indexes($a);$Fg=unique_array($_GET["where"],$x);$Ye="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($B,'Item has been deleted.',$k->delete($a,$Ye,!$Fg));else{$P=array();foreach($n -as$F=>$m){$X=process_input($m);if($X!==false&&$X!==null)$P[idf_escape($F)]=$X;}if($Kg){if(!$P)redirect($B);queries_redirect($B,'Item has been updated.',$k->update($a,$P,$Ye,!$Fg));if(is_ajax()){page_headers();page_messages($l);exit;}}else{$J=$k->insert($a,$P);$id=($J?last_id():0);queries_redirect($B,sprintf('Item%s has been inserted.',($id?" $id":"")),$J);}}}$L=null;if($_POST["save"])$L=(array)$_POST["fields"];elseif($Z){$N=array();foreach($n -as$F=>$m){if(isset($m["privileges"]["select"])){$pa=convert_field($m);if($_POST["clone"]&&$m["auto_increment"])$pa="''";if($y=="sql"&&preg_match("~enum|set~",$m["type"]))$pa="1*".idf_escape($F);$N[]=($pa?"$pa AS ":"").idf_escape($F);}}$L=array();if(!support("table"))$N=array("*");if($N){$J=$k->select($a,$N,array($Z),$N,array(),(isset($_GET["select"])?2:1));if(!$J)$l=error();else{$L=$J->fetch_assoc();if(!$L)$L=false;}if(isset($_GET["select"])&&(!$L||$J->fetch_assoc()))$L=null;}}if(!support("table")&&!$n){if(!$Z){$J=$k->select($a,array("*"),$Z,array("*"));$L=($J?$J->fetch_assoc():false);if(!$L)$L=array($k->primary=>"");}if($L){foreach($L -as$z=>$X){if(!$Z)$L[$z]=null;$n[$z]=array("field"=>$z,"null"=>($z!=$k->primary),"auto_increment"=>($z==$k->primary));}}}edit_form($a,$n,$L,$Kg);}elseif(isset($_GET["create"])){$a=$_GET["create"];$we=array();foreach(array('HASH','LINEAR HASH','KEY','LINEAR KEY','RANGE','LIST')as$z)$we[$z]=$z;$ef=referencable_primary($a);$q=array();foreach($ef -as$Wf=>$m)$q[str_replace("`","``",$Wf)."`".str_replace("`","``",$m["field"])]=$Wf;$le=array();$S=array();if($a!=""){$le=fields($a);$S=table_status($a);if(!$S)$l='No tables.';}$L=$_POST;$L["fields"]=(array)$L["fields"];if($L["auto_increment_col"])$L["fields"][$L["auto_increment_col"]]["auto_increment"]=true;if($_POST)set_adminer_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($L["fields"])&&!$l){if($_POST["drop"])queries_redirect(substr(ME,0,-1),'Table has been dropped.',drop_tables(array($a)));else{$n=array();$na=array();$Og=false;$oc=array();$ke=reset($le);$ma=" FIRST";foreach($L["fields"]as$z=>$m){$p=$q[$m["type"]];$Bg=($p!==null?$ef[$p]:$m);if($m["field"]!=""){if(!$m["has_default"])$m["default"]=null;if($z==$L["auto_increment_col"])$m["auto_increment"]=true;$Ue=process_field($m,$Bg);$na[]=array($m["orig"],$Ue,$ma);if(!$ke||$Ue!=process_field($ke,$ke)){$n[]=array($m["orig"],$Ue,$ma);if($m["orig"]!=""||$ma)$Og=true;}if($p!==null)$oc[idf_escape($m["field"])]=($a!=""&&$y!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$q[$m["type"]],'source'=>array($m["field"]),'target'=>array($Bg["field"]),'on_delete'=>$m["on_delete"],));$ma=" AFTER ".idf_escape($m["field"]);}elseif($m["orig"]!=""){$Og=true;$n[]=array($m["orig"]);}if($m["orig"]!=""){$ke=next($le);if(!$ke)$ma="";}}$ye="";if($we[$L["partition_by"]]){$ze=array();if($L["partition_by"]=='RANGE'||$L["partition_by"]=='LIST'){foreach(array_filter($L["partition_names"])as$z=>$X){$Y=$L["partition_values"][$z];$ze[]="\n PARTITION ".idf_escape($X)." VALUES ".($L["partition_by"]=='RANGE'?"LESS THAN":"IN").($Y!=""?" ($Y)":" MAXVALUE");}}$ye.="\nPARTITION BY $L[partition_by]($L[partition])".($ze?" (".implode(",",$ze)."\n)":($L["partitions"]?" PARTITIONS ".(+$L["partitions"]):""));}elseif(support("partitioning")&&preg_match("~partitioned~",$S["Create_options"]))$ye.="\nREMOVE PARTITIONING";$D='Table has been altered.';if($a==""){cookie("adminer_engine",$L["Engine"]);$D='Table has been created.';}$F=trim($L["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($F),$D,alter_table($a,$F,($y=="sqlite"&&($Og||$oc)?$na:$n),$oc,($L["Comment"]!=$S["Comment"]?$L["Comment"]:null),($L["Engine"]&&$L["Engine"]!=$S["Engine"]?$L["Engine"]:""),($L["Collation"]&&$L["Collation"]!=$S["Collation"]?$L["Collation"]:""),($L["Auto_increment"]!=""?number($L["Auto_increment"]):""),$ye));}}page_header(($a!=""?'Alter table':'Create table'),$l,array("table"=>$a),h($a));if(!$_POST){$L=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($Cg["int"])?"int":(isset($Cg["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$L=$S;$L["name"]=$a;$L["fields"]=array();if(!$_GET["auto_increment"])$L["Auto_increment"]="";foreach($le -as$m){$m["has_default"]=isset($m["default"]);$L["fields"][]=$m;}if(support("partitioning")){$tc="FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = ".q(DB)." AND TABLE_NAME = ".q($a);$J=$f->query("SELECT PARTITION_METHOD, PARTITION_ORDINAL_POSITION, PARTITION_EXPRESSION $tc ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");list($L["partition_by"],$L["partitions"],$L["partition"])=$J->fetch_row();$ze=get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $tc AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");$ze[""]="";$L["partition_names"]=array_keys($ze);$L["partition_values"]=array_values($ze);}}}$Pa=collations();$Pb=engines();foreach($Pb -as$Ob){if(!strcasecmp($Ob,$L["Engine"])){$L["Engine"]=$Ob;break;}}echo' +';$Kc="";if(!isset($_GET["import"])){$hh=$_GET["sql"];if($_POST)$hh=$_POST["query"];elseif($_GET["history"]=="all")$hh=$Kd;elseif($_GET["history"]!="")$hh=idx($Kd[$_GET["history"]],0);echo"

    ";textarea("query",$hh,20);echo +script(($_POST?"":"qs('textarea').focus();\n")."qs('#form').onsubmit = partial(sqlSubmit, qs('#form'), '".js_escape(remove_from_uri("sql|limit|error_stops|only_errors|history"))."');"),"

    ";adminer()->sqlPrintAfter();echo"$Kc\n",lang(165).": \n";}else{$Ad=(extension_loaded("zlib")?"[.gz]":"");echo"

    ".lang(166)."
    ",file_input("SQL$Ad: \n$Kc"),"
    \n";$Wd=adminer()->importServerPath();if($Wd)echo"
    ".lang(167)."
    ",lang(168,"".h($Wd)."$Ad"),' ',"
    \n";echo"

    ";}echo +checkbox("error_stops",1,($_POST?$_POST["error_stops"]:isset($_GET["import"])||$_GET["error_stops"]),lang(170))."\n",checkbox("only_errors",1,($_POST?$_POST["only_errors"]:isset($_GET["import"])||$_GET["only_errors"]),lang(171))."\n",input_token();if(!isset($_GET["import"])&&$Kd){print_fieldset("history",lang(172),$_GET["history"]!="");for($X=end($Kd);$X;$X=prev($Kd)){$y=key($Kd);list($hh,$Ti,$sc)=$X;echo''.lang(12).""." ".@date("H:i:s",$Ti).""." ".shorten_utf8(ltrim(str_replace("\n"," ",str_replace("\r","",preg_replace("~^(#|$Ue).*~m",'',$hh)))),80,"").($sc?" ($sc)":"")."
    \n";}echo"\n","".lang(174)."\n","\n";}echo' +';}elseif(isset($_GET["edit"])){$a=$_GET["edit"];$o=fields($a);$Z=(isset($_GET["select"])?($_POST["check"]&&count($_POST["check"])==1?where_check($_POST["check"][0],$o):""):where($_GET,$o));$_j=(isset($_GET["select"])?$_POST["edit"]:$Z);foreach($o +as$B=>$n){if((!$_j&&!isset($n["privileges"]["insert"]))||adminer()->fieldName($n)=="")unset($o[$B]);}if($_POST&&!$m&&!isset($_GET["select"])){$We=$_POST["referer"];if($_POST["insert"])$We=($_j?null:$_SERVER["REQUEST_URI"]);elseif(!preg_match('~^.+&select=.+$~',$We))$We=ME."select=".urlencode($a);$x=indexes($a);$vj=unique_array($_GET["where"],$x);$kh="\nWHERE $Z";if(isset($_POST["delete"]))queries_redirect($We,lang(175),driver()->delete($a,$kh,$vj?0:1));else{$O=array();foreach($o +as$B=>$n){$X=process_input($n);if($X!==false&&$X!==null)$O[idf_escape($B)]=$X;}if($_j){if(!$O)redirect($We);queries_redirect($We,lang(176),driver()->update($a,$O,$kh,$vj?0:1));if(is_ajax()){page_headers();page_messages($m);exit;}}else{$I=driver()->insert($a,$O);$Me=($I?last_id($I):0);queries_redirect($We,lang(177,($Me?" $Me":"")),$I);}}}$K=null;if($Z){$M=array();foreach($o +as$B=>$n){if(isset($n["privileges"]["select"])){$ya=($_POST["clone"]&&$n["auto_increment"]?"''":convert_field($n));$M[]=($ya?"$ya AS ":"").idf_escape($B);}}$K=array();if(!support("table"))$M=array("*");if($M){$I=driver()->select($a,$M,array($Z),$M,array(),(isset($_GET["select"])?2:1));if(!$I)$m=error();else{$K=$I->fetch_assoc();if(!$K)$K=false;}if(isset($_GET["select"])&&(!$K||$I->fetch_assoc()))$K=null;}}if(!support("table")&&!$o){if(!$Z){$I=driver()->select($a,array("*"),array(),array("*"));$K=($I?$I->fetch_assoc():false);if(!$K)$K=array(driver()->primary=>"");}if($K){foreach($K +as$y=>$X){if(!$Z)$K[$y]=null;$o[$y]=array("field"=>$y,"null"=>($y!=driver()->primary),"auto_increment"=>($y==driver()->primary));}}}if($_POST["save"])$K=(array)$_POST["fields"]+($K?$K:array());edit_form($a,$o,$K,$_j,$m);}elseif(isset($_GET["create"])){$a=$_GET["create"];$Fg=driver()->partitionBy;$Ig=($Fg?driver()->partitionsInfo($a):array());$qh=referencable_primary($a);$md=array();foreach($qh +as$Di=>$n)$md[str_replace("`","``",$Di)."`".str_replace("`","``",$n["field"])]=$Di;$pg=array();$S=array();if($a!=""){$pg=fields($a);$S=table_status1($a);if(count($S)<2)$m=lang(11);}$K=$_POST;$K["fields"]=(array)$K["fields"];if($K["auto_increment_col"])$K["fields"][$K["auto_increment_col"]]["auto_increment"]=true;if($_POST)save_settings(array("comments"=>$_POST["comments"],"defaults"=>$_POST["defaults"]));if($_POST&&!process_fields($K["fields"])&&!$m){if($_POST["drop"])queries_redirect(substr(ME,0,-1),lang(178),drop_tables(array($a)));else{$o=array();$ua=array();$Fj=false;$kd=array();$og=reset($pg);$sa=" FIRST";foreach($K["fields"]as$y=>$n){$q=$md[$n["type"]];$qj=($q!==null?$qh[$q]:$n);if($n["field"]!=""){if(!$n["generated"])$n["default"]=null;$gh=process_field($n,$qj);$ua[]=array($n["orig"],$gh,$sa);if(!$og||$gh!==process_field($og,$og)){$o[]=array($n["orig"],$gh,$sa);if($n["orig"]!=""||$sa)$Fj=true;}if($q!==null)$kd[idf_escape($n["field"])]=($a!=""&&JUSH!="sqlite"?"ADD":" ").format_foreign_key(array('table'=>$md[$n["type"]],'source'=>array($n["field"]),'target'=>array($qj["field"]),'on_delete'=>$n["on_delete"],));$sa=" AFTER ".idf_escape($n["field"]);}elseif($n["orig"]!=""){$Fj=true;$o[]=array($n["orig"]);}if($n["orig"]!=""){$og=next($pg);if(!$og)$sa="";}}$E=array();if(in_array($K["partition_by"],$Fg)){foreach($K +as$y=>$X){if(preg_match('~^partition~',$y))$E[$y]=$X;}foreach($E["partition_names"]as$y=>$B){if($B==""){unset($E["partition_names"][$y]);unset($E["partition_values"][$y]);}}$E["partition_names"]=array_values($E["partition_names"]);$E["partition_values"]=array_values($E["partition_values"]);if($E==$Ig)$E=array();}elseif(preg_match("~partitioned~",$S["Create_options"]))$E=null;$qf=lang(179);if($a==""){cookie("adminer_engine",$K["Engine"]);$qf=lang(180);}$B=trim($K["name"]);queries_redirect(ME.(support("table")?"table=":"select=").urlencode($B),$qf,alter_table($a,$B,(JUSH=="sqlite"&&($Fj||$kd)?$ua:$o),$kd,($K["Comment"]!=$S["Comment"]?$K["Comment"]:null),($K["Engine"]&&$K["Engine"]!=$S["Engine"]?$K["Engine"]:""),($K["Collation"]&&$K["Collation"]!=$S["Collation"]?$K["Collation"]:""),($K["Auto_increment"]!=""?number($K["Auto_increment"]):""),$E));}}page_header(($a!=""?lang(45):lang(78)),$m,array("table"=>$a),h($a));if(!$_POST){$rj=driver()->types();$K=array("Engine"=>$_COOKIE["adminer_engine"],"fields"=>array(array("field"=>"","type"=>(isset($rj["int"])?"int":(isset($rj["integer"])?"integer":"")),"on_update"=>"")),"partition_names"=>array(""),);if($a!=""){$K=$S;$K["name"]=$a;$K["fields"]=array();if(!$_GET["auto_increment"])$K["Auto_increment"]="";foreach($pg +as$n){$n["generated"]=$n["generated"]?:(isset($n["default"])?"DEFAULT":"");$K["fields"][]=$n;}if($Fg){$K+=$Ig;$K["partition_names"][]="";$K["partition_values"][]="";}}}$lb=collations();if(is_array(reset($lb)))$lb=call_user_func_array('array_merge',array_values($lb));$zc=driver()->engines();foreach($zc +as$yc){if(!strcasecmp($yc,$K["Engine"])){$K["Engine"]=$yc;break;}}echo'

    -';if(support("columns")||$a==""){echo'Table name: -';if($a==""&&!$_POST)echo -script("focus(qs('#form')['name']);");echo($Pb?"".on_help("getTarget(event).value",1).script("qsl('select').onchange = helpClose;"):""),' ',($Pa&&!preg_match("~sqlite|mssql~",$y)?html_select("Collation",array(""=>"(".'collation'.")")+$Pa,$L["Collation"]):""),' -';}echo' -';if(support("columns")){echo'

    - -';edit_fields($L["fields"],$Pa,"TABLE",$q);echo'
    -',script("editFields();"),'
    -

    -Auto Increment: -',checkbox("defaults",1,($_POST?$_POST["defaults"]:adminer_setting("defaults")),'Default values',"columnShow(this.checked, 5)","jsonly"),(support("comment")?checkbox("comments",1,($_POST?$_POST["comments"]:adminer_setting("comments")),'Comment',"editingCommentsClick(this, true);","jsonly").' ':''),'

    - +';if(support("columns")||$a==""){echo +lang(181).": \n",($zc?html_select("Engine",array(""=>"(".lang(182).")")+$zc,$K["Engine"]).on_help("event.target.value",1).script("qsl('select').onchange = helpClose;")."\n":"");if($lb)echo"".optionlist($lb)."\n",(preg_match("~sqlite|mssql~",JUSH)?"":"\n");echo"\n";}if(support("columns")){echo"

    \n","\n";edit_fields($K["fields"],$lb,"TABLE",$md);echo"
    \n",script("editFields();"),"
    \n

    \n",lang(52).": \n",checkbox("defaults",1,($_POST?$_POST["defaults"]:get_setting("defaults")),lang(183),"columnShow(this.checked, 5)","jsonly");$sb=($_POST?$_POST["comments"]:get_setting("comments"));echo(support("comment")?checkbox("comments",1,$sb,lang(51),"editingCommentsClick(this, true);","jsonly").' '.(preg_match('~\n~',$K["Comment"])?"":''):''),'

    + ';}echo' -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}if(support("partitioning")){$xe=preg_match('~RANGE|LIST~',$L["partition_by"]);print_fieldset("partition",'Partition by',$L["partition_by"]);echo'

    -',"".on_help("getTarget(event).value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),'() -Partitions: - - -';foreach($L["partition_names"]as$z=>$X){echo'',' - -';}echo' -

    -';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$Oc=array("PRIMARY","UNIQUE","INDEX");$S=table_status($a,true);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$Oc[]="SPATIAL";$x=indexes($a);$Oe=array();if($y=="mongo"){$Oe=$x["_id_"];unset($Oc[0]);unset($x["_id_"]);}$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["drop_col"]){$oa=array();foreach($L["indexes"]as$w){$F=$w["name"];if(in_array($w["type"],$Oc)){$e=array();$od=array();$tb=array();$P=array();ksort($w["columns"]);foreach($w["columns"]as$z=>$d){if($d!=""){$nd=$w["lengths"][$z];$sb=$w["descs"][$z];$P[]=idf_escape($d).($nd?"(".(+$nd).")":"").($sb?" DESC":"");$e[]=$d;$od[]=($nd?$nd:null);$tb[]=$sb;}}if($e){$Yb=$x[$F];if($Yb){ksort($Yb["columns"]);ksort($Yb["lengths"]);ksort($Yb["descs"]);if($w["type"]==$Yb["type"]&&array_values($Yb["columns"])===$e&&(!$Yb["lengths"]||array_values($Yb["lengths"])===$od)&&array_values($Yb["descs"])===$tb){unset($x[$F]);continue;}}$oa[]=array($w["type"],$F,$P);}}}foreach($x -as$F=>$Yb)$oa[]=array($Yb["type"],$F,"DROP");if(!$oa)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),'Indexes have been altered.',alter_indexes($a,$oa));}page_header('Indexes',$l,array("table"=>$a),h($a));$n=array_keys(fields($a));if($_POST["add"]){foreach($L["indexes"]as$z=>$w){if($w["columns"][count($w["columns"])]!="")$L["indexes"][$z]["columns"][]="";}$w=end($L["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$L["indexes"][]=array("columns"=>array(1=>""));}if(!$L){foreach($x -as$z=>$w){$x[$z]["name"]=$z;$x[$z]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$L["indexes"]=$x;}echo' +';if($a!="")echo'',confirm(lang(184,$a));if($Fg&&(JUSH=='sql'||$a=="")){$Gg=preg_match('~RANGE|LIST~',$K["partition_by"]);print_fieldset("partition",lang(185),$K["partition_by"]);echo"

    ".html_select("partition_by",array_merge(array(""),$Fg),$K["partition_by"]).on_help("event.target.value.replace(/./, 'PARTITION BY \$&')",1).script("qsl('select').onchange = partitionByChange;"),"()\n",lang(186).": \n","\n","\n";foreach($K["partition_names"]as$y=>$X)echo'','\n\n";}echo +input_token(),' +';}elseif(isset($_GET["indexes"])){$a=$_GET["indexes"];$ee=array("PRIMARY","UNIQUE","INDEX");$S=table_status1($a,true);$be=driver()->indexAlgorithms($S);if(preg_match('~MyISAM|M?aria'.(min_version(5.6,'10.0.5')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="FULLTEXT";if(preg_match('~MyISAM|M?aria'.(min_version(5.7,'10.2.2')?'|InnoDB':'').'~i',$S["Engine"]))$ee[]="SPATIAL";$x=indexes($a);$o=fields($a);$G=array();if(JUSH=="mongo"){$G=$x["_id_"];unset($ee[0]);unset($x["_id_"]);}$K=$_POST;if($K)save_settings(array("index_options"=>$K["options"]));if($_POST&&!$m&&!$_POST["add"]&&!$_POST["drop_col"]){$b=array();foreach($K["indexes"]as$w){$B=$w["name"];if(in_array($w["type"],$ee)){$e=array();$Se=array();$cc=array();$ce=(support("partial_indexes")?$w["partial"]:"");$ae=(in_array($w["algorithm"],$be)?$w["algorithm"]:"");$O=array();ksort($w["columns"]);foreach($w["columns"]as$y=>$d){if($d!=""){$Re=idx($w["lengths"],$y);$ac=idx($w["descs"],$y);$O[]=($o[$d]?idf_escape($d):$d).($Re?"(".(+$Re).")":"").($ac?" DESC":"");$e[]=$d;$Se[]=($Re?:null);$cc[]=$ac;}}$Lc=$x[$B];if($Lc){ksort($Lc["columns"]);ksort($Lc["lengths"]);ksort($Lc["descs"]);if($w["type"]==$Lc["type"]&&array_values($Lc["columns"])===$e&&(!$Lc["lengths"]||array_values($Lc["lengths"])===$Se)&&array_values($Lc["descs"])===$cc&&$Lc["partial"]==$ce&&(!$be||$Lc["algorithm"]==$ae)){unset($x[$B]);continue;}}if($e)$b[]=array($w["type"],$B,$O,$ae,$ce);}}foreach($x +as$B=>$Lc)$b[]=array($Lc["type"],$B,"DROP");if(!$b)redirect(ME."table=".urlencode($a));queries_redirect(ME."table=".urlencode($a),lang(189),alter_indexes($a,$b));}page_header(lang(141),$m,array("table"=>$a),h($a));$Zc=array_keys($o);if($_POST["add"]){foreach($K["indexes"]as$y=>$w){if($w["columns"][count($w["columns"])]!="")$K["indexes"][$y]["columns"][]="";}$w=end($K["indexes"]);if($w["type"]||array_filter($w["columns"],'strlen'))$K["indexes"][]=array("columns"=>array(1=>""));}if(!$K){foreach($x +as$y=>$w){$x[$y]["name"]=$y;$x[$y]["columns"][]="";}$x[]=array("columns"=>array(1=>""));$K["indexes"]=$x;}$Se=(JUSH=="sql"||JUSH=="mssql");$ei=($_POST?$_POST["options"]:get_setting("index_options"));echo'

    - +
    - -';if($Oe){echo"
    Index Type -Column (length) -Name - +',lang(190);$Ud=" class='idxopts".($ei?"":" hidden")."'";if($be)echo"".lang(191).doc_link(array('sql'=>'create-index.html#create-index-storage-engine-index-types','mariadb'=>'storage-engine-index-types/','pgsql'=>'indexes-types.html',));echo'',lang(192).($Se?" (".lang(193).")":"");if($Se||support("descidx"))echo +checkbox("options",1,$ei,lang(113),"indexOptionsShow(this.checked)","jsonly")."\n";echo'',lang(194);if(support("partial_indexes"))echo"".lang(195);echo'
    PRIMARY";foreach($Oe["columns"]as$z=>$d){echo -select_input(" disabled",$n,$d)," ";}echo"\n";}$Zc=1;foreach($L["indexes"]as$w){if(!$_POST["drop_col"]||$Zc!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$Zc][type]",array(-1=>"")+$Oc,$w["type"],($Zc==count($L["indexes"])?"indexesAddRow.call(this);":1),"label-type"),"";ksort($w["columns"]);$u=1;foreach($w["columns"]as$z=>$d){echo"".select_input(" name='indexes[$Zc][columns][$u]' title='".'Column'."'",($n?array_combine($n,$n):$n),$d,"partial(".($u==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape($y=="sql"?"":$_GET["indexes"]."_")."')"),($y=="sql"||$y=="mssql"?"":""),(support("descidx")?checkbox("indexes[$Zc][descs][$u]",1,$w["descs"][$z],'descending'):"")," ";$u++;}echo"\n","".script("qsl('input').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$Zc++;}echo'
    +';if($G){echo"
    PRIMARY";foreach($G["columns"]as$y=>$d)echo +select_input(" disabled",$Zc,$d)," ";echo"\n";}$_e=1;foreach($K["indexes"]as$w){if(!$_POST["drop_col"]||$_e!=key($_POST["drop_col"])){echo"
    ".html_select("indexes[$_e][type]",array(-1=>"")+$ee,$w["type"],($_e==count($K["indexes"])?"indexesAddRow.call(this);":""),"label-type");if($be)echo"".html_select("indexes[$_e][algorithm]",array_merge(array(""),$be),$w['algorithm'],"label-algorithm");echo"";ksort($w["columns"]);$t=1;foreach($w["columns"]as$y=>$d){echo"".select_input(" name='indexes[$_e][columns][$t]' title='".lang(49)."'",($o&&($d==""||$o[$d])?array_combine($Zc,$Zc):array()),$d,"partial(".($t==count($w["columns"])?"indexesAddColumn":"indexesChangeColumn").", '".js_escape(JUSH=="sql"?"":$_GET["indexes"]."_")."')"),"",($Se?"":""),(support("descidx")?checkbox("indexes[$_e][descs][$t]",1,idx($w["descs"],$y),lang(60)):"")," ";$t++;}echo"\n";if(support("partial_indexes"))echo"\n";echo"".icon("cross","drop_col[$_e]","x",lang(117)).script("qsl('button').onclick = partial(editingRemoveRow, 'indexes\$1[type]');");}$_e++;}echo'

    - - - -';}elseif(isset($_GET["database"])){$L=$_POST;if($_POST&&!$l&&!isset($_POST["add_x"])){$F=trim($L["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),'Database has been dropped.',drop_databases(array(DB)));}elseif(DB!==$F){if(DB!=""){$_GET["db"]=$F;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($F),'Database has been renamed.',rename_database($F,$L["collation"]));}else{$i=explode("\n",str_replace("\r","",$F));$Qf=true;$hd="";foreach($i -as$j){if(count($i)==1||$j!=""){if(!create_database($j,$L["collation"]))$Qf=false;$hd=$j;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($hd),'Database has been created.',$Qf);}}else{if(!$L["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($F).(preg_match('~^[a-z0-9_]+$~i',$L["collation"])?" COLLATE $L[collation]":""),substr(ME,0,-1),'Database has been altered.');}}page_header(DB!=""?'Alter database':'Create database',$l,array(),h(DB));$Pa=collations();$F=DB;if($_POST)$F=$L["name"];elseif(DB!="")$L["collation"]=db_collation(DB,$Pa);elseif($y=="sql"){foreach(get_vals("SHOW GRANTS")as$vc){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vc,$C)&&$C[1]){$F=stripcslashes(idf_unescape("`$C[2]`"));break;}}}echo' + +',input_token(),' +';}elseif(isset($_GET["database"])){$K=$_POST;if($_POST&&!$m&&!$_POST["add"]){$B=trim($K["name"]);if($_POST["drop"]){$_GET["db"]="";queries_redirect(remove_from_uri("db|database"),lang(196),drop_databases(array(DB)));}elseif(DB!==$B){if(DB!=""){$_GET["db"]=$B;queries_redirect(preg_replace('~\bdb=[^&]*&~','',ME)."db=".urlencode($B),lang(197),rename_database($B,$K["collation"]));}else{$j=explode("\n",str_replace("\r","",$B));$xi=true;$Le="";foreach($j +as$k){if(count($j)==1||$k!=""){if(!create_database($k,$K["collation"]))$xi=false;$Le=$k;}}restart_session();set_session("dbs",null);queries_redirect(ME."db=".urlencode($Le),lang(198),$xi);}}else{if(!$K["collation"])redirect(substr(ME,0,-1));query_redirect("ALTER DATABASE ".idf_escape($B).(preg_match('~^[a-z0-9_]+$~i',$K["collation"])?" COLLATE $K[collation]":""),substr(ME,0,-1),lang(199));}}page_header(DB!=""?lang(68):lang(121),$m,array(),h(DB));$lb=collations();$B=DB;if($_POST)$B=$K["name"];elseif(DB!="")$K["collation"]=db_collation(DB,$lb);elseif(JUSH=="sql"){foreach(get_vals("SHOW GRANTS")as$vd){if(preg_match('~ ON (`(([^\\\\`]|``|\\\\.)*)%`\.\*)?~',$vd,$A)&&$A[1]){$B=stripcslashes(idf_unescape("`$A[2]`"));break;}}}echo'

    -',($_POST["add_x"]||strpos($F,"\n")?'
    ':'')."\n".($Pa?html_select("collation",array(""=>"(".'collation'.")")+$Pa,$L["collation"]).'':""),script("focus(qs('#name'));"),' -';if(DB!="")echo"".confirm(sprintf('Drop %s?',DB))."\n";elseif(!$_POST["add_x"]&&$_GET["db"]=="")echo"\n";echo' -

    -';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$F=$_GET["name"];$L=$_POST;if($_POST&&!$l&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){$D=($_POST["drop"]?'Foreign key has been dropped.':($F!=""?'Foreign key has been altered.':'Foreign key has been created.'));$B=ME."table=".urlencode($a);if(!$_POST["drop"]){$L["source"]=array_filter($L["source"],'strlen');ksort($L["source"]);$dg=array();foreach($L["source"]as$z=>$X)$dg[$z]=$L["target"][$z];$L["target"]=$dg;}if($y=="sqlite")queries_redirect($B,$D,recreate_table($a,$a,array(),array(),array(" $F"=>($_POST["drop"]?"":" ".format_foreign_key($L)))));else{$oa="ALTER TABLE ".table($a);$_b="\nDROP ".($y=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($F);if($_POST["drop"])query_redirect($oa.$_b,$B,$D);else{query_redirect($oa.($F!=""?"$_b,":"")."\nADD".format_foreign_key($L),$B,$D);$l='Source and target columns must have the same data type, there must be an index on the target columns and referenced data must exist.'."
    $l";}}}page_header('Foreign key',$l,array("table"=>$a),h($a));if($_POST){ksort($L["source"]);if($_POST["add"])$L["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$L["target"]=array();}elseif($F!=""){$q=foreign_keys($a);$L=$q[$F];$L["source"][]="";}else{$L["table"]=$a;$L["source"]=array("");}echo' +',($_POST["add"]||strpos($B,"\n")?'
    ':'')."\n".($lb?html_select("collation",array(""=>"(".lang(107).")")+$lb,$K["collation"]).doc_link(array('sql'=>"charset-charsets.html",'mariadb'=>"supported-character-sets-and-collations/",'mssql'=>"relational-databases/system-functions/sys-fn-helpcollations-transact-sql",)):""),' +';if(DB!="")echo"".confirm(lang(184,DB))."\n";elseif(!$_POST["add"]&&$_GET["db"]=="")echo +icon("plus","add[0]","+",lang(114))."\n";echo +input_token(),' +';}elseif(isset($_GET["scheme"])){$K=$_POST;if($_POST&&!$m){$_=preg_replace('~ns=[^&]*&~','',ME)."ns=";if($_POST["drop"])query_redirect("DROP SCHEMA ".idf_escape($_GET["ns"]),$_,lang(200));else{$B=trim($K["name"]);$_ +.=urlencode($B);if($_GET["ns"]=="")query_redirect("CREATE SCHEMA ".idf_escape($B),$_,lang(201));elseif($_GET["ns"]!=$B)query_redirect("ALTER SCHEMA ".idf_escape($_GET["ns"])." RENAME TO ".idf_escape($B),$_,lang(202));else +redirect($_);}}page_header($_GET["ns"]!=""?lang(69):lang(70),$m);if(!$K)$K["name"]=$_GET["ns"];echo' +
    +

    + +';if($_GET["ns"]!="")echo"".confirm(lang(184,$_GET["ns"]))."\n";echo +input_token(),'

    +';}elseif(isset($_GET["call"])){$ca=($_GET["name"]?:$_GET["call"]);page_header(lang(203).": ".h($ca),$m);$Dh=routine($_GET["call"],(isset($_GET["callf"])?"FUNCTION":"PROCEDURE"));$Xd=array();$ug=array();foreach($Dh["fields"]as$t=>$n){if(substr($n["inout"],-3)=="OUT"&&JUSH=='sql')$ug[$t]="@".idf_escape($n["field"])." AS ".idf_escape($n["field"]);if(!$n["inout"]||substr($n["inout"],0,2)=="IN")$Xd[]=$t;}if(!$m&&$_POST){$Ua=array();foreach($Dh["fields"]as$y=>$n){$X="";if(in_array($y,$Xd)){$X=process_input($n);if($X===false)$X="''";if(isset($ug[$y]))connection()->query("SET @".idf_escape($n["field"])." = $X");}if(isset($ug[$y]))$Ua[]="@".idf_escape($n["field"]);elseif(in_array($y,$Xd))$Ua[]=$X;}$H=(isset($_GET["callf"])?"SELECT ":"CALL ").(idx($Dh["returns"],"type")=="record"?"* FROM ":"").table($ca)."(".implode(", ",$Ua).")";$si=microtime(true);$I=connection()->multi_query($H);$qa=connection()->affected_rows;echo +adminer()->selectQuery($H,$si,!$I);if(!$I)echo"

    ".error()."\n";else{$h=connect();if($h)$h->select_db(DB);do{$I=connection()->store_result();if(is_object($I))print_select_result($I,$h);else +echo"

    ".lang(204,$qa)." ".@date("H:i:s")."\n";}while(connection()->next_result());if($ug)print_select_result(connection()->query("SELECT ".implode(", ",$ug)));}}echo'

    -';$Ff=array_keys(fields($a));if($L["db"]!="")$f->select_db($L["db"]);if($L["ns"]!="")set_schema($L["ns"]);$df=array_keys(array_filter(table_status('',true),'fk_support'));$dg=array_keys(fields(in_array($L["table"],$df)?$L["table"]:reset($df)));$Xd="this.form['change-js'].value = '1'; this.form.submit();";echo"

    ".'Target table'.": ".html_select("table",$df,$L["table"],$Xd)."\n";if($y=="pgsql")echo'Schema'.": ".html_select("ns",$b->schemas(),$L["ns"]!=""?$L["ns"]:$_GET["ns"],$Xd);elseif($y!="sqlite"){$mb=array();foreach($b->databases()as$j){if(!information_schema($j))$mb[]=$j;}echo'DB'.": ".html_select("db",$mb,$L["db"]!=""?$L["db"]:$_GET["db"],$Xd);}echo' -

    - - -';$Zc=0;foreach($L["source"]as$z=>$X){echo"","
    SourceTarget
    ".html_select("source[".(+$z)."]",array(-1=>"")+$Ff,$X,($Zc==count($L["source"])-1?"foreignAddRow.call(this);":1),"label-source"),"".html_select("target[".(+$z)."]",$dg,$L["target"][$z],1,"label-target");$Zc++;}echo'
    +';if($Xd){echo"\n";foreach($Xd +as$y){$n=$Dh["fields"][$y];$B=$n["field"];echo"
    ".adminer()->fieldName($n);$Y=idx($_POST["fields"],$B);if($Y!=""){if($n["type"]=="set")$Y=implode(",",$Y);}input($n,$Y,idx($_POST["function"],$B,""));echo"\n";}echo"
    \n";}echo'

    + +',input_token(),'

    + +
    +';function
    +pre_tr($Hh){return
    +preg_replace('~^~m','',preg_replace('~\|~','',preg_replace('~\|$~m',"",rtrim($Hh))));}$R='(\+--[-+]+\+\n)';$K='(\| .* \|\n)';echo
    +preg_replace_callback("~^$R?$K$R?($K*)$R?~m",function($A){$dd=pre_tr($A[2]);return"\n".($A[1]?"$dd\n":$dd).pre_tr($A[4])."\n
    ";},preg_replace('~(\n( -|mysql)> )(.+)~',"\\1\\3",preg_replace('~(.+)\n---+\n~',"\\1\n",h($Dh['comment']))));echo'
    +';}elseif(isset($_GET["foreign"])){$a=$_GET["foreign"];$B=$_GET["name"];$K=$_POST;if($_POST&&!$m&&!$_POST["add"]&&!$_POST["change"]&&!$_POST["change-js"]){if(!$_POST["drop"]){$K["source"]=array_filter($K["source"],'strlen');ksort($K["source"]);$Mi=array();foreach($K["source"]as$y=>$X)$Mi[$y]=$K["target"][$y];$K["target"]=$Mi;}if(JUSH=="sqlite")$I=recreate_table($a,$a,array(),array(),array(" $B"=>($K["drop"]?"":" ".format_foreign_key($K))));else{$b="ALTER TABLE ".table($a);$I=($B==""||queries("$b DROP ".(JUSH=="sql"?"FOREIGN KEY ":"CONSTRAINT ").idf_escape($B)));if(!$K["drop"])$I=queries("$b ADD".format_foreign_key($K));}queries_redirect(ME."table=".urlencode($a),($K["drop"]?lang(205):($B!=""?lang(206):lang(207))),$I);if(!$K["drop"])$m=lang(208);}page_header(lang(209),$m,array("table"=>$a),h($a));if($_POST){ksort($K["source"]);if($_POST["add"])$K["source"][]="";elseif($_POST["change"]||$_POST["change-js"])$K["target"]=array();}elseif($B!=""){$md=foreign_keys($a);$K=$md[$B];$K["source"][]="";}else{$K["table"]=$a;$K["source"]=array("");}echo' +
    +';$ji=array_keys(fields($a));if($K["db"]!="")connection()->select_db($K["db"]);if($K["ns"]!=""){$qg=get_schema();set_schema($K["ns"]);}$ph=array_keys(array_filter(table_status('',true),'Adminer\fk_support'));$Mi=array_keys(fields(in_array($K["table"],$ph)?$K["table"]:reset($ph)));$ag="this.form['change-js'].value = '1'; this.form.submit();";echo"

    \n";if(support("scheme")){$Kh=array_filter(adminer()->schemas(),function($Jh){return!preg_match('~^information_schema$~i',$Jh);});echo"";if($K["ns"]!="")set_schema($qg);}elseif(JUSH!="sqlite"){$Sb=array();foreach(adminer()->databases()as$k){if(!information_schema($k))$Sb[]=$k;}echo"";}echo +input_hidden("change-js"),'

    + + +';$_e=0;foreach($K["source"]as$y=>$X){echo"","
    ',lang(143),'',lang(144),'
    ".html_select("source[".(+$y)."]",array(-1=>"")+$ji,$X,($_e==count($K["source"])-1?"foreignAddRow.call(this);":""),"label-source"),"".html_select("target[".(+$y)."]",$Mi,idx($K["target"],$y),"","label-target");$_e++;}echo'

    -ON DELETE: ',html_select("on_delete",array(-1=>"")+explode("|",$Wd),$L["on_delete"]),' ON UPDATE: ',html_select("on_update",array(-1=>"")+explode("|",$Wd),$L["on_update"]),'','

    - -

    -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["view"])){$a=$_GET["view"];$L=$_POST;$me="VIEW";if($y=="pgsql"&&$a!=""){$Mf=table_status($a);$me=strtoupper($Mf["Engine"]);}if($_POST&&!$l){$F=trim($L["name"]);$pa=" AS\n$L[select]";$B=ME."table=".urlencode($F);$D='View has been altered.';$V=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$F&&$y!="sqlite"&&$V=="VIEW"&&$me=="VIEW")query_redirect(($y=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($F).$pa,$B,$D);else{$fg=$F."_adminer_".uniqid();drop_create("DROP $me ".table($a),"CREATE $V ".table($F).$pa,"DROP $V ".table($F),"CREATE $V ".table($fg).$pa,"DROP $V ".table($fg),($_POST["drop"]?substr(ME,0,-1):$B),'View has been dropped.',$D,'View has been created.',$a,$F);}}if(!$_POST&&$a!=""){$L=view($a);$L["name"]=$a;$L["materialized"]=($me!="VIEW");if(!$l)$l=error();}page_header(($a!=""?'Alter view':'Create view'),$l,array("table"=>$a),h($a));echo' + + +',(DRIVER==='pgsql'?html_select("deferrable",array('NOT DEFERRABLE','DEFERRABLE','DEFERRABLE INITIALLY DEFERRED'),$K["deferrable"]).' ':''),doc_link(array('sql'=>"innodb-foreign-key-constraints.html",'mariadb'=>"foreign-keys/",'pgsql'=>"sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES",'mssql'=>"t-sql/statements/create-table-transact-sql",'oracle'=>"SQLRF01111",)),'

    + +

    +';if($B!="")echo'',confirm(lang(184,$B));echo +input_token(),' +';}elseif(isset($_GET["view"])){$a=$_GET["view"];$K=$_POST;$rg="VIEW";if(JUSH=="pgsql"&&$a!=""){$P=table_status1($a);$rg=strtoupper($P["Engine"]);}if($_POST&&!$m){$B=trim($K["name"]);$ya=" AS\n$K[select]";$We=ME."table=".urlencode($B);$qf=lang(213);$U=($_POST["materialized"]?"MATERIALIZED VIEW":"VIEW");if(!$_POST["drop"]&&$a==$B&&JUSH!="sqlite"&&$U=="VIEW"&&$rg=="VIEW")query_redirect((JUSH=="mssql"?"ALTER":"CREATE OR REPLACE")." VIEW ".table($B).$ya,$We,$qf);else{$Oi=$B."_adminer_".uniqid();drop_create("DROP $rg ".table($a),"CREATE $U ".table($B).$ya,"DROP $U ".table($B),"CREATE $U ".table($Oi).$ya,"DROP $U ".table($Oi),($_POST["drop"]?substr(ME,0,-1):$We),lang(214),$qf,lang(215),$a,$B);}}if(!$_POST&&$a!=""){$K=view($a);$K["name"]=$a;$K["materialized"]=($rg!="VIEW");if(!$m)$m=error();}page_header(($a!=""?lang(44):lang(216)),$m,array("table"=>$a),h($a));echo'

    -

    Name: -',(support("materializedview")?" ".checkbox("materialized",1,$L["materialized"],'Materialized view'):""),'

    ';textarea("select",$L["select"]);echo'

    - -';if($a!=""){echo'',confirm(sprintf('Drop %s?',$a));}echo' -

    -';}elseif(isset($_GET["trigger"])){$a=$_GET["trigger"];$F=$_GET["name"];$_g=trigger_options();$L=(array)trigger($F,$a)+array("Trigger"=>$a."_bi");if($_POST){if(!$l&&in_array($_POST["Timing"],$_g["Timing"])&&in_array($_POST["Event"],$_g["Event"])&&in_array($_POST["Type"],$_g["Type"])){$Vd=" ON ".table($a);$_b="DROP TRIGGER ".idf_escape($F).($y=="pgsql"?$Vd:"");$B=ME."table=".urlencode($a);if($_POST["drop"])query_redirect($_b,$B,'Trigger has been dropped.');else{if($F!="")queries($_b);queries_redirect($B,($F!=""?'Trigger has been altered.':'Trigger has been created.'),queries(create_trigger($Vd,$_POST)));if($F!="")queries(create_trigger($Vd,$L+array("Type"=>reset($_g["Type"]))));}}$L=$_POST;}page_header(($F!=""?'Alter trigger'.": ".h($F):'Create trigger'),$l,array("table"=>$a));echo' +

    ',lang(194),': +',(support("materializedview")?" ".checkbox("materialized",1,$K["materialized"],lang(137)):""),'

    ';textarea("select",$K["select"]);echo'

    + +';if($a!="")echo'',confirm(lang(184,$a));echo +input_token(),' +';}elseif(isset($_GET["event"])){$aa=$_GET["event"];$re=array("YEAR","QUARTER","MONTH","DAY","HOUR","MINUTE","WEEK","SECOND","YEAR_MONTH","DAY_HOUR","DAY_MINUTE","DAY_SECOND","HOUR_MINUTE","HOUR_SECOND","MINUTE_SECOND");$ti=array("ENABLED"=>"ENABLE","DISABLED"=>"DISABLE","SLAVESIDE_DISABLED"=>"DISABLE ON SLAVE");$K=$_POST;if($_POST&&!$m){if($_POST["drop"])query_redirect("DROP EVENT ".idf_escape($aa),substr(ME,0,-1),lang(217));elseif(in_array($K["INTERVAL_FIELD"],$re)&&isset($ti[$K["STATUS"]])){$Ih="\nON SCHEDULE ".($K["INTERVAL_VALUE"]?"EVERY ".q($K["INTERVAL_VALUE"])." $K[INTERVAL_FIELD]".($K["STARTS"]?" STARTS ".q($K["STARTS"]):"").($K["ENDS"]?" ENDS ".q($K["ENDS"]):""):"AT ".q($K["STARTS"]))." ON COMPLETION".($K["ON_COMPLETION"]?"":" NOT")." PRESERVE";queries_redirect(substr(ME,0,-1),($aa!=""?lang(218):lang(219)),queries(($aa!=""?"ALTER EVENT ".idf_escape($aa).$Ih.($aa!=$K["EVENT_NAME"]?"\nRENAME TO ".idf_escape($K["EVENT_NAME"]):""):"CREATE EVENT ".idf_escape($K["EVENT_NAME"]).$Ih)."\n".$ti[$K["STATUS"]]." COMMENT ".q($K["EVENT_COMMENT"]).rtrim(" DO\n$K[EVENT_DEFINITION]",";").";"));}}page_header(($aa!=""?lang(220).": ".h($aa):lang(221)),$m);if(!$K&&$aa!=""){$L=get_rows("SELECT * FROM information_schema.EVENTS WHERE EVENT_SCHEMA = ".q(DB)." AND EVENT_NAME = ".q($aa));$K=reset($L);}echo' +

    + +
    ',lang(194),' +
    ',lang(222),' +
    ',lang(223),' +
    ',lang(224),' ',html_select("INTERVAL_FIELD",$re,$K["INTERVAL_FIELD"]),'
    ',lang(124),'',html_select("STATUS",$ti,$K["STATUS"]),'
    ',lang(51),' +
    ',checkbox("ON_COMPLETION","PRESERVE",$K["ON_COMPLETION"]=="PRESERVE",lang(225)),'
    +

    ';textarea("EVENT_DEFINITION",$K["EVENT_DEFINITION"]);echo'

    + +';if($aa!="")echo'',confirm(lang(184,$aa));echo +input_token(),'

    +';}elseif(isset($_GET["procedure"])){$ca=($_GET["name"]?:$_GET["procedure"]);$Dh=(isset($_GET["function"])?"FUNCTION":"PROCEDURE");$K=$_POST;$K["fields"]=(array)$K["fields"];if($_POST&&!process_fields($K["fields"])&&!$m){$ng=routine($_GET["procedure"],$Dh);$Oi="$K[name]_adminer_".uniqid();foreach($K["fields"]as$y=>$n){if($n["field"]=="")unset($K["fields"][$y]);}drop_create("DROP $Dh ".routine_id($ca,$ng),create_routine($Dh,$K),"DROP $Dh ".routine_id($K["name"],$K),create_routine($Dh,array("name"=>$Oi)+$K),"DROP $Dh ".routine_id($Oi,$K),substr(ME,0,-1),lang(226),lang(227),lang(228),$ca,$K["name"]);}page_header(($ca!=""?(isset($_GET["function"])?lang(229):lang(230)).": ".h($ca):(isset($_GET["function"])?lang(231):lang(232))),$m);if(!$_POST){if($ca=="")$K["language"]="sql";else{$K=routine($_GET["procedure"],$Dh);$K["name"]=$ca;}}$lb=get_vals("SHOW CHARACTER SET");sort($lb);$Eh=routine_languages();echo($lb?"".optionlist($lb)."":""),'
    - -
    Time',html_select("Timing",$_g["Timing"],$L["Timing"],"triggerChange(/^".preg_quote($a,"/")."_[ba][iud]$/, '".js_escape($a)."', this.form);"),'
    Event',html_select("Event",$_g["Event"],$L["Event"],"this.form['Timing'].onchange();"),(in_array("UPDATE OF",$_g["Event"])?" ":""),'
    Type',html_select("Type",$_g["Type"],$L["Type"]),'
    -

    Name: -',script("qs('#form')['Timing'].onchange();"),'

    ';textarea("Statement",$L["Statement"]);echo'

    - -';if($F!=""){echo'',confirm(sprintf('Drop %s?',$F));}echo' -

    -';}elseif(isset($_GET["select"])){$a=$_GET["select"];$S=table_status1($a);$x=indexes($a);$n=fields($a);$q=column_foreign_keys($a);$Td=$S["Oid"];parse_str($_COOKIE["adminer_import"],$ja);$lf=array();$e=array();$ig=null;foreach($n -as$z=>$m){$F=$b->fieldName($m);if(isset($m["privileges"]["select"])&&$F!=""){$e[$z]=html_entity_decode(strip_tags($F),ENT_QUOTES);if(is_shortable($m))$ig=$b->selectLengthProcess();}$lf+=$m["privileges"];}list($N,$t)=$b->selectColumnsProcess($e,$x);$Wc=count($t)selectSearchProcess($n,$x);$fe=$b->selectOrderProcess($n,$x);$_=$b->selectLimitProcess();if($_GET["val"]&&is_ajax()){header("Content-Type: text/plain; charset=utf-8");foreach($_GET["val"]as$Gg=>$L){$pa=convert_field($n[key($L)]);$N=array($pa?$pa:idf_escape(key($L)));$Z[]=where_check($Gg,$n);$K=$k->select($a,$N,$Z,$N);if($K)echo -reset($K->fetch_row());}exit;}$Oe=$Ig=null;foreach($x -as$w){if($w["type"]=="PRIMARY"){$Oe=array_flip($w["columns"]);$Ig=($N?$Oe:array());foreach($Ig -as$z=>$X){if(in_array(idf_escape($z),$N))unset($Ig[$z]);}break;}}if($Td&&!$Oe){$Oe=$Ig=array($Td=>0);$x[]=array("type"=>"PRIMARY","columns"=>array($Td));}if($_POST&&!$l){$fh=$Z;if(!$_POST["all"]&&is_array($_POST["check"])){$Ga=array();foreach($_POST["check"]as$Ea)$Ga[]=where_check($Ea,$n);$fh[]="((".implode(") OR (",$Ga)."))";}$fh=($fh?"\nWHERE ".implode(" AND ",$fh):"");if($_POST["export"]){cookie("adminer_import","output=".urlencode($_POST["output"])."&format=".urlencode($_POST["format"]));dump_headers($a);$b->dumpTable($a,"");$tc=($N?implode(", ",$N):"*").convert_fields($e,$n,$N)."\nFROM ".table($a);$xc=($t&&$Wc?"\nGROUP BY ".implode(", ",$t):"").($fe?"\nORDER BY ".implode(", ",$fe):"");if(!is_array($_POST["check"])||$Oe)$I="SELECT $tc$fh$xc";else{$Eg=array();foreach($_POST["check"]as$X)$Eg[]="(SELECT".limit($tc,"\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n).$xc,1).")";$I=implode(" UNION ALL ",$Eg);}$b->dumpData($a,"table",$I);exit;}if(!$b->selectEmailProcess($Z,$q)){if($_POST["save"]||$_POST["delete"]){$J=true;$ka=0;$P=array();if(!$_POST["delete"]){foreach($e -as$F=>$X){$X=process_input($n[$F]);if($X!==null&&($_POST["clone"]||$X!==false))$P[idf_escape($F)]=($X!==false?$X:idf_escape($F));}}if($_POST["delete"]||$P){if($_POST["clone"])$I="INTO ".table($a)." (".implode(", ",array_keys($P)).")\nSELECT ".implode(", ",$P)."\nFROM ".table($a);if($_POST["all"]||($Oe&&is_array($_POST["check"]))||$Wc){$J=($_POST["delete"]?$k->delete($a,$fh):($_POST["clone"]?queries("INSERT $I$fh"):$k->update($a,$P,$fh)));$ka=$f->affected_rows;}else{foreach((array)$_POST["check"]as$X){$eh="\nWHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($X,$n);$J=($_POST["delete"]?$k->delete($a,$eh,1):($_POST["clone"]?queries("INSERT".limit1($a,$I,$eh)):$k->update($a,$P,$eh,1)));if(!$J)break;$ka+=$f->affected_rows;}}}$D=lang(array('%d item has been affected.','%d items have been affected.'),$ka);if($_POST["clone"]&&$J&&$ka==1){$id=last_id();if($id)$D=sprintf('Item%s has been inserted.'," $id");}queries_redirect(remove_from_uri($_POST["all"]&&$_POST["delete"]?"page":""),$D,$J);if(!$_POST["delete"]){edit_form($a,$n,(array)$_POST["fields"],!$_POST["clone"]);page_footer();exit;}}elseif(!$_POST["import"]){if(!$_POST["val"])$l='Ctrl+click on a value to modify it.';else{$J=true;$ka=0;foreach($_POST["val"]as$Gg=>$L){$P=array();foreach($L -as$z=>$X){$z=bracket_escape($z,1);$P[idf_escape($z)]=(preg_match('~char|text~',$n[$z]["type"])||$X!=""?$b->processInput($n[$z],$X):"NULL");}$J=$k->update($a,$P," WHERE ".($Z?implode(" AND ",$Z)." AND ":"").where_check($Gg,$n),!$Wc&&!$Oe," ");if(!$J)break;$ka+=$f->affected_rows;}queries_redirect(remove_from_uri(),lang(array('%d item has been affected.','%d items have been affected.'),$ka),$J);}}elseif(!is_string($jc=get_file("csv_file",true)))$l=upload_error($jc);elseif(!preg_match('~~u',$jc))$l='File must be in UTF-8 encoding.';else{cookie("adminer_import","output=".urlencode($ja["output"])."&format=".urlencode($_POST["separator"]));$J=true;$Qa=array_keys($n);preg_match_all('~(?>"[^"]*"|[^"\r\n]+)+~',$jc,$ud);$ka=count($ud[0]);$k->begin();$xf=($_POST["separator"]=="csv"?",":($_POST["separator"]=="tsv"?"\t":";"));$M=array();foreach($ud[0]as$z=>$X){preg_match_all("~((?>\"[^\"]*\")+|[^$xf]*)$xf~",$X.$xf,$vd);if(!$z&&!array_diff($vd[1],$Qa)){$Qa=$vd[1];$ka--;}else{$P=array();foreach($vd[1]as$u=>$Ma)$P[idf_escape($Qa[$u])]=($Ma==""&&$n[$Qa[$u]]["null"]?"NULL":q(str_replace('""','"',preg_replace('~^"|"$~','',$Ma))));$M[]=$P;}}$J=(!$M||$k->insertUpdate($a,$M,$Oe));if($J)$J=$k->commit();queries_redirect(remove_from_uri("page"),lang(array('%d row has been imported.','%d rows have been imported.'),$ka),$J);$k->rollback();}}}$Wf=$b->tableName($S);if(is_ajax()){page_headers();ob_start();}else -page_header('Select'.": $Wf",$l);$P=null;if(isset($lf["insert"])||!support("table")){$P="";foreach((array)$_GET["where"]as$X){if($q[$X["col"]]&&count($q[$X["col"]])==1&&($X["op"]=="="||(!$X["op"]&&!preg_match('~[_%]~',$X["val"]))))$P.="&set".urlencode("[".bracket_escape($X["col"])."]")."=".urlencode($X["val"]);}}$b->selectLinks($S,$P);if(!$e&&support("table"))echo"

    ".'Unable to select the table'.($n?".":": ".error())."\n";else{echo"

    \n","
    ";hidden_fields_get();echo(DB!=""?''.(isset($_GET["ns"])?'':""):"");echo'',"
    \n";$b->selectColumnsPrint($N,$e);$b->selectSearchPrint($Z,$e,$x);$b->selectOrderPrint($fe,$e,$x);$b->selectLimitPrint($_);$b->selectLengthPrint($ig);$b->selectActionPrint($x);echo"
    \n";$G=$_GET["page"];if($G=="last"){$sc=$f->result(count_rows($a,$Z,$Wc,$t));$G=floor(max(0,$sc-1)/$_);}$sf=$N;$wc=$t;if(!$sf){$sf[]="*";$ab=convert_fields($e,$n,$N);if($ab)$sf[]=substr($ab,2);}foreach($N -as$z=>$X){$m=$n[idf_unescape($X)];if($m&&($pa=convert_field($m)))$sf[$z]="$pa AS $X";}if(!$Wc&&$Ig){foreach($Ig -as$z=>$X){$sf[]=idf_escape($z);if($wc)$wc[]=idf_escape($z);}}$J=$k->select($a,$sf,$Z,$wc,$fe,$_,$G,true);if(!$J)echo"

    ".error()."\n";else{if($y=="mssql"&&$G)$J->seek($_*$G);$Mb=array();echo"

    \n";$M=array();while($L=$J->fetch_assoc()){if($G&&$y=="oracle")unset($L["RNUM"]);$M[]=$L;}if($_GET["page"]!="last"&&$_!=""&&$t&&$Wc&&$y=="sql")$sc=$f->result(" SELECT FOUND_ROWS()");if(!$M)echo"

    ".'No rows.'."\n";else{$wa=$b->backwardKeys($a,$Wf);echo"

    ","",script("mixin(qs('#table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true), onkeydown: editingKeydown});"),"".(!$t&&$N?"":"\n";if(is_ajax()){if($_%2==1&&$G%2==1)odd();ob_end_clean();}foreach($b->rowDescriptions($M,$q)as$E=>$L){$Fg=unique_array($M[$E],$x);if(!$Fg){$Fg=array();foreach($M[$E]as$z=>$X){if(!preg_match('~^(COUNT\((\*|(DISTINCT )?`(?:[^`]|``)+`)\)|(AVG|GROUP_CONCAT|MAX|MIN|SUM)\(`(?:[^`]|``)+`\))$~',$z))$Fg[$z]=$X;}}$Gg="";foreach($Fg -as$z=>$X){if(($y=="sql"||$y=="pgsql")&&preg_match('~char|text|enum|set~',$n[$z]["type"])&&strlen($X)>64){$z=(strpos($z,'(')?$z:idf_escape($z));$z="MD5(".($y!='sql'||preg_match("~^utf8~",$n[$z]["collation"])?$z:"CONVERT($z USING ".charset($f).")").")";$X=md5($X);}$Gg.="&".($X!==null?urlencode("where[".bracket_escape($z)."]")."=".urlencode($X):"null%5B%5D=".urlencode($z));}echo"".(!$t&&$N?"":"";}}}if($wa)echo"\n";}if(is_ajax())exit;echo"
    ".script("qs('#all-page').onclick = partial(formCheck, /check/);","")." ".'Modify'."");$Kd=array();$uc=array();reset($N);$af=1;foreach($M[0]as$z=>$X){if(!isset($Ig[$z])){$X=$_GET["columns"][key($N)];$m=$n[$N?($X?$X["col"]:current($N)):$z];$F=($m?$b->fieldName($m,$af):($X["fun"]?"*":$z));if($F!=""){$af++;$Kd[$z]=$F;$d=idf_escape($z);$Ic=remove_from_uri('(order|desc)[^=]*|page').'&order%5B0%5D='.urlencode($z);$sb="&desc%5B0%5D=1";echo"".script("mixin(qsl('th'), {onmouseover: partial(columnMouse), onmouseout: partial(columnMouse, ' hidden')});",""),'';echo -apply_sql_function($X["fun"],$F)."";echo"";}$uc[$z]=$X["fun"];next($N);}}$od=array();if($_GET["modify"]){foreach($M -as$L){foreach($L -as$z=>$X)$od[$z]=max($od[$z],min(40,strlen(utf8_decode($X))));}}echo($wa?"".'Relations':"")."
    ".checkbox("check[]",substr($Gg,1),in_array(substr($Gg,1),(array)$_POST["check"])).($Wc||information_schema(DB)?"":" ".'edit'.""));foreach($L -as$z=>$X){if(isset($Kd[$z])){$m=$n[$z];$X=$k->value($X,$m);if($X!=""&&(!isset($Mb[$z])||$Mb[$z]!=""))$Mb[$z]=(is_mail($X)?$Kd[$z]:"");$A="";if(preg_match('~blob|bytea|raw|file~',$m["type"])&&$X!="")$A=ME.'download='.urlencode($a).'&field='.urlencode($z).$Gg;if(!$A&&$X!==null){foreach((array)$q[$z]as$p){if(count($q[$z])==1||end($p["source"])==$z){$A="";foreach($p["source"]as$u=>$Ff)$A.=where_link($u,$p["target"][$u],$M[$E][$Ff]);$A=($p["db"]!=""?preg_replace('~([?&]db=)[^&]+~','\1'.urlencode($p["db"]),ME):ME).'select='.urlencode($p["table"]).$A;if($p["ns"])$A=preg_replace('~([?&]ns=)[^&]+~','\1'.urlencode($p["ns"]),$A);if(count($p["source"])==1)break;}}}if($z=="COUNT(*)"){$A=ME."select=".urlencode($a);$u=0;foreach((array)$_GET["where"]as$W){if(!array_key_exists($W["col"],$Fg))$A.=where_link($u++,$W["col"],$W["val"],$W["op"]);}foreach($Fg -as$ad=>$W)$A.=where_link($u++,$ad,$W);}$X=select_value($X,$A,$m,$ig);$v=h("val[$Gg][".bracket_escape($z)."]");$Y=$_POST["val"][$Gg][bracket_escape($z)];$Hb=!is_array($L[$z])&&is_utf8($X)&&$M[$E][$z]==$L[$z]&&!$uc[$z];$hg=preg_match('~text|lob~',$m["type"]);echo"".($hg?"":"");}else{$sd=strpos($X,"…");echo" data-text='".($sd?2:($hg?1:0))."'".($Hb?"":" data-warning='".h('Use edit link to modify this value.')."'").">$X";$b->backwardKeysPrint($wa,$M[$E]);echo"
    \n","
    \n";}if(!is_ajax()){if($M||$G){$Wb=true;if($_GET["page"]!="last"){if($_==""||(count($M)<$_&&($M||!$G)))$sc=($G?$G*$_:0)+count($M);elseif($y!="sql"||!$Wc){$sc=($Wc?false:found_rows($S,$Z));if($sc$_||$G));if($se){echo(($sc===false?count($M)+1:$sc-$G*$_)>$_?'

    '.'Load more data'.''.script("qsl('a').onclick = partial(selectLoadMore, ".(+$_).", '".'Loading'."…');",""):''),"\n";}}echo"

    \n";}if(adminer()->selectImportPrint())echo"

    ","".lang(76)."",script("qsl('a').onclick = partial(toggle, 'import');",""),"";echo +input_token(),"\n",(!$xd&&$M?"":script("tableCheck();"));}}}if(is_ajax()){ob_end_clean();exit;}}elseif(isset($_GET["variables"])){$P=isset($_GET["status"]);page_header($P?lang(124):lang(123));$Oj=($P?adminer()->showStatus():adminer()->showVariables());if(!$Oj)echo"

    ".lang(14)."\n";else{echo"\n";foreach($Oj +as$K){echo"";$y=array_shift($K);echo"
    ".h($y)."";foreach($K +as$X)echo"".nl_br(h($X));}echo"
    \n";}}elseif(isset($_GET["script"])){header("Content-Type: text/javascript; charset=utf-8");if($_GET["script"]=="db"){$_i=array("Data_length"=>0,"Index_length"=>0,"Data_free"=>0);foreach(table_status()as$B=>$S){json_row("Comment-$B",h($S["Comment"]));if(!is_view($S)||preg_match('~materialized~i',$S["Engine"])){foreach(array("Engine","Collation")as$y)json_row("$y-$B",h($S[$y]));foreach($_i+array("Auto_increment"=>0,"Rows"=>0)as$y=>$X){if($S[$y]!=""){$X=format_number($S[$y]);if($X>=0)json_row("$y-$B",($y=="Rows"&&$X&&$S["Engine"]==(JUSH=="pgsql"?"table":"InnoDB")?"~ $X":$X));if(isset($_i[$y]))$_i[$y]+=($S["Engine"]!="InnoDB"||$y!="Data_free"?$S[$y]:0);}elseif(array_key_exists($y,$S))json_row("$y-$B","?");}}}foreach($_i +as$y=>$X)json_row("sum-$y",format_number($X));json_row("");}elseif($_GET["script"]=="kill")connection()->query("KILL ".number($_POST["kill"]));else{foreach(count_tables(adminer()->databases())as$k=>$X){json_row("tables-$k",$X);json_row("size-$k",db_size($k));}json_row("");}exit;}else{$Ki=array_merge((array)$_POST["tables"],(array)$_POST["views"]);if($Ki&&!$m&&!$_POST["search"]){$I=true;$qf="";if(JUSH=="sql"&&$_POST["tables"]&&count($_POST["tables"])>1&&($_POST["drop"]||$_POST["truncate"]||$_POST["copy"]))queries("SET foreign_key_checks = 0");if($_POST["truncate"]){if($_POST["tables"])$I=truncate_tables($_POST["tables"]);$qf=lang(279);}elseif($_POST["move"]){$I=move_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(280);}elseif($_POST["copy"]){$I=copy_tables((array)$_POST["tables"],(array)$_POST["views"],$_POST["target"]);$qf=lang(281);}elseif($_POST["drop"]){if($_POST["views"])$I=drop_views($_POST["views"]);if($I&&$_POST["tables"])$I=drop_tables($_POST["tables"]);$qf=lang(282);}elseif(JUSH=="sqlite"&&$_POST["check"]){foreach((array)$_POST["tables"]as$R){foreach(get_rows("PRAGMA integrity_check(".q($R).")")as$K)$qf +.="".h($R).": ".h($K["integrity_check"])."
    ";}}elseif(JUSH!="sql"){$I=(JUSH=="sqlite"?queries("VACUUM"):apply_queries("VACUUM".($_POST["optimize"]?"":" ANALYZE"),$_POST["tables"]));$qf=lang(283);}elseif(!$_POST["tables"])$qf=lang(11);elseif($I=queries(($_POST["optimize"]?"OPTIMIZE":($_POST["check"]?"CHECK":($_POST["repair"]?"REPAIR":"ANALYZE")))." TABLE ".implode(", ",array_map('Adminer\idf_escape',$_POST["tables"])))){while($K=$I->fetch_assoc())$qf +.="".h($K["Table"]).": ".h($K["Msg_text"])."
    ";}queries_redirect(substr(ME,0,-1),$qf,$I);}page_header(($_GET["ns"]==""?lang(38).": ".h(DB):lang(80).": ".h($_GET["ns"])),$m,true);if(adminer()->homepage()){if($_GET["ns"]!==""){echo"

    ".lang(284)."

    \n";$Ji=tables_list();if(!$Ji)echo"

    ".lang(11)."\n";else{echo"

    \n";if(support("table")){echo"
    ".lang(285)."
    ",html_select("op",adminer()->operators(),idx($_POST,"op",JUSH=="elastic"?"should":"LIKE %%"))," ",script("qsl('input').onkeydown = partialArg(bodyKeydown, 'search');","")," \n","
    \n";if($_POST["search"]&&$_POST["query"]!=""){$_GET["where"][0]["op"]=$_POST["op"];search_tables();}}echo"
    \n","\n",script("mixin(qsl('table'), {onclick: tableClick, ondblclick: partialArg(tableClick, true)});"),'','\n";$T=0;foreach($Ji +as$B=>$U){$Rj=($U!==null&&!preg_match('~table|sequence~i',$U));$u=h("Table-".$B);echo'
    '.script("qs('#check-all').onclick = partial(formCheck, /^(tables|views)\[/);",""),''.lang(139);$e=array("Engine"=>array(lang(286).doc_link(array('sql'=>'storage-engines.html'))));if(collations())$e["Collation"]=array(lang(128).doc_link(array('sql'=>'charset-charsets.html','mariadb'=>'supported-character-sets-and-collations/')));if(function_exists('Adminer\alter_table'))$e["Data_length"]=array(lang(287).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT','oracle'=>'REFRN20286')),"create",lang(45));if(support('indexes'))$e["Index_length"]=array(lang(288).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-admin.html#FUNCTIONS-ADMIN-DBOBJECT')),"indexes",lang(142));$e["Data_free"]=array(lang(289).doc_link(array('sql'=>'show-table-status.html')),"edit",lang(46));if(function_exists('Adminer\alter_table'))$e["Auto_increment"]=array(lang(52).doc_link(array('sql'=>'example-auto-increment.html','mariadb'=>'auto_increment/')),"auto_increment=1&create",lang(45));$e["Rows"]=array(lang(290).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'catalog-pg-class.html#CATALOG-PG-CLASS','oracle'=>'REFRN20286')),"select",lang(42));if(support("comment"))$e["Comment"]=array(lang(51).doc_link(array('sql'=>'show-table-status.html','pgsql'=>'functions-info.html#FUNCTIONS-INFO-COMMENT-TABLE')));foreach($e +as$d)echo"$d[0]";echo"
    '.checkbox(($Rj?"views[]":"tables[]"),$B,in_array("$B",$Ki,true),"","","",$u),''.(support("table")||support("indexes")?"".h($B).'':h($B));if($Rj&&!preg_match('~materialized~i',$U)){$Wi=lang(138);echo''.(support("view")?"$Wi":$Wi),'?';}else{foreach($e +as$y=>$d){$u=" id='$y-".h($B)."'";echo($d[1]?"?":"");}$T++;}echo"\n";}echo"
    ".lang(263,count($Ji)),"".h(JUSH=="sql"?get_val("SELECT @@default_storage_engine"):""),"".h(db_collation(DB,collations()));foreach(array("Data_length","Index_length","Data_free")as$y)echo($e[$y]?"":"");echo"\n","
    \n",script("ajaxSetHtml('".js_escape(ME)."script=db');"),"
    \n";if(!information_schema(DB)){$Lj=" ".on_help("'VACUUM'");$eg=" ".on_help(JUSH=="sql"?"'OPTIMIZE TABLE'":"'VACUUM OPTIMIZE'");$bh=(JUSH=="sqlite"?$Lj." ".on_help("'PRAGMA integrity_check'"):(JUSH=="pgsql"?$Lj.$eg:(JUSH=="sql"?" ".on_help("'ANALYZE TABLE'").$eg." ".on_help("'CHECK TABLE'")." ".on_help("'REPAIR TABLE'"):""))).(function_exists('Adminer\truncate_tables')?" ".on_help(JUSH=="sqlite"?"'DELETE'":"'TRUNCATE".(JUSH=="pgsql"?"'":" TABLE'")).confirm():"").(function_exists('Adminer\drop_tables')?"".on_help("'DROP TABLE'").confirm():"");echo($bh?"\n";}echo"
    \n",script("tableCheck();");}echo(function_exists('Adminer\alter_table')?"

    ".lang(73)."

    \n";$Fh=routines();if($Fh){echo"\n",'\n";foreach($Fh +as$K){$B=($K["SPECIFIC_NAME"]==$K["ROUTINE_NAME"]?"":"&name=".urlencode($K["ROUTINE_NAME"]));echo'','
    '.lang(194).''.lang(50).''.lang(233)."
    '.h($K["ROUTINE_NAME"]).'',''.h($K["ROUTINE_TYPE"]),''.h($K["DTD_IDENTIFIER"]),''.lang(145)."";}echo"
    \n";}echo'

    ".lang(74)."

    \n";$Yh=get_vals("SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = current_schema() ORDER BY sequence_name");if($Yh){echo"\n","\n";foreach($Yh +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(6)."

    \n";$Ij=types();if($Ij){echo"\n","\n";foreach($Ij +as$X)echo"
    ".lang(194)."
    ".h($X)."\n";echo"
    \n";}echo"

    ".lang(75)."

    \n";$L=get_rows("SHOW EVENTS");if($L){echo"\n","\n";foreach($L +as$K)echo"","
    ".lang(194)."".lang(301)."".lang(222)."".lang(223)."
    ".h($K["Name"]),"".($K["Execute at"]?lang(302)."".$K["Execute at"]:lang(224)." ".$K["Interval value"]." ".$K["Interval field"]."$K[Starts]"),"$K[Ends]",''.lang(145).'';echo"
    \n";$Hc=get_val("SELECT @@event_scheduler");if($Hc&&$Hc!="ON")echo"

    event_scheduler: ".h($Hc)."\n";}echo'

    ".$ret."
    "; fclose($temp_conf); diff --git a/scripts/history.php b/scripts/history.php index 48455bae9a..fd938ebec4 100644 --- a/scripts/history.php +++ b/scripts/history.php @@ -1,8 +1,8 @@ busyTimeout(1000); $statement1 = $db_writable->prepare('DELETE FROM detections WHERE File_Name = :file_name LIMIT 1'); ensure_db_ok($statement1); - $statement1->bindValue(':file_name', explode("/", $_GET['deletefile'])[2]); - $file_pointer = $home."/BirdSongs/Extracted/By_Date/".$_GET['deletefile']; - if (!exec("sudo rm $file_pointer 2>&1 && sudo rm $file_pointer.png 2>&1", $output)) { + $statement1->bindValue(':file_name', basename($deletefile)); + $file_pointer = $home."/BirdSongs/Extracted/By_Date/".$deletefile; + $output = []; + $return_code = 0; + exec("sudo rm -f " . escapeshellarg($file_pointer) . " 2>&1", $output, $return_code); + exec("sudo rm -f " . escapeshellarg($file_pointer . '.png') . " 2>&1", $output, $return_code_png); + if ($return_code === 0 && $return_code_png === 0) { echo "OK"; } else { echo "Error - file deletion failed : " . implode(", ", $output) . "
    "; @@ -76,13 +81,20 @@ if(isset($_GET['changefile']) && isset($_GET['newname'])) { ensure_authenticated('You must be authenticated to delete files.'); - if (preg_match('~^.*(\.\.\/).+$~', $_GET['changefile'])) { + $changefile = urldecode($_GET['changefile']); + if ($changefile === '' || str_contains($changefile, "\0") || str_contains($changefile, '..') || str_starts_with($changefile, '/')) { echo "Error"; die(); } - $oldname = basename(urldecode($_GET['changefile'])); + $oldname = basename($changefile); $newname = urldecode($_GET['newname']); - if (!exec("sudo -u ".$user." ".$home."/BirdNET-Pi/scripts/birdnet_changeidentification.sh \"$oldname\" \"$newname\" log_errors 2>&1", $output)) { + $output = []; + $return_code = 0; + $cmd = "sudo -u " . escapeshellarg($user) . " " . + escapeshellarg($home . "/BirdNET-Pi/scripts/birdnet_changeidentification.sh") . " " . + escapeshellarg($oldname) . " " . escapeshellarg($newname) . " log_errors 2>&1"; + exec($cmd, $output, $return_code); + if ($return_code === 0) { echo "OK"; } else { echo "Error : " . implode(", ", $output) . "
    "; diff --git a/scripts/species_tools.php b/scripts/species_tools.php index 3ca70b8799..fbd4121ac3 100644 --- a/scripts/species_tools.php +++ b/scripts/species_tools.php @@ -57,6 +57,14 @@ /* ---------- helpers ---------- */ function join_path(...$parts): string { return preg_replace('#/+#', '/', implode('/', $parts)); } function can_unlink(string $p): bool { return is_link($p) || is_file($p); } +function is_within_path(string $path, string $base): bool { + $real = realpath($path); + if ($real === false) { + return false; + } + return str_starts_with($real . DIRECTORY_SEPARATOR, rtrim($base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) + || $real === rtrim($base, DIRECTORY_SEPARATOR); +} /* Collect files/dirs for a species */ function collect_species_targets(SQLite3 $db, string $species, string $home, $base): array { @@ -121,10 +129,22 @@ function collect_species_targets(SQLite3 $db, string $species, string $home, $ba $species = htmlspecialchars_decode($_GET['delete'], ENT_QUOTES); $info = collect_species_targets($db, $species, $home, $base); $deleted = count($info['files']); + $allowed_base = realpath($home . '/BirdSongs/Extracted/By_Date'); + if ($allowed_base === false) { + http_response_code(500); + exit(json_encode(['error' => 'Delete base directory not found'])); + } foreach ($info['dirs'] as $dir) { - if (exec("sudo rm -r $dir 2>&1", $output)) { - echo "Error - files deletion failed : " . implode(", ", $output) . "
    "; - exit; + if (!is_within_path($dir, $allowed_base)) { + http_response_code(400); + exit(json_encode(['error' => 'Invalid delete target'])); + } + $output = []; + $return_code = 0; + exec("sudo rm -r " . escapeshellarg($dir) . " 2>&1", $output, $return_code); + if ($return_code !== 0) { + http_response_code(500); + exit(json_encode(['error' => 'files deletion failed', 'details' => implode(", ", $output)])); } } $del = $db->prepare('DELETE FROM detections WHERE Sci_Name = :name'); diff --git a/scripts/stats.php b/scripts/stats.php index b3f536dfd7..2d6c576b4a 100644 --- a/scripts/stats.php +++ b/scripts/stats.php @@ -1,8 +1,8 @@ Date: Thu, 16 Jul 2026 09:22:32 -0700 Subject: [PATCH 2/7] Fix PHP 7.4 fatal in hardening guards; cache label file and DB handle P1 - the path-validation guards added by the security hardening used str_contains()/str_starts_with(), which are PHP 8.0+. Debian 11 ships PHP 7.4, so every guarded path (delete, rename, species-delete) died with "Call to undefined function str_contains()". Add function_exists-guarded polyfills in common.php (loaded by both call sites) so the guards run on 7.4 and stay correct on 8+. P2 - performance on the Pi 3: - get_com_en_name() and get_db() tested `isset()` on a plain local, so the guard was always false: the ~331KB labels_en.json was re-read and re-decoded, and a new SQLite handle opened, on every call - i.e. once per rendered detection row. Make both `static`. - stats.php drained one SQLite3Result cursor at :61 then iterated it again at :197 with no reset(), so the second loop never ran: the Best Recordings table always rendered empty and $excludelines stayed empty, rewriting disk_check_exclude.txt with an empty block on every page view. - birdnet_analysis join()ed the report queue before every put(), forcing analysis and reporting to run strictly serially. Bound the queue instead (maxsize=1): identical backpressure, but the next chunk's inference can overlap the previous chunk's reporting. Verified on the target: php -l clean on PHP 7.4.33, polyfill semantics match PHP 8, py_compile clean. --- scripts/birdnet_analysis.py | 12 +++++++----- scripts/common.php | 32 +++++++++++++++++++++++++++----- scripts/stats.php | 3 +++ 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/scripts/birdnet_analysis.py b/scripts/birdnet_analysis.py index ec805286cc..807871be40 100644 --- a/scripts/birdnet_analysis.py +++ b/scripts/birdnet_analysis.py @@ -36,7 +36,10 @@ def main(): backlog = get_wav_files() - report_queue = Queue() + # maxsize bounds the queue so reporting cannot fall behind: put() blocks once + # a chunk is already waiting. This replaces an explicit join() per file, which + # forced analysis and reporting to run strictly serially. + report_queue = Queue(maxsize=1) thread = threading.Thread(target=handle_reporting_queue, args=(report_queue, )) thread.start() @@ -90,10 +93,9 @@ def process_file(file_name, report_queue): analyzing.write(file_name) file = ParseFileName(file_name) detections = run_analysis(file) - # we join() to make sure te reporting queue does not get behind - if not report_queue.empty(): - log.warning('reporting queue not yet empty') - report_queue.join() + # The queue is bounded (maxsize=1), so this blocks only if reporting is a + # full chunk behind - same guarantee the old join() gave, but the next + # chunk's inference can overlap this chunk's reporting. report_queue.put((file, detections)) except BaseException as e: stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" diff --git a/scripts/common.php b/scripts/common.php index 4d0fc2a47d..9e8f311972 100644 --- a/scripts/common.php +++ b/scripts/common.php @@ -2,6 +2,24 @@ define('__ROOT__', dirname(dirname(__FILE__))); +/* PHP 8 string helpers, polyfilled for PHP 7.4 (Debian 11 ships 7.4). + Guarded so this stays correct if/when the host moves to PHP 8+. */ +if (!function_exists('str_contains')) { + function str_contains($haystack, $needle) { + return $needle === '' || strpos($haystack, $needle) !== false; + } +} +if (!function_exists('str_starts_with')) { + function str_starts_with($haystack, $needle) { + return strncmp($haystack, $needle, strlen($needle)) === 0; + } +} +if (!function_exists('str_ends_with')) { + function str_ends_with($haystack, $needle) { + return $needle === '' || substr($haystack, -strlen($needle)) === $needle; + } +} + if (session_status() !== PHP_SESSION_ACTIVE) session_start(); @@ -92,11 +110,13 @@ function debug_log($message) { } function get_com_en_name($sci_name) { - if (!isset($_labels_flickr)) { - $_labels_flickr = json_decode(file_get_contents(get_home() . "/BirdNET-Pi/model/l18n/labels_en.json"), true); + /* static: the label file is ~331KB. Without it the cache never survives the + call and we re-read + re-decode it once per detection row. */ + static $_labels_flickr = null; + if ($_labels_flickr === null) { + $_labels_flickr = json_decode(file_get_contents(get_home() . "/BirdNET-Pi/model/l18n/labels_en.json"), true) ?: []; } - $engname = $_labels_flickr[$sci_name]; - return $engname; + return $_labels_flickr[$sci_name] ?? null; } function get_label($record, $sort_by, $date=null) { @@ -121,7 +141,9 @@ function get_label($record, $sort_by, $date=null) { } function get_db() { - if (!isset($_db)) { + /* static: otherwise every caller opens its own SQLite handle. */ + static $_db = null; + if ($_db === null) { $_db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READONLY); $_db->busyTimeout(1000); } diff --git a/scripts/stats.php b/scripts/stats.php index 2d6c576b4a..a86ac7382e 100644 --- a/scripts/stats.php +++ b/scripts/stats.php @@ -194,6 +194,9 @@ function setModalText(iter, title, text, authorlink) { reset(); while($results=$result->fetchArray(SQLITE3_ASSOC)) { $comname = preg_replace('/ /', '_', $results['Com_Name']); From 23c810d7537825ce63719187c3c47d50d94673a4 Mon Sep 17 00:00:00 2001 From: hydrospheric0 Date: Thu, 16 Jul 2026 10:20:17 -0700 Subject: [PATCH 3/7] P3: fix resource leaks, silent data loss and copy-paste drift Leaks / correctness (python): - reporting.spectrogram(): os.remove(tmp_file) only ran on the success path, so a sox failure (check=True) or the RuntimeError below leaked the temp PNG. /tmp is a tmpfs, so each leak was RAM on a 1GB box. Wrap in try/finally and use `with Image.open(...)` so the handle closes too. - reporting.write_to_db(): con.close() sat inside the try, leaking a connection per failed attempt, and after 3 failures the loop just fell through - the detection was dropped from the DB while its wav, extraction, spectrogram and BirdDB.txt line all still existed, silently desyncing DB from filesystem. Use contextlib.closing + PRAGMA busy_timeout, catch sqlite3.Error (not BaseException) and raise after the final attempt. - birdnet_analysis: os.remove() was the last statement in both try blocks, so any earlier error stranded the wav forever (nothing else reaps StreamData). Move to finally. process_file only removes when it failed *before* handing the file to the reporting thread, which otherwise owns it. - birdnet_analysis: except BaseException -> except Exception, so KeyboardInterrupt and SystemExit are no longer swallowed at shutdown. - db.get_records(): swallowed the error, slept 2s (retrying nothing, in the analysis critical path) and returned [], which callers cannot distinguish from a real empty result - a DB hiccup silently dropped notifications. Now logs via the logger (not print) and raises. The notification call sites absorb it so a failed count skips only that notification, never the whole detection. - notifications: cache failed image-API lookups, otherwise a down API meant a fresh 10s timeout on every detection of that species. - helpers.ANALYZING_NOW hardcoded ~/BirdSongs, ignoring RECS_DIR; a relocated RECS_DIR made open() raise for every file, which the caller swallowed - analysis stopped while the service still looked healthy. Now derived from RECS_DIR via get_analyzing_now_path(), and spectrogram.sh derives the same path from RECS_DIR so both sides stay in step. Shell: - disk_check.sh: $used was measured once and never recomputed, so the second, more destructive purge (rm -rf $PROCESSED) fired unconditionally whenever the first did - the sleep 1 between them shows re-measuring was the intent. Also guard the divide-by-zero divisor, and derive from RECS_DIR. - dump_logs.sh: services was a string, so "${services[@]}" expanded to one element containing all names joined by newlines and the -L test never matched - every support bundle shipped with no journals. Make it an array (as uninstall.sh already does) and prefer the canonical birdnet.conf path. PHP: - play.php: busyTimeout was set on the read-only handle, leaving $db_writable with none, so DELETE failed instantly with SQLITE_BUSY exactly when the analysis service was inserting. - advanced.php: compared $freqshift_hi and $RAW_SPECTROGRAM - the wrong and undefined variables - instead of $freqshift_reconnect_delay/$raw_spectrogram. - history.php / weekly_report.php: error_reporting is process-global and both are include()d by views.php, so E_ALL + display_errors sprayed notices and absolute filesystem paths into the rendered page. Align with the other views. Verified: py_compile + bash -n clean, php -l clean on the target's PHP 7.4.33, and the spectrogram-cleanup and write_to_db-raises paths behaviorally tested. --- scripts/advanced.php | 7 ++- scripts/birdnet_analysis.py | 32 +++++++++---- scripts/disk_check.sh | 29 ++++++++++-- scripts/dump_logs.sh | 12 ++++- scripts/history.php | 8 ++-- scripts/play.php | 5 +- scripts/spectrogram.sh | 11 +++-- scripts/utils/db.py | 18 ++++--- scripts/utils/helpers.py | 12 ++++- scripts/utils/notifications.py | 24 ++++++++-- scripts/utils/reporting.py | 86 +++++++++++++++++++++------------- scripts/weekly_report.php | 10 ++-- 12 files changed, 182 insertions(+), 72 deletions(-) diff --git a/scripts/advanced.php b/scripts/advanced.php index e9c0cd9eb7..5f87ece379 100644 --- a/scripts/advanced.php +++ b/scripts/advanced.php @@ -127,7 +127,8 @@ if(isset($_GET["freqshift_reconnect_delay"]) && is_numeric($_GET['freqshift_reconnect_delay'])) { $freqshift_reconnect_delay = $_GET["freqshift_reconnect_delay"]; - if(strcmp($freqshift_hi,$config['FREQSHIFT_RECONNECT_DELAY']) !== 0) { + /* was comparing $freqshift_hi - the wrong (and usually undefined) variable */ + if(strcmp($freqshift_reconnect_delay,$config['FREQSHIFT_RECONNECT_DELAY']) !== 0) { $contents = preg_replace("/FREQSHIFT_RECONNECT_DELAY=.*/", "FREQSHIFT_RECONNECT_DELAY=$freqshift_reconnect_delay", $contents); } } @@ -214,7 +215,9 @@ if(isset($_GET["raw_spectrogram"])) { $raw_spectrogram = 1; - if(strcmp($RAW_SPECTROGRAM,$config['RAW_SPECTROGRAM']) !== 0) { + /* was comparing $RAW_SPECTROGRAM (undefined) instead of $raw_spectrogram; + strcmp(null, ...) is also deprecated on PHP 8.1+ */ + if(strcmp($raw_spectrogram,$config['RAW_SPECTROGRAM']) !== 0) { $contents = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=$raw_spectrogram", $contents); } } else { diff --git a/scripts/birdnet_analysis.py b/scripts/birdnet_analysis.py index 807871be40..92c033ca41 100644 --- a/scripts/birdnet_analysis.py +++ b/scripts/birdnet_analysis.py @@ -12,7 +12,7 @@ from inotify.constants import IN_CLOSE_WRITE from utils.analysis import load_global_model, run_analysis -from utils.helpers import get_settings, get_wav_files, ANALYZING_NOW +from utils.helpers import get_settings, get_wav_files, get_analyzing_now_path from utils.classes import ParseFileName from utils.reporting import extract_detection, summary, write_to_file, write_to_db, apprise, bird_weather, heartbeat, \ update_json_file @@ -84,12 +84,12 @@ def main(): def process_file(file_name, report_queue): + enqueued = False try: if os.path.getsize(file_name) == 0: - os.remove(file_name) return log.info('Analyzing %s', file_name) - with open(ANALYZING_NOW, 'w') as analyzing: + with open(get_analyzing_now_path(), 'w') as analyzing: analyzing.write(file_name) file = ParseFileName(file_name) detections = run_analysis(file) @@ -97,9 +97,19 @@ def process_file(file_name, report_queue): # full chunk behind - same guarantee the old join() gave, but the next # chunk's inference can overlap this chunk's reporting. report_queue.put((file, detections)) - except BaseException as e: + enqueued = True + except Exception as e: stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" log.exception(f'Unexpected error: {stderr}', exc_info=e) + finally: + # On success the reporting thread owns the file and removes it there. + # Only clean up here when we failed before handing it off - otherwise a + # failed analysis strands the wav forever (nothing else reaps StreamData). + if not enqueued: + try: + os.remove(file_name) + except OSError: + pass def handle_reporting_queue(queue): @@ -120,12 +130,18 @@ def handle_reporting_queue(queue): apprise(file, detections) bird_weather(file, detections) heartbeat() - os.remove(file.file_name) - except BaseException as e: + except Exception as e: stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" log.exception(f'Unexpected error: {stderr}', exc_info=e) - - queue.task_done() + finally: + # This is the ONLY place StreamData wavs get removed (cleanup.sh only + # reaps PROCESSED), so it must run even when reporting above fails - + # otherwise any error strands the wav permanently. + try: + os.remove(file.file_name) + except OSError: + pass + queue.task_done() # mark the 'None' signal as processed queue.task_done() diff --git a/scripts/disk_check.sh b/scripts/disk_check.sh index ba5b5e6484..6ae5e4c867 100755 --- a/scripts/disk_check.sh +++ b/scripts/disk_check.sh @@ -2,10 +2,17 @@ set -x source /etc/birdnet/birdnet.conf -used="$(df -h ${EXTRACTED} | tail -n1 | awk '{print $5}')" + +disk_used_pct() { + local u + u="$(df -h "${EXTRACTED}" | tail -n1 | awk '{print $5}')" + echo "${u//%}" +} + +used="$(disk_used_pct)" purge_threshold="${PURGE_THRESHOLD:-95}" -if [ "${used//%}" -ge "$purge_threshold" ]; then +if [ "${used}" -ge "$purge_threshold" ]; then case $FULL_DISK in purge) echo "Removing oldest data" @@ -14,7 +21,15 @@ if [ "${used//%}" -ge "$purge_threshold" ]; then if ! grep -qxFe \#\#start $HOME/BirdNET-Pi/scripts/disk_check_exclude.txt; then exit fi - filestodelete=$(($(find ${EXTRACTED}/By_Date/* -type f | wc -l) / $(find ${EXTRACTED}/By_Date/* -maxdepth 0 -type d | wc -l))) + datedirs=$(find ${EXTRACTED}/By_Date/* -maxdepth 0 -type d | wc -l) + # Guard the divisor: with no date dirs this was a division by zero, which + # left filestodelete empty and made the [ -ge ] test below error instead + # of ever breaking out of the loop. + if [ "${datedirs}" -eq 0 ]; then + echo "No date directories to purge" + exit 0 + fi + filestodelete=$(( $(find ${EXTRACTED}/By_Date/* -type f | wc -l) / datedirs )) iter=0 for i in */*/*; do if [ $iter -ge $filestodelete ]; then @@ -25,7 +40,7 @@ if [ "${used//%}" -ge "$purge_threshold" ]; then fi ((iter++)) done - find ~/BirdSongs/ -type d -empty -mtime +90 -delete + find "${RECS_DIR:-$HOME/BirdSongs}/" -type d -empty -mtime +90 -delete find ${EXTRACTED}/By_Date/ -empty -type d -delete;; #rm -drfv "$(find ${EXTRACTED}/By_Date/* -maxdepth 1 -type d -prune \ @@ -35,7 +50,11 @@ if [ "${used//%}" -ge "$purge_threshold" ]; then esac fi sleep 1 -if [ "${used//%}" -ge "$purge_threshold" ]; then +# Re-measure: the purge above may already have freed enough. Re-using the stale +# reading made this second, more destructive purge (rm -rf $PROCESSED) fire +# unconditionally whenever the first one did. +used="$(disk_used_pct)" +if [ "${used}" -ge "$purge_threshold" ]; then case $FULL_DISK in purge) echo "Removing more data" rm -rfv ${PROCESSED}/*;; diff --git a/scripts/dump_logs.sh b/scripts/dump_logs.sh index 170afdca96..5d67a6c2a6 100755 --- a/scripts/dump_logs.sh +++ b/scripts/dump_logs.sh @@ -4,7 +4,11 @@ source /etc/birdnet/birdnet.conf &> /dev/null LOG_DIR="${HOME}/BirdNET-Pi/logs" my_dir=$HOME/BirdNET-Pi/scripts -services=$(awk '/service/ && /systemctl/ && !/php/ {print $3}' ${my_dir}/install_services.sh | sort) +# Must be an ARRAY: as a plain string, "${services[@]}" below expands to a single +# element holding every service name joined by newlines, so the -L test never +# matched and the bundle shipped with no journals at all. (uninstall.sh does this +# correctly.) +services=($(awk '/service/ && /systemctl/ && !/php/ {print $3}' ${my_dir}/install_services.sh | sort -u)) # Create logs directory [ -d ${LOG_DIR} ] || mkdir ${LOG_DIR} @@ -18,7 +22,11 @@ for i in "${services[@]}";do done # Create password-removed birdnet.conf -sed -e '/PWD=/d' ${HOME}/BirdNET-Pi/birdnet.conf > ${LOG_DIR}/birdnet.conf +# Prefer the canonical location the rest of the tree sources; fall back to the +# in-tree copy so this keeps working on older layouts. +CONF=/etc/birdnet/birdnet.conf +[ -f "${CONF}" ] || CONF="${HOME}/BirdNET-Pi/birdnet.conf" +sed -e '/PWD=/d' "${CONF}" > ${LOG_DIR}/birdnet.conf # Create password-removed Caddyfile if [ -f /etc/caddy/Caddyfile ];then diff --git a/scripts/history.php b/scripts/history.php index fd938ebec4..4596c61026 100644 --- a/scripts/history.php +++ b/scripts/history.php @@ -4,9 +4,11 @@ $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; -error_reporting(E_ALL); -ini_set('display_errors',1); -ini_set('display_startup_errors',1); +/* error_reporting is process-global and this file is include()d by views.php, so + E_ALL + display_errors here sprayed notices (and absolute filesystem paths) + into the rendered page for the rest of the request. Match every other view. */ +error_reporting(E_ERROR); +ini_set('display_errors', 0); require_once 'scripts/common.php'; $config = get_config(); diff --git a/scripts/play.php b/scripts/play.php index b0f5a749a6..c56a1ef5e9 100644 --- a/scripts/play.php +++ b/scripts/play.php @@ -22,7 +22,10 @@ die(); } $db_writable = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READWRITE); - $db->busyTimeout(1000); + /* was setting the timeout on $db (the read-only handle), leaving the writable + one with none - so the DELETE below failed instantly with SQLITE_BUSY + exactly when the analysis service was mid-insert. */ + $db_writable->busyTimeout(1000); $statement1 = $db_writable->prepare('DELETE FROM detections WHERE File_Name = :file_name LIMIT 1'); ensure_db_ok($statement1); $statement1->bindValue(':file_name', basename($deletefile)); diff --git a/scripts/spectrogram.sh b/scripts/spectrogram.sh index 73cfcf65fc..df752a9f61 100755 --- a/scripts/spectrogram.sh +++ b/scripts/spectrogram.sh @@ -15,13 +15,18 @@ fi next=0 looptime=$(( RECORDING_LENGTH * 2 / 3 )) -touch "$HOME/BirdSongs/StreamData/analyzing_now.txt" +# Derive from RECS_DIR so this stays in step with the python side +# (utils/helpers.py:get_analyzing_now_path). Hardcoding $HOME/BirdSongs meant a +# relocated RECS_DIR silently broke the watch. +ANALYZING_NOW="${RECS_DIR:-$HOME/BirdSongs}/StreamData/analyzing_now.txt" + +touch "${ANALYZING_NOW}" # Continuously loop generating a spectrogram -inotifywait -m -e close_write "$HOME/BirdSongs/StreamData/analyzing_now.txt" | +inotifywait -m -e close_write "${ANALYZING_NOW}" | while read; do now=$(date +%s) if (( now > next )); then - analyzing_now="$(<$HOME/BirdSongs/StreamData/analyzing_now.txt)" + analyzing_now="$(<"${ANALYZING_NOW}")" if [ -n "${analyzing_now}" ] && [ -f "${analyzing_now}" ]; then spectrogram_png=${EXTRACTED}/spectrogram.png diff --git a/scripts/utils/db.py b/scripts/utils/db.py index 88b0b5e290..127a720c87 100644 --- a/scripts/utils/db.py +++ b/scripts/utils/db.py @@ -1,9 +1,11 @@ +import logging import sqlite3 -import time as timeim from datetime import datetime from .helpers import DB_PATH +log = logging.getLogger(__name__) + _DB = None @@ -17,15 +19,17 @@ def get_db(): def get_records(select_sql): + # Previously this swallowed the error, slept 2s (in the analysis critical + # path, retrying nothing) and returned [] - which callers cannot tell apart + # from a genuine "no rows", so a DB hiccup silently dropped notifications. + # Log properly and let the caller's handler decide. con = get_db() try: cur = con.execute(select_sql) - records = cur.fetchall() - except sqlite3.Error as e: - print(e) - timeim.sleep(2) - records = [] - return records + return cur.fetchall() + except sqlite3.Error: + log.exception('query failed: %s', select_sql) + raise def get_record(select_sql): diff --git a/scripts/utils/helpers.py b/scripts/utils/helpers.py index 8c30043b00..ff945a68a9 100644 --- a/scripts/utils/helpers.py +++ b/scripts/utils/helpers.py @@ -13,7 +13,17 @@ DB_PATH = os.path.join(BASE_PATH, 'scripts/birds.db') MODEL_PATH = os.path.join(BASE_PATH, 'model') FONT_DIR = os.path.join(BASE_PATH, 'homepage/static') -ANALYZING_NOW = os.path.expanduser('~/BirdSongs/StreamData/analyzing_now.txt') + + +def get_analyzing_now_path(): + """Path of the 'currently analyzing' marker file. + + Derived from RECS_DIR rather than hardcoding ~/BirdSongs: with the old + constant, relocating RECS_DIR made open() raise for every file, which the + caller's handler swallowed - analysis stopped while the service still + looked healthy. scripts/spectrogram.sh derives the same path from RECS_DIR. + """ + return os.path.join(get_settings()['RECS_DIR'], 'StreamData', 'analyzing_now.txt') def get_font(): diff --git a/scripts/utils/notifications.py b/scripts/utils/notifications.py index c35edb8018..30db523926 100644 --- a/scripts/utils/notifications.py +++ b/scripts/utils/notifications.py @@ -2,8 +2,10 @@ import apprise except ImportError: apprise = None +import logging import os import socket +import sqlite3 import requests import html import time @@ -11,6 +13,8 @@ from .db import get_todays_count_for, get_this_weeks_count_for from .helpers import get_settings +log = logging.getLogger(__name__) + userDir = os.path.expanduser('~') APPRISE_CONFIG = userDir + '/BirdNET-Pi/apprise.txt' APPRISE_BODY = userDir + '/BirdNET-Pi/body.txt' @@ -93,7 +97,11 @@ def render_template(template, reason=""): resp = requests.get(url=url, timeout=10).json() images[com_name] = resp['data']['image_url'] except Exception as e: - print("IMAGE API ERROR:", e) + # Cache the failure too. Otherwise a down image API means a fresh + # 10s timeout on EVERY detection of this species, in the analysis + # critical path. + images[com_name] = "" + log.warning("image API lookup failed for %s: %s", sci_name, e) image_url = images.get(com_name, "") if settings_dict.get('APPRISE_NOTIFY_EACH_DETECTION') == "1": @@ -105,7 +113,13 @@ def render_template(template, reason=""): APPRISE_NOTIFICATION_NEW_SPECIES_DAILY_COUNT_LIMIT = 1 # Notifies the first N per day. if settings_dict.get('APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY') == "1": - numberDetections = get_todays_count_for(sci_name) + # A failed count must only skip this notification - never abort the + # caller's reporting for the detection as a whole. + try: + numberDetections = get_todays_count_for(sci_name) + except sqlite3.Error: + log.warning("could not count today's detections for %s; skipping notification", sci_name) + numberDetections = 0 if 0 < numberDetections <= APPRISE_NOTIFICATION_NEW_SPECIES_DAILY_COUNT_LIMIT: reason = "first time today" notify_body = render_template(body, reason) @@ -114,7 +128,11 @@ def render_template(template, reason=""): species_last_notified[com_name] = int(time.time()) if settings_dict.get('APPRISE_NOTIFY_NEW_SPECIES') == "1": - numberDetections = get_this_weeks_count_for(sci_name) + try: + numberDetections = get_this_weeks_count_for(sci_name) + except sqlite3.Error: + log.warning("could not count this week's detections for %s; skipping notification", sci_name) + numberDetections = 0 if 0 < numberDetections <= 5: reason = f"only seen {numberDetections} times in last 7d" notify_body = render_template(body, reason) diff --git a/scripts/utils/reporting.py b/scripts/utils/reporting.py index dfa8a66199..c23a2b3451 100644 --- a/scripts/utils/reporting.py +++ b/scripts/utils/reporting.py @@ -7,6 +7,7 @@ import tempfile import io import soundfile +from contextlib import closing from time import sleep import requests @@ -53,24 +54,31 @@ def spectrogram(in_file, title, comment, raw=0): '-t', '', '-c', '', '-o', tmp_file] args += ['-r'] if int(raw) else [] - result = subprocess.run(args, check=True, capture_output=True) - ret = result.stdout.decode('utf-8') - err = result.stderr.decode('utf-8') - if err: - raise RuntimeError(f'{ret}:\n {err}') - img = Image.open(tmp_file) - height = img.size[1] - width = img.size[0] - draw = ImageDraw.Draw(img) - title_font = ImageFont.truetype(get_font()['path'], 13) - _, _, w, _ = draw.textbbox((0, 0), title, font=title_font) - draw.text(((width-w)/2, 6), title, fill="white", font=title_font) - - comment_font = ImageFont.truetype(get_font()['path'], 11) - _, _, _, h = draw.textbbox((0, 0), comment, font=comment_font) - draw.text((1, height - (h + 1)), comment, fill="white", font=comment_font) - img.save(f'{in_file}.png') - os.remove(tmp_file) + # /tmp is a tmpfs, so a leaked temp file is leaked RAM. sox failing + # (check=True) or the RuntimeError below must not skip the cleanup. + try: + result = subprocess.run(args, check=True, capture_output=True) + ret = result.stdout.decode('utf-8') + err = result.stderr.decode('utf-8') + if err: + raise RuntimeError(f'{ret}:\n {err}') + with Image.open(tmp_file) as img: + height = img.size[1] + width = img.size[0] + draw = ImageDraw.Draw(img) + title_font = ImageFont.truetype(get_font()['path'], 13) + _, _, w, _ = draw.textbbox((0, 0), title, font=title_font) + draw.text(((width-w)/2, 6), title, fill="white", font=title_font) + + comment_font = ImageFont.truetype(get_font()['path'], 11) + _, _, _, h = draw.textbbox((0, 0), comment, font=comment_font) + draw.text((1, height - (h + 1)), comment, fill="white", font=comment_font) + img.save(f'{in_file}.png') + finally: + try: + os.remove(tmp_file) + except OSError: + pass def extract_detection(file: ParseFileName, detection: Detection): @@ -90,24 +98,36 @@ def extract_detection(file: ParseFileName, detection: Detection): def write_to_db(file: ParseFileName, detection: Detection): conf = get_settings() # Connect to SQLite Database + last_error = None for attempt_number in range(3): try: - con = sqlite3.connect(DB_PATH) - cur = con.cursor() - cur.execute("INSERT INTO detections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - (detection.date, detection.time, detection.scientific_name, detection.common_name, detection.confidence, - conf['LATITUDE'], conf['LONGITUDE'], conf['CONFIDENCE'], str(detection.week), conf['SENSITIVITY'], - conf['OVERLAP'], os.path.basename(detection.file_name_extr))) - # (Date, Time, Sci_Name, Com_Name, str(score), - # Lat, Lon, Cutoff, Week, Sens, - # Overlap, File_Name)) - - con.commit() - con.close() - break - except BaseException as e: - log.warning("Database busy: %s", e) + # `with` closes the connection even when execute/commit raises, which + # is exactly the contended case this retry loop exists for. + with closing(sqlite3.connect(DB_PATH, timeout=5)) as con: + # Let SQLite wait out a competing writer instead of failing instantly. + con.execute("PRAGMA busy_timeout=5000") + cur = con.cursor() + cur.execute("INSERT INTO detections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (detection.date, detection.time, detection.scientific_name, detection.common_name, detection.confidence, + conf['LATITUDE'], conf['LONGITUDE'], conf['CONFIDENCE'], str(detection.week), conf['SENSITIVITY'], + conf['OVERLAP'], os.path.basename(detection.file_name_extr))) + # (Date, Time, Sci_Name, Com_Name, str(score), + # Lat, Lon, Cutoff, Week, Sens, + # Overlap, File_Name)) + + con.commit() + return + except sqlite3.Error as e: + last_error = e + log.warning("Database busy (attempt %d/3): %s", attempt_number + 1, e) sleep(2) + # Previously the loop just fell through here: the detection was dropped from + # the DB while its wav/extraction/spectrogram/BirdDB.txt line all still + # existed, silently desyncing the DB from the filesystem. Fail loudly instead. + raise RuntimeError( + f'failed to write detection {detection.common_name} ' + f'({detection.file_name_extr}) to the database after 3 attempts' + ) from last_error def summary(file: ParseFileName, detection: Detection): diff --git a/scripts/weekly_report.php b/scripts/weekly_report.php index c31d5ae3d6..2d03fd968a 100644 --- a/scripts/weekly_report.php +++ b/scripts/weekly_report.php @@ -1,7 +1,9 @@ - Date: Thu, 16 Jul 2026 10:43:54 -0700 Subject: [PATCH 4/7] P4: close the injection sinks the hardening commit missed Root RCE via shiftfile (play.php) The hardening escaped the ffmpeg/sox *arguments* but $shifted_path.$dir - derived from the unvalidated $_GET['shiftfile'] via pathinfo() - was concatenated raw into a shell_exec running under sudo, so ?shiftfile=a/$(cmd)/b.wav&doshift=true executed as root. FILTER_SANITIZE_FULL_SPECIAL_CHARS encodes & < > " ' but NOT ; | ` $ ( ) or newline, so it never protected this. Validate the path (the guard the delete and rename paths already had, now factored into reject_unsafe_relpath() so the three cannot drift again) and escapeshellarg the mkdir path. Also escape the FREQSHIFT_* config values interpolated into the same command - the settings pages write those, so they are not trustworthy either. RCE via the config writers (config.php, advanced.php) Raw $_GET was written into /etc/birdnet/birdnet.conf, which bash `source`s (restart_services.sh et al), so LATITUDE=$(id) executed on the next restart - triggered in the same request. advanced.php had no filter_input_array at all. Quoting cannot fix this: the file has three parsers - bash `source`, PHP parse_ini_string, and python ConfigParser+strip('"') - which forces the KEY="value" convention, and inside bash double quotes $(...), `...` and $VAR still expand. So sanitise by type at the point of read instead: conf_safe_ {string,number,token,url,device} in common.php. This also removes the preg_replace() backreference hazard for free, since a sanitised value can no longer contain '$' or '\'. Verified end-to-end: a $(touch /tmp/PWNED) payload survives as an inert literal, /tmp/PWNED is not created, and all three parsers still read the file identically (including apostrophes in species names). SQL injection (common.php) fetch_species_array/fetch_best_detection/fetch_all_detections called prepare() with the value interpolated into the SQL - no placeholder, no bind - and callers reach them via htmlspecialchars_decode($_GET[...]), which restores the very quotes the input filter encoded. Bind properly (as species_tools.php already did). The decode calls stay: they are required to recover real species names ("Anna's Hummingbird"), and are safe once the value is bound. todays_detections.php Raw $_GET['searchterm'] concatenated into a LIKE literal, blocked only by the input filter's quote-encoding. Bind it. This also fixes a live bug: the filter turned ' into ', so searching for a species with an apostrophe always returned zero matches. homepage/views.php, homepage/index.php Still on FILTER_SANITIZE_STRING - the two actual HTTP entry points the migration missed. Deprecated in PHP 8.1 and slated for removal, at which point they would silently stop filtering. Also restore the `?: []` fallback. play.php / advanced.php: display_errors=1 -> 0 (fatals leaked absolute paths). Verified: php -l clean on the target PHP 7.4.33; sanitisers behaviourally tested against $(id), `id`, "; id; #, $VAR and newline-injection payloads. --- homepage/index.php | 9 ++-- homepage/views.php | 9 ++-- scripts/advanced.php | 58 ++++++++++++----------- scripts/common.php | 86 ++++++++++++++++++++++++++++++----- scripts/config.php | 46 ++++++++++--------- scripts/play.php | 40 ++++++++++++---- scripts/todays_detections.php | 18 ++++++-- 7 files changed, 189 insertions(+), 77 deletions(-) diff --git a/homepage/index.php b/homepage/index.php index 3f24eda3cf..3ef31d933a 100644 --- a/homepage/index.php +++ b/homepage/index.php @@ -7,9 +7,12 @@ die(); } -/* Prevent XSS input */ -$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING); -$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); +/* Prevent XSS input. + FILTER_SANITIZE_STRING is deprecated as of PHP 8.1 and slated for removal, at + which point this would silently stop filtering. The `?: []` matters too: + filter_input_array returns null (not []) when there is no query string. */ +$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; +$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; require_once 'scripts/common.php'; $config = get_config(); $site_name = get_sitename(); diff --git a/homepage/views.php b/homepage/views.php index 501989eaf1..d921429697 100644 --- a/homepage/views.php +++ b/homepage/views.php @@ -1,8 +1,11 @@ prepare("SELECT Date, Time, File_Name, Com_Name, Sci_Name, COUNT(*) as Count, MAX(Confidence) as MaxConfidence FROM detections $where GROUP BY Sci_Name ORDER BY COUNT(*) DESC"); + $order = "COUNT(*) DESC"; } elseif ($sort_by === "confidence") { - $statement = $db->prepare("SELECT Date, Time, File_Name, Com_Name, Sci_Name, COUNT(*) as Count, MAX(Confidence) as MaxConfidence FROM detections $where GROUP BY Sci_Name ORDER BY MAX(Confidence) DESC"); + $order = "MAX(Confidence) DESC"; } elseif ($sort_by === "date") { - $statement = $db->prepare("SELECT Date, Time, File_Name, Com_Name, Sci_Name, COUNT(*) as Count, MAX(Confidence) as MaxConfidence FROM detections $where GROUP BY Sci_Name ORDER BY MIN(Date) DESC, Time DESC"); + $order = "MIN(Date) DESC, Time DESC"; } else { - $statement = $db->prepare("SELECT Date, Time, File_Name, Com_Name, Sci_Name, COUNT(*) as Count, MAX(Confidence) as MaxConfidence FROM detections $where GROUP BY Sci_Name ORDER BY Com_Name ASC"); + $order = "Com_Name ASC"; } + $statement = $db->prepare("SELECT Date, Time, File_Name, Com_Name, Sci_Name, COUNT(*) as Count, MAX(Confidence) as MaxConfidence FROM detections $where GROUP BY Sci_Name ORDER BY $order"); ensure_db_ok($statement); + if (isset($date)) { + $statement->bindValue(':date', $date, SQLITE3_TEXT); + } $result = $statement->execute(); return $result; } function fetch_best_detection($com_name) { $db = get_db(); - $statement = $db->prepare("SELECT Com_Name, Sci_Name, COUNT(*), MAX(Confidence), File_Name, Date, Time from detections WHERE Com_Name = \"$com_name\""); + $statement = $db->prepare("SELECT Com_Name, Sci_Name, COUNT(*), MAX(Confidence), File_Name, Date, Time from detections WHERE Com_Name = :com_name"); ensure_db_ok($statement); + $statement->bindValue(':com_name', $com_name, SQLITE3_TEXT); $result = $statement->execute(); return $result; } function fetch_all_detections($sci_name, $sort_by, $date=null) { $db = get_db(); - $filter = (isset($date)) ? "AND Date == \"$date\"" : ""; + $filter = isset($date) ? "AND Date == :date" : ""; if ($sort_by === "occurrences") { - $statement = $db->prepare("SELECT * FROM detections WHERE Sci_Name == \"$sci_name\" $filter ORDER BY COUNT(*) DESC"); + $order = "COUNT(*) DESC"; } elseif ($sort_by === "confidence") { - $statement = $db->prepare("SELECT * FROM detections WHERE Sci_Name == \"$sci_name\" $filter ORDER BY Confidence DESC"); + $order = "Confidence DESC"; } else { - $order = (isset($date)) ? "Time DESC" : "Date DESC, Time DESC"; - $statement = $db->prepare("SELECT * FROM detections where Sci_Name == \"$sci_name\" $filter ORDER BY $order"); + $order = isset($date) ? "Time DESC" : "Date DESC, Time DESC"; } + $statement = $db->prepare("SELECT * FROM detections WHERE Sci_Name == :sci_name $filter ORDER BY $order"); ensure_db_ok($statement); + $statement->bindValue(':sci_name', $sci_name, SQLITE3_TEXT); + if (isset($date)) { + $statement->bindValue(':date', $date, SQLITE3_TEXT); + } $result = $statement->execute(); return $result; } diff --git a/scripts/config.php b/scripts/config.php index 1e46589e64..fcd600903c 100644 --- a/scripts/config.php +++ b/scripts/config.php @@ -55,32 +55,36 @@ function syslog_shell_exec($cmd, $sudo_user = null) { # Basic Settings if(isset($_GET["latitude"])){ - $latitude = $_GET["latitude"]; - $longitude = $_GET["longitude"]; - $site_name = $_GET["site_name"]; - $site_name = str_replace('"', "", $site_name); - $site_name = str_replace('\'', "", $site_name); - $birdweather_id = $_GET["birdweather_id"]; - $apprise_input = $_GET['apprise_input']; - $apprise_notification_title = $_GET['apprise_notification_title']; - $apprise_notification_body = htmlspecialchars_decode($_GET['apprise_notification_body'], ENT_QUOTES); - $minimum_time_limit = $_GET['minimum_time_limit']; - $image_provider = $_GET["image_provider"]; - $flickr_api_key = $_GET['flickr_api_key']; - $flickr_filter_email = $_GET["flickr_filter_email"]; - $language = $_GET["language"]; - $info_site = $_GET["info_site"]; - $color_scheme = $_GET["color_scheme"]; - $timezone = $_GET["timezone"]; - $model = $_GET["model"]; - $sf_thresh = $_GET["sf_thresh"]; + /* Everything below lands in /etc/birdnet/birdnet.conf, which bash `source`s - + so an unsanitised value here is remote code execution (e.g. LATITUDE=$(id)). + Sanitise by type at the point of read; see conf_safe_* in common.php. */ + $latitude = conf_safe_number($_GET["latitude"]); + $longitude = conf_safe_number($_GET["longitude"]); + $site_name = conf_safe_string($_GET["site_name"] ?? ''); + $birdweather_id = conf_safe_token($_GET["birdweather_id"] ?? ''); + /* written to apprise.txt / body.txt, not to the sourced conf */ + $apprise_input = $_GET['apprise_input'] ?? ''; + $apprise_notification_title = conf_safe_string($_GET['apprise_notification_title'] ?? ''); + $apprise_notification_body = htmlspecialchars_decode($_GET['apprise_notification_body'] ?? '', ENT_QUOTES); + $minimum_time_limit = conf_safe_number($_GET['minimum_time_limit'] ?? '', '0'); + $image_provider = conf_safe_token($_GET["image_provider"] ?? ''); + $flickr_api_key = conf_safe_token($_GET['flickr_api_key'] ?? ''); + $flickr_filter_email = conf_safe_token($_GET["flickr_filter_email"] ?? ''); + $language = conf_safe_token($_GET["language"] ?? ''); + $info_site = conf_safe_token($_GET["info_site"] ?? ''); + $color_scheme = conf_safe_token($_GET["color_scheme"] ?? ''); + $timezone = $_GET["timezone"] ?? ''; + $model = conf_safe_token($_GET["model"] ?? ''); + $sf_thresh = conf_safe_number($_GET["sf_thresh"] ?? '', '0.03'); if(isset($_GET['data_model_version'])) { $data_model_version = 2; } else { $data_model_version = 1; } - $only_notify_species_names = htmlspecialchars_decode($_GET['only_notify_species_names'], ENT_QUOTES); - $only_notify_species_names_2 = htmlspecialchars_decode($_GET['only_notify_species_names_2'], ENT_QUOTES); + /* decode first so apostrophes in species names survive ("Anna's Hummingbird"), + then strip what bash would still expand inside the double-quoted value */ + $only_notify_species_names = conf_safe_string(htmlspecialchars_decode($_GET['only_notify_species_names'] ?? '', ENT_QUOTES)); + $only_notify_species_names_2 = conf_safe_string(htmlspecialchars_decode($_GET['only_notify_species_names_2'] ?? '', ENT_QUOTES)); if(isset($_GET['apprise_notify_each_detection'])) { $apprise_notify_each_detection = 1; diff --git a/scripts/play.php b/scripts/play.php index c56a1ef5e9..aac21da93f 100644 --- a/scripts/play.php +++ b/scripts/play.php @@ -5,19 +5,32 @@ $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; error_reporting(E_ERROR); -ini_set('display_errors',1); +ini_set('display_errors', 0); require_once 'scripts/common.php'; $home = get_home(); $config = get_config(); $user = get_user(); +/* Reject a user-supplied relative path that could escape its base directory. + This guard was previously inline (and duplicated) on the delete and rename + paths, while the shift path had none at all - hence the drift. Keep one + copy so every caller gets the same rules. + NB FILTER_SANITIZE_FULL_SPECIAL_CHARS above encodes & < > " ' but NOT + ; | ` $ ( ) or newline, so it is not a substitute for this. */ +function reject_unsafe_relpath($p) { + return $p === '' || $p === null + || str_contains($p, "\0") + || str_contains($p, '..') + || str_starts_with($p, '/'); +} + $db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READONLY); $db->busyTimeout(1000); if(isset($_GET['deletefile'])) { ensure_authenticated('You must be authenticated to delete files.'); $deletefile = urldecode($_GET['deletefile']); - if ($deletefile === '' || str_contains($deletefile, "\0") || str_contains($deletefile, '..') || str_starts_with($deletefile, '/')) { + if (reject_unsafe_relpath($deletefile)) { echo "Error"; die(); } @@ -85,7 +98,7 @@ if(isset($_GET['changefile']) && isset($_GET['newname'])) { ensure_authenticated('You must be authenticated to delete files.'); $changefile = urldecode($_GET['changefile']); - if ($changefile === '' || str_contains($changefile, "\0") || str_contains($changefile, '..') || str_starts_with($changefile, '/')) { + if (reject_unsafe_relpath($changefile)) { echo "Error"; die(); } @@ -110,7 +123,13 @@ if(isset($_GET['shiftfile'])) { ensure_authenticated('You cannot shift files for this installation'); - $filename = $_GET['shiftfile']; + $filename = urldecode($_GET['shiftfile']); + /* Previously unvalidated: $dir below is derived from this and was + concatenated raw into a shell_exec running under sudo. */ + if (reject_unsafe_relpath($filename)) { + echo "Error"; + die(); + } $pp = pathinfo($filename); $dir = $pp['dirname']; $fn = $pp['filename']; @@ -120,16 +139,21 @@ if(isset($_GET['doshift'])) { $freqshift_tool = $config['FREQSHIFT_TOOL']; + /* These come from birdnet.conf, which the settings pages write - so they are + not inherently trustworthy either. Escape rather than interpolate raw. */ + $mkdir_cmd = "sudo mkdir -p ".escapeshellarg($shifted_path.$dir); + if ($freqshift_tool == "ffmpeg") { - $cmd = "sudo /usr/bin/nohup /usr/bin/ffmpeg -y -i ".escapeshellarg($pi.$filename)." -af \"rubberband=pitch=".$config['FREQSHIFT_LO']."/".$config['FREQSHIFT_HI']."\" ".escapeshellarg($shifted_path.$filename).""; - shell_exec("sudo mkdir -p ".$shifted_path.$dir." && ".$cmd); + $af = "rubberband=pitch=".$config['FREQSHIFT_LO']."/".$config['FREQSHIFT_HI']; + $cmd = "sudo /usr/bin/nohup /usr/bin/ffmpeg -y -i ".escapeshellarg($pi.$filename)." -af ".escapeshellarg($af)." ".escapeshellarg($shifted_path.$filename); + shell_exec($mkdir_cmd." && ".$cmd); } else if ($freqshift_tool == "sox") { //linux.die.net/man/1/sox $soxopt = "-q"; $soxpitch = $config['FREQSHIFT_PITCH']; - $cmd = "sudo /usr/bin/nohup /usr/bin/sox ".escapeshellarg($pi.$filename)." ".escapeshellarg($shifted_path.$filename)." pitch ".$soxopt." ".$soxpitch; - shell_exec("sudo mkdir -p ".$shifted_path.$dir." && ".$cmd); + $cmd = "sudo /usr/bin/nohup /usr/bin/sox ".escapeshellarg($pi.$filename)." ".escapeshellarg($shifted_path.$filename)." pitch ".escapeshellarg($soxopt)." ".escapeshellarg($soxpitch); + shell_exec($mkdir_cmd." && ".$cmd); } } else { $cmd = "sudo rm -f " . escapeshellarg($shifted_path.$filename); diff --git a/scripts/todays_detections.php b/scripts/todays_detections.php index 7feb1449ad..81e16ecc14 100644 --- a/scripts/todays_detections.php +++ b/scripts/todays_detections.php @@ -127,17 +127,24 @@ function relativeTime($ts) if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" ) { + $searchterm = null; if(isset($_GET['searchterm'])) { - if(strtolower(explode(" ", $_GET['searchterm'])[0]) == "not") { + /* Decode first: the input filter turns ' into ', so searching for + e.g. "Anna's Hummingbird" was matching the literal ' and always + returned nothing. */ + $searchterm = htmlspecialchars_decode($_GET['searchterm'], ENT_QUOTES); + if(strtolower(explode(" ", $searchterm)[0]) == "not") { $not = "NOT "; $operator = "AND"; - $_GET['searchterm'] = str_replace("not ", "", $_GET['searchterm']); - $_GET['searchterm'] = str_replace("NOT ", "", $_GET['searchterm']); + $searchterm = str_replace(array("not ", "NOT "), "", $searchterm); } else { $not = ""; $operator = "OR"; } - $searchquery = "AND (Com_name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Sci_name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Confidence ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." File_Name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Time ".$not."LIKE '%".$_GET['searchterm']."%')"; + /* Bound below - previously the raw value was concatenated into the LIKE + literal, which only the input filter's quote-encoding kept from being a + live injection. $not/$operator are internal constants, not user input. */ + $searchquery = "AND (Com_name ".$not."LIKE :term ".$operator." Sci_name ".$not."LIKE :term ".$operator." Confidence ".$not."LIKE :term ".$operator." File_Name ".$not."LIKE :term ".$operator." Time ".$not."LIKE :term)"; } else { $searchquery = ""; } @@ -153,6 +160,9 @@ function relativeTime($ts) } ensure_db_ok($statement0); + if ($searchterm !== null) { + $statement0->bindValue(':term', '%'.$searchterm.'%', SQLITE3_TEXT); + } $result0 = $statement0->execute(); ?>
    From 99dc2ff5aa1c3d56a30efc314d5b3ce7424ddded Mon Sep 17 00:00:00 2001 From: hydrospheric0 Date: Thu, 16 Jul 2026 11:04:09 -0700 Subject: [PATCH 5/7] P5: cheap correctness and efficiency cleanups - common.php get_info_url(): `require` (not require_once) of the ~6,500-entry / 243KB ebird.php array literal sat inside the function body, so the whole array was rebuilt on EVERY call - and callers invoke it once per rendered row. Load once into a static. Use __DIR__ too: the relative path silently depended on the caller's CWD being homepage/. Guard with the static rather than require_once, which would become a silent no-op (leaving $ebirds undefined) if anything else ever includes the file first. - spectrogram.php: glob() sorts ascending and the filenames are date-time prefixed, so $files[0] was the OLDEST file - despite being assigned to $newest_file, and despite the RTSP branch deliberately keeping the newest. Take the last entry. - system_controls.php: ran a blocking, networked `git fetch` on every render, so a slow/absent uplink hung the page for the full DNS+TCP timeout. views.php already backgrounds the fetch and caches the result in the session for 86400s - reuse that shape instead of duplicating it differently. - birdnet_recording.sh: the RTSP path hardcoded `-ac 2`, ignoring ${CHANNELS} that the arecord path honours, so RTSP users could never record mono. - livestream.sh: `-re` sat after the output URL, where it is a no-op ("Trailing option(s) found in the command: may be ignored") - it is an input option and is meaningless for an inherently realtime ALSA capture anyway. - disk_check.sh / cleanup.sh / custom_recording.sh / restart_services.sh: drop the unconditional `set -x`. These run on a timer or at every restart and every traced line is a journal write, i.e. SD-card wear. Left enabled in the install/uninstall/clear_all_data scripts, which run rarely and interactively where the trace is genuinely useful. - system_controls.php / advanced.php / play.php: display_errors 1 -> 0. Verified: php -l clean on the target PHP 7.4.33, bash -n clean. --- scripts/birdnet_recording.sh | 2 +- scripts/cleanup.sh | 3 ++- scripts/common.php | 18 +++++++++++++++-- scripts/custom_recording.sh | 3 ++- scripts/disk_check.sh | 3 ++- scripts/livestream.sh | 4 ++-- scripts/restart_services.sh | 3 ++- scripts/spectrogram.php | 6 +++++- scripts/system_controls.php | 38 ++++++++++++++++++++++-------------- 9 files changed, 55 insertions(+), 25 deletions(-) diff --git a/scripts/birdnet_recording.sh b/scripts/birdnet_recording.sh index cde2167022..81861c5537 100755 --- a/scripts/birdnet_recording.sh +++ b/scripts/birdnet_recording.sh @@ -4,7 +4,7 @@ source /etc/birdnet/birdnet.conf loop_ffmpeg(){ while true;do - if ! ffmpeg -hide_banner -loglevel $LOGGING_LEVEL -nostdin ${1} -i ${2} -vn -map a:0 -acodec pcm_s16le -ac 2 -ar 48000 -f segment -segment_format wav -segment_time ${RECORDING_LENGTH} -strftime 1 ${RECS_DIR}/StreamData/%F-birdnet-RTSP_${3}-%H:%M:%S.wav + if ! ffmpeg -hide_banner -loglevel $LOGGING_LEVEL -nostdin ${1} -i ${2} -vn -map a:0 -acodec pcm_s16le -ac ${CHANNELS} -ar 48000 -f segment -segment_format wav -segment_time ${RECORDING_LENGTH} -strftime 1 ${RECS_DIR}/StreamData/%F-birdnet-RTSP_${3}-%H:%M:%S.wav then sleep 1 fi diff --git a/scripts/cleanup.sh b/scripts/cleanup.sh index 4c009f3dc2..2d585dc7df 100755 --- a/scripts/cleanup.sh +++ b/scripts/cleanup.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash source /etc/birdnet/birdnet.conf -set -x +# set -x # was unconditional: this runs on a timer/at every restart, and every +# traced line is a journal write (SD-card wear). Uncomment to debug. cd "${PROCESSED}" || exit 1 empties=($(find ${PROCESSED} -size 57c)) diff --git a/scripts/common.php b/scripts/common.php index bd7b384d94..af5f765194 100644 --- a/scripts/common.php +++ b/scripts/common.php @@ -572,8 +572,22 @@ function get_info_url($sciname){ $engname = get_com_en_name($sciname); $config = get_config(); if ($config['INFO_SITE'] === 'EBIRD'){ - require 'scripts/ebird.php'; - $ebird = $ebirds[$sciname]; + /* `require` (not require_once) inside the function body rebuilt this ~6,500 + entry / 243KB array literal on EVERY call - and callers invoke this once + per rendered row. Load it once into a static. + Also __DIR__: the old relative path silently depended on the caller's CWD + being homepage/. */ + static $ebirds_cache = null; + if ($ebirds_cache === null) { + /* plain require, guarded by the static: require_once would silently become + a no-op (leaving $ebirds undefined) if anything else ever includes this + file first. The static already guarantees we only pay for it once. */ + $ebirds = null; + require __DIR__ . '/ebird.php'; + $ebirds_cache = $ebirds; + } + $ebirds = $ebirds_cache; + $ebird = $ebirds[$sciname] ?? ''; $language = $config['DATABASE_LANG']; $url = "https://ebird.org/species/$ebird?siteLanguage=$language"; $url_title = "eBirds"; diff --git a/scripts/custom_recording.sh b/scripts/custom_recording.sh index ccf43033a5..eed55d7ccf 100755 --- a/scripts/custom_recording.sh +++ b/scripts/custom_recording.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -set -x +# set -x # was unconditional: this runs on a timer/at every restart, and every +# traced line is a journal write (SD-card wear). Uncomment to debug. source /etc/birdnet/birdnet.conf STAMP="%H:%M:%S" diff --git a/scripts/disk_check.sh b/scripts/disk_check.sh index 6ae5e4c867..46ab3005ad 100755 --- a/scripts/disk_check.sh +++ b/scripts/disk_check.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -set -x +# set -x # was unconditional: this runs on a timer/at every restart, and every +# traced line is a journal write (SD-card wear). Uncomment to debug. source /etc/birdnet/birdnet.conf diff --git a/scripts/livestream.sh b/scripts/livestream.sh index 69fe21a990..741b44a090 100755 --- a/scripts/livestream.sh +++ b/scripts/livestream.sh @@ -39,10 +39,10 @@ elif [[ ! -z ${RTSP_STREAM} ]];then ffmpeg -nostdin -loglevel $LOGGING_LEVEL -ac ${CHANNELS} -i ${SELECTED_RSTP_STREAM} -acodec libmp3lame \ -b:a 320k -ac ${CHANNELS} -content_type 'audio/mpeg' \ ${FREQSHIFT_OPT} \ - -f mp3 icecast://source:${ICE_PWD}@localhost:8000/stream -re + -f mp3 icecast://source:${ICE_PWD}@localhost:8000/stream else ffmpeg -nostdin -loglevel $LOGGING_LEVEL -ac ${CHANNELS} -f alsa -i ${REC_CARD} -acodec libmp3lame \ -b:a 320k -ac ${CHANNELS} -content_type 'audio/mpeg' \ ${FREQSHIFT_OPT} \ - -f mp3 icecast://source:${ICE_PWD}@localhost:8000/stream -re + -f mp3 icecast://source:${ICE_PWD}@localhost:8000/stream fi diff --git a/scripts/restart_services.sh b/scripts/restart_services.sh index 9ce33d398b..7748c96755 100755 --- a/scripts/restart_services.sh +++ b/scripts/restart_services.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # Restarts ALL services and removes ALL unprocessed audio source /etc/birdnet/birdnet.conf -set -x +# set -x # was unconditional: this runs on a timer/at every restart, and every +# traced line is a journal write (SD-card wear). Uncomment to debug. my_dir=$HOME/BirdNET-Pi/scripts diff --git a/scripts/spectrogram.php b/scripts/spectrogram.php index 831f3a93a3..52ce5a3920 100644 --- a/scripts/spectrogram.php +++ b/scripts/spectrogram.php @@ -20,7 +20,11 @@ $look_in_directory = $STREAM_DATA_DIR; $files = glob($look_in_directory . "*.wav.json"); if (count($files) !== 0) { - $newest_file = $files[0]; + /* glob() sorts ascending and the names are date-time prefixed, so $files[0] + was the OLDEST - despite the variable name, and despite the RTSP branch + below deliberately keeping the newest. Take the last entry. */ + $newest_file = end($files); + reset($files); } } else { diff --git a/scripts/system_controls.php b/scripts/system_controls.php index 7eb325a500..0d2cfe8443 100644 --- a/scripts/system_controls.php +++ b/scripts/system_controls.php @@ -1,27 +1,35 @@ &1"); -$str = trim(shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi status")); -if (preg_match("/behind '.*?' by (\d+) commit(s?)\b/", $str, $matches)) { - $num_commits_behind = $matches[1]; -} -if (preg_match('/\b(\d+)\b and \b(\d+)\b different commits each/', $str, $matches)) { - $num1 = (int) $matches[1]; - $num2 = (int) $matches[2]; - $num_commits_behind = $num1 + $num2; -} -if (stripos($str, "Your branch is up to date") !== false) { - $num_commits_behind = '0'; +/* This used to run a *blocking, networked* `git fetch` on every single render, + so with a slow or absent uplink the page hung for the full DNS+TCP timeout. + views.php already solved this: background the fetch and cache the result in + the session for a day. Reuse that instead of duplicating it differently. */ +$num_commits_behind = $_SESSION['behind'] ?? '0'; +if (!isset($_SESSION['behind']) || !isset($_SESSION['behind_time']) + || time() > $_SESSION['behind_time'] + 86400) { + shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi fetch > /dev/null 2>/dev/null &"); + $str = trim(shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi status")); + if (preg_match("/behind '.*?' by (\d+) commit(s?)\b/", $str, $matches)) { + $num_commits_behind = $matches[1]; + } + if (preg_match('/\b(\d+)\b and \b(\d+)\b different commits each/', $str, $matches)) { + $num1 = (int) $matches[1]; + $num2 = (int) $matches[2]; + $num_commits_behind = $num1 + $num2; + } + if (stripos($str, "Your branch is up to date") !== false) { + $num_commits_behind = '0'; + } + $_SESSION['behind'] = $num_commits_behind; + $_SESSION['behind_time'] = time(); } -$_SESSION['behind'] = $num_commits_behind; -$_SESSION['behind_time'] = time(); $restore = "cat $home/BirdSongs/restore.log"; $max_upload_size = floor(disk_free_space("$home/BirdNET-Pi/") / 1.001); From 93076c2f7c54a234b4edc5615f5b9dd36e1d91dd Mon Sep 17 00:00:00 2001 From: hydrospheric0 Date: Thu, 16 Jul 2026 12:06:00 -0700 Subject: [PATCH 6/7] P6: fix three regressions from my own P3/P4, plus new review findings Regressions I introduced (found by adversarially re-reviewing 5cc3c6a..HEAD): - advanced.php CUSTOM_IMAGE: I used conf_safe_string on an UNQUOTED value. That function only strips what bash expands INSIDE double quotes ($ ` " \) and deliberately permits ; | & and spaces - which are live when unquoted. So CUSTOM_IMAGE=a.png;cmd executed on the next `source`. Reachable from the settings form, which has no pattern attribute. In other words P4 closed three injection sinks and opened a fourth. Now written double-quoted like its sibling CUSTOM_IMAGE_TITLE. Verified: the payload is now an inert literal and bash/PHP both read it back unchanged. - birdnet_analysis: making write_to_db raise (P3) widened the blast radius from one detection to the whole chunk - a failure on detection #2 of 5 dropped #3-5 AND skipped apprise/bird_weather/heartbeat, where a missed heartbeat can trip a false "station down" alert. Worse, write_to_file had already appended #2 to BirdDB.txt, so it caused a wider desync than the silent drop it replaced. Contain per-detection; pass only successfully reported detections onward (apprise/bird_weather read file_name_extr, unset if extract_detection failed). - disk_check.sh: my divide-by-zero guard used `exit 0`, which skipped the second block - the PROCESSED purge. On a full disk with an empty By_Date that is the fallback that actually frees space, i.e. exactly the recovery path the script exists for. Skip only the By_Date loop. - conf_safe_number defaulted to '0' on rejection, silently destroying a working config: SENSITIVITY=0 is outside BirdNET's legal 0.5-1.5 and CONFIDENCE=0 means record everything. All call sites now pass the CURRENT config value as the fallback, so a rejected input preserves the existing setting. Regex also accepts a leading '.' (".5" previously became 0). New findings from a fresh review of previously-unreviewed files: - stop_core_services.sh ran `sudo rm -rf ${RECS_DIR}/$(date ...)/*` while never sourcing the config - and install_config.sh sets RECS_DIR without export, so it was empty even when a parent had sourced it. It expanded to an absolute path like /July-2026/16-Thursday/*: the documented cleanup silently never happened, and it sat one layout change away from real damage under sudo. Source the config and refuse to run unless RECS_DIR is a real directory. - api.php is routed before any auth or filtering and a cache miss drives blocking outbound HTTP + a DB write, unbounded and unauthenticated - a loop over junk names pins the whole PHP-FPM pool. Cannot simply require auth: utils/notifications.py fetches it from localhost with no credentials. So allow loopback, require auth otherwise; bound the species pattern; honour the IMAGE_PROVIDER off-switch (which previously did not reach this endpoint at all); add a 5s timeout to ImageProvider's stream context (it was inheriting default_socket_timeout=60). - birdnet_changeidentification.sh: play.php escapeshellarg's the args, which protects the shell layer only - the values then land raw inside single-quoted SQL against a writable DB. Escape at the SQL layer. Its own guard was also `grep -q "$NEWNAME"`, treating input as a regex, satisfiable via alternation while smuggling a quote: use grep -qF --. - plotly_streamlit.py: y_downscale_factor could be 0 for a species detected in a <3h window on one day, making the [::0] slices raise "slice step cannot be zero" - precisely the rare species the view exists to inspect. max(1, ...). - common.php: rawurlencode the species name before it becomes a path segment in the Wikipedia request. - weekly_report.php: was 1+2N queries (prior-week count and first-seen check ran per species inside the loop). Pre-aggregate into two lookups: 3 grouped queries total, zero prepare() calls inside the loop. Values bound. Verified behaviourally identical to the old logic on a synthetic DB. - dump_logs.sh: `arecord --dump-hw-params` blocks forever on a live station because the capture device is always held - so logs could not be collected precisely when needed. Bound with timeout and report the omission. - createdb.sh/update_birdnet_snippets.sh: add composite (Sci_Name, Date) index. overview.php's correlated subqueries filter on both; with only the Sci_Name index each probe scans every historical row for that species. createdb.sh DROPs the table so it only helps new installs - migrate existing DBs too. Verified: py_compile + bash -n clean; php -l clean on the target PHP 7.4.33; the CUSTOM_IMAGE payload proven inert across bash and PHP; conf_safe_number proven to preserve the current value on rejection. --- scripts/advanced.php | 34 +++++++------ scripts/api.php | 35 ++++++++++++- scripts/birdnet_analysis.py | 26 +++++++--- scripts/birdnet_changeidentification.sh | 15 ++++-- scripts/common.php | 24 +++++++-- scripts/config.php | 8 +-- scripts/createdb.sh | 5 ++ scripts/disk_check.sh | 39 ++++++++------- scripts/dump_logs.sh | 14 +++++- scripts/plotly_streamlit.py | 7 ++- scripts/stop_core_services.sh | 14 +++++- scripts/update_birdnet_snippets.sh | 6 +++ scripts/weekly_report.php | 66 ++++++++++++++++++------- 13 files changed, 222 insertions(+), 71 deletions(-) diff --git a/scripts/advanced.php b/scripts/advanced.php index 2035e569fb..0b10f54cf5 100644 --- a/scripts/advanced.php +++ b/scripts/advanced.php @@ -81,42 +81,42 @@ } if(isset($_GET["overlap"])) { - $overlap = conf_safe_number($_GET["overlap"]); + $overlap = conf_safe_number($_GET["overlap"], $config['OVERLAP'] ?? '0'); if(strcmp($overlap,$config['OVERLAP']) !== 0) { $contents = preg_replace("/OVERLAP=.*/", "OVERLAP=$overlap", $contents); } } if(isset($_GET["confidence"])) { - $confidence = conf_safe_number($_GET["confidence"]); + $confidence = conf_safe_number($_GET["confidence"], $config['CONFIDENCE'] ?? '0'); if(strcmp($confidence,$config['CONFIDENCE']) !== 0) { $contents = preg_replace("/CONFIDENCE=.*/", "CONFIDENCE=$confidence", $contents); } } if(isset($_GET["sensitivity"])) { - $sensitivity = conf_safe_number($_GET["sensitivity"]); + $sensitivity = conf_safe_number($_GET["sensitivity"], $config['SENSITIVITY'] ?? '0'); if(strcmp($sensitivity,$config['SENSITIVITY']) !== 0) { $contents = preg_replace("/SENSITIVITY=.*/", "SENSITIVITY=$sensitivity", $contents); } } if(isset($_GET["freqshift_hi"]) && is_numeric($_GET['freqshift_hi'])) { - $freqshift_hi = conf_safe_number($_GET["freqshift_hi"]); + $freqshift_hi = conf_safe_number($_GET["freqshift_hi"], $config['FREQSHIFT_HI'] ?? '0'); if(strcmp($freqshift_hi,$config['FREQSHIFT_HI']) !== 0) { $contents = preg_replace("/FREQSHIFT_HI=.*/", "FREQSHIFT_HI=$freqshift_hi", $contents); } } if(isset($_GET["freqshift_lo"]) && is_numeric($_GET['freqshift_lo'])) { - $freqshift_lo = conf_safe_number($_GET["freqshift_lo"]); + $freqshift_lo = conf_safe_number($_GET["freqshift_lo"], $config['FREQSHIFT_LO'] ?? '0'); if(strcmp($freqshift_lo,$config['FREQSHIFT_LO']) !== 0) { $contents = preg_replace("/FREQSHIFT_LO=.*/", "FREQSHIFT_LO=$freqshift_lo", $contents); } } if(isset($_GET["freqshift_pitch"]) && is_numeric($_GET['freqshift_pitch'])) { - $freqshift_pitch = conf_safe_number($_GET["freqshift_pitch"]); + $freqshift_pitch = conf_safe_number($_GET["freqshift_pitch"], $config['FREQSHIFT_PITCH'] ?? '0'); if(strcmp($freqshift_pitch,$config['FREQSHIFT_PITCH']) !== 0) { $contents = preg_replace("/FREQSHIFT_PITCH=.*/", "FREQSHIFT_PITCH=$freqshift_pitch", $contents); } @@ -130,7 +130,7 @@ } if(isset($_GET["freqshift_reconnect_delay"]) && is_numeric($_GET['freqshift_reconnect_delay'])) { - $freqshift_reconnect_delay = conf_safe_number($_GET["freqshift_reconnect_delay"]); + $freqshift_reconnect_delay = conf_safe_number($_GET["freqshift_reconnect_delay"], $config['FREQSHIFT_RECONNECT_DELAY'] ?? '0'); /* was comparing $freqshift_hi - the wrong (and usually undefined) variable */ if(strcmp($freqshift_reconnect_delay,$config['FREQSHIFT_RECONNECT_DELAY']) !== 0) { $contents = preg_replace("/FREQSHIFT_RECONNECT_DELAY=.*/", "FREQSHIFT_RECONNECT_DELAY=$freqshift_reconnect_delay", $contents); @@ -145,21 +145,21 @@ } if (isset($_GET["purge_threshold"])) { - $purge_threshold = conf_safe_number($_GET["purge_threshold"]); + $purge_threshold = conf_safe_number($_GET["purge_threshold"], $config['PURGE_THRESHOLD'] ?? '0'); if (strcmp($purge_threshold, $config['PURGE_THRESHOLD']) !== 0) { $contents = preg_replace("/PURGE_THRESHOLD=.*/", "PURGE_THRESHOLD=$purge_threshold", $contents); } } if (isset($_GET["max_files_species"])) { - $max_files_species = conf_safe_number($_GET["max_files_species"]); + $max_files_species = conf_safe_number($_GET["max_files_species"], $config['MAX_FILES_SPECIES'] ?? '0'); if (strcmp($max_files_species, $config['MAX_FILES_SPECIES']) !== 0) { $contents = preg_replace("/MAX_FILES_SPECIES=.*/", "MAX_FILES_SPECIES=$max_files_species", $contents); } } if(isset($_GET["privacy_threshold"])) { - $privacy_threshold = conf_safe_number($_GET["privacy_threshold"]); + $privacy_threshold = conf_safe_number($_GET["privacy_threshold"], $config['PRIVACY_THRESHOLD'] ?? '0'); if(strcmp($privacy_threshold,$config['PRIVACY_THRESHOLD']) !== 0) { $contents = preg_replace("/PRIVACY_THRESHOLD=.*/", "PRIVACY_THRESHOLD=$privacy_threshold", $contents); } @@ -173,21 +173,21 @@ } if(isset($_GET["channels"])) { - $channels = conf_safe_number($_GET["channels"]); + $channels = conf_safe_number($_GET["channels"], $config['CHANNELS'] ?? '0'); if(strcmp($channels,$config['CHANNELS']) !== 0) { $contents = preg_replace("/CHANNELS=.*/", "CHANNELS=$channels", $contents); } } if(isset($_GET["recording_length"])) { - $recording_length = conf_safe_number($_GET["recording_length"]); + $recording_length = conf_safe_number($_GET["recording_length"], $config['RECORDING_LENGTH'] ?? '0'); if(strcmp($recording_length,$config['RECORDING_LENGTH']) !== 0) { $contents = preg_replace("/RECORDING_LENGTH=.*/", "RECORDING_LENGTH=$recording_length", $contents); } } if(isset($_GET["extraction_length"])) { - $extraction_length = conf_safe_number($_GET["extraction_length"]); + $extraction_length = conf_safe_number($_GET["extraction_length"], $config['EXTRACTION_LENGTH'] ?? '0'); if(strcmp($extraction_length,$config['EXTRACTION_LENGTH']) !== 0) { $contents = preg_replace("/EXTRACTION_LENGTH=.*/", "EXTRACTION_LENGTH=$extraction_length", $contents); } @@ -229,7 +229,7 @@ } if(isset($_GET["rare_species_threshold"])) { - $rare_species_threshold = conf_safe_number($_GET["rare_species_threshold"]); + $rare_species_threshold = conf_safe_number($_GET["rare_species_threshold"], $config['RARE_SPECIES_THRESHOLD'] ?? '0'); if(strcmp($rare_species_threshold, $config['RARE_SPECIES_THRESHOLD']) !== 0) { $contents = preg_replace("/RARE_SPECIES_THRESHOLD=.*/", "RARE_SPECIES_THRESHOLD=$rare_species_threshold", $contents); } @@ -240,7 +240,11 @@ if(isset($_GET["custom_image"])) { $custom_image = conf_safe_string($_GET["custom_image"]); if(strcmp($custom_image,$config['CUSTOM_IMAGE']) !== 0) { - $contents = preg_replace("/CUSTOM_IMAGE=.*/", "CUSTOM_IMAGE=$custom_image", $contents); + /* MUST stay double-quoted: conf_safe_string only strips what bash expands + INSIDE quotes ($ ` " \) and deliberately permits ; | & and spaces, which + are live on an unquoted value (CUSTOM_IMAGE=a.png;cmd would execute cmd + when the conf is sourced). Quoting matches CUSTOM_IMAGE_TITLE below. */ + $contents = preg_replace("/CUSTOM_IMAGE=.*/", "CUSTOM_IMAGE=\"$custom_image\"", $contents); } } diff --git a/scripts/api.php b/scripts/api.php index 76c0b5dc8b..f1b8e3d2f8 100644 --- a/scripts/api.php +++ b/scripts/api.php @@ -11,13 +11,46 @@ sendResponse405(); } +/* This file is routed from homepage/index.php BEFORE any auth or input + filtering, and a cache miss triggers blocking outbound HTTP plus a DB write. + Unauthenticated and unbounded, a loop over junk names pins every PHP-FPM + worker on live network fetches and takes the UI down - cheap DoS on a 1GB Pi. + + We cannot simply require auth: scripts/utils/notifications.py fetches + http://localhost/api/v1/image/ with no credentials. So: allow the + loopback caller, require authentication for anyone else. */ +function api_is_local() { + $ip = $_SERVER['REMOTE_ADDR'] ?? ''; + return $ip === '127.0.0.1' || $ip === '::1' || $ip === '::ffff:127.0.0.1'; +} + if (preg_match('#^/api/v1/image/(\S+)$#', $requestUri, $matches)) { + if (!api_is_local() && !is_authenticated()) { + http_response_code(401); + header('WWW-Authenticate: Basic realm="BirdNET-Pi"'); + echo json_encode(["message" => "Unauthorized"]); + exit; + } + /* Every other call site guards on this; without it the image feature's + off-switch simply did not reach this endpoint. */ + if (empty($config["IMAGE_PROVIDER"])) { + http_response_code(404); + echo "Error 404! Image provider disabled."; + exit; + } + $sci_name = urldecode($matches[1]); + /* Bound the input: a scientific name, not an arbitrary \S+ that becomes a + URL path suffix in the upstream request. */ + if (!preg_match('/^[A-Za-z .\'-]{1,64}$/', $sci_name)) { + http_response_code(400); + echo "Error 400! Invalid species name."; + exit; + } if ($config["IMAGE_PROVIDER"] === 'FLICKR') { $image_provider = new Flickr(); } else { $image_provider = new Wikipedia(); } - $sci_name = urldecode($matches[1]); $result = $image_provider->get_image($sci_name); if ($result == false) { diff --git a/scripts/birdnet_analysis.py b/scripts/birdnet_analysis.py index 92c033ca41..74edaedcec 100644 --- a/scripts/birdnet_analysis.py +++ b/scripts/birdnet_analysis.py @@ -122,13 +122,27 @@ def handle_reporting_queue(queue): file, detections = msg try: update_json_file(file, detections) + reported = [] for detection in detections: - detection.file_name_extr = extract_detection(file, detection) - log.info('%s;%s', summary(file, detection), os.path.basename(detection.file_name_extr)) - write_to_file(file, detection) - write_to_db(file, detection) - apprise(file, detections) - bird_weather(file, detections) + # Contain per detection: write_to_db now raises on persistent + # failure, and without this one bad row would drop every later + # detection in the chunk AND skip apprise/bird_weather/heartbeat + # below - a wider desync than the silent drop it replaced, and a + # missed heartbeat can trip a false "station down" alert. + try: + detection.file_name_extr = extract_detection(file, detection) + log.info('%s;%s', summary(file, detection), os.path.basename(detection.file_name_extr)) + write_to_file(file, detection) + write_to_db(file, detection) + reported.append(detection) + except Exception as e: + log.exception('dropping detection %s', detection.common_name, exc_info=e) + # Only pass on detections that actually made it: apprise() and + # bird_weather() read detection.file_name_extr, which is unset if + # extract_detection() was the thing that failed. + if reported: + apprise(file, reported) + bird_weather(file, reported) heartbeat() except Exception as e: stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" diff --git a/scripts/birdnet_changeidentification.sh b/scripts/birdnet_changeidentification.sh index a9a0acc07c..5f62634580 100755 --- a/scripts/birdnet_changeidentification.sh +++ b/scripts/birdnet_changeidentification.sh @@ -48,7 +48,10 @@ elif [[ "$2" != *"_"* ]]; then fi # Check if $NEWNAME is found in the file $LABELS_FILE -if ! grep -q "$NEWNAME" "$LABELS_FILE"; then +# -F: without it the name is treated as a REGEX, so a crafted value could satisfy +# this guard via alternation/optional groups while still smuggling a quote into +# the SQL built below. -- stops a leading dash being read as an option. +if ! grep -qF -- "$NEWNAME" "$LABELS_FILE"; then echo "Error: $NEWNAME not found in $LABELS_FILE" exit 1 fi @@ -64,11 +67,17 @@ fi # EXECUTE SCRIPT # ################## +# SQL-escape a value for a single-quoted sqlite literal by doubling any quote. +# The caller (play.php) escapeshellarg's these, which protects the SHELL layer - +# but the values then land raw inside the SQL below, against a DB opened for +# WRITE. Shell escaping is not SQL escaping. +sql_lit() { printf '%s' "${1//\'/\'\'}"; } + # Intro [[ "$OUTPUT_TYPE" == "debug" ]] && echo "Starting to modify $OLDNAME to $NEWNAME" # Get the line where the column "File_Name" matches exactly $OLDNAME -IFS='|' read -r OLDNAME_sciname OLDNAME_comname OLDNAME_date < <(sqlite3 "$DB_FILE" "SELECT Sci_Name, Com_Name, Date FROM $DETECTIONS_TABLE WHERE File_Name = '$OLDNAME' LIMIT 1;") +IFS='|' read -r OLDNAME_sciname OLDNAME_comname OLDNAME_date < <(sqlite3 "$DB_FILE" "SELECT Sci_Name, Com_Name, Date FROM $DETECTIONS_TABLE WHERE File_Name = '$(sql_lit "$OLDNAME")' LIMIT 1;") if [[ -z "$OLDNAME_sciname" ]]; then echo "Error: No line matching $OLDNAME in $DB_FILE" @@ -113,7 +122,7 @@ fi ################################### # Update the database -sqlite3 "$DB_FILE" "UPDATE $DETECTIONS_TABLE SET Sci_Name = '$NEWNAME_sciname', Com_Name = '$NEWNAME_comname', Confidence = '0', File_Name = '$NEWNAME_filename' WHERE File_Name = '$OLDNAME';" +sqlite3 "$DB_FILE" "UPDATE $DETECTIONS_TABLE SET Sci_Name = '$(sql_lit "$NEWNAME_sciname")', Com_Name = '$(sql_lit "$NEWNAME_comname")', Confidence = '0', File_Name = '$(sql_lit "$NEWNAME_filename")' WHERE File_Name = '$(sql_lit "$OLDNAME")';" [[ "$OUTPUT_TYPE" == "debug" ]] && echo "Database entry removed" diff --git a/scripts/common.php b/scripts/common.php index af5f765194..aef0916be3 100644 --- a/scripts/common.php +++ b/scripts/common.php @@ -45,10 +45,16 @@ function conf_safe_string($v) { return trim(preg_replace('/[\r\n]+/', ' ', $v)); } -/* A bare, unquoted numeric value. */ +/* A bare, unquoted numeric value. + Pass the CURRENT config value as $default: on a rejected input we must not + silently write a plausible-looking constant. '0' is outside the legal range + for SENSITIVITY (0.5-1.5) and would mean "record everything" for CONFIDENCE. + Keeping the existing value preserves "never write an unsafe value" without + destroying a working configuration. + Accepts a leading '.' (".5") and a trailing '.' which bash/INI tolerate. */ function conf_safe_number($v, $default = '0') { $v = trim((string)$v); - return preg_match('/^-?\d+(\.\d+)?$/', $v) ? $v : $default; + return preg_match('/^-?(\d+(\.\d*)?|\.\d+)$/', $v) ? $v : $default; } /* A bare, unquoted identifier (model names, colour schemes, ids, ...). */ @@ -301,7 +307,14 @@ class ImageProvider { public function __construct() { $this->set_db(); - $opts = ['http' => ['header' => "User-Agent: BirdNET-Pi"]]; + /* An explicit timeout matters: these are blocking outbound fetches made from + inside a PHP-FPM worker. Without it they inherit default_socket_timeout + (60s), so a slow upstream pins a worker for a minute - and on a 1GB Pi the + worker pool is small enough that a handful of those stall the whole UI. */ + $opts = ['http' => [ + 'header' => "User-Agent: BirdNET-Pi", + 'timeout' => 5, + ]]; $this->context = stream_context_create($opts); } @@ -509,7 +522,10 @@ class Wikipedia extends ImageProvider { protected $db_path = __ROOT__ . '/scripts/wikipedia.db'; protected function get_from_source($sci_name) { - $page_title = str_replace(' ', '_', $sci_name); + /* rawurlencode: this value becomes a path segment in the upstream request. + Unencoded, dot-segments and query separators in the name let a caller + reach arbitrary paths on the target host. */ + $page_title = rawurlencode(str_replace(' ', '_', $sci_name)); $data = $this->get_json("https://en.wikipedia.org/api/rest_v1/page/summary/$page_title"); if ($data == false or !isset($data['originalimage'])) return; diff --git a/scripts/config.php b/scripts/config.php index fcd600903c..a26295b1d9 100644 --- a/scripts/config.php +++ b/scripts/config.php @@ -58,15 +58,15 @@ function syslog_shell_exec($cmd, $sudo_user = null) { /* Everything below lands in /etc/birdnet/birdnet.conf, which bash `source`s - so an unsanitised value here is remote code execution (e.g. LATITUDE=$(id)). Sanitise by type at the point of read; see conf_safe_* in common.php. */ - $latitude = conf_safe_number($_GET["latitude"]); - $longitude = conf_safe_number($_GET["longitude"]); + $latitude = conf_safe_number($_GET["latitude"], $config['LATITUDE'] ?? '0'); + $longitude = conf_safe_number($_GET["longitude"], $config['LONGITUDE'] ?? '0'); $site_name = conf_safe_string($_GET["site_name"] ?? ''); $birdweather_id = conf_safe_token($_GET["birdweather_id"] ?? ''); /* written to apprise.txt / body.txt, not to the sourced conf */ $apprise_input = $_GET['apprise_input'] ?? ''; $apprise_notification_title = conf_safe_string($_GET['apprise_notification_title'] ?? ''); $apprise_notification_body = htmlspecialchars_decode($_GET['apprise_notification_body'] ?? '', ENT_QUOTES); - $minimum_time_limit = conf_safe_number($_GET['minimum_time_limit'] ?? '', '0'); + $minimum_time_limit = conf_safe_number($_GET['minimum_time_limit'] ?? '', $config['APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES'] ?? '0'); $image_provider = conf_safe_token($_GET["image_provider"] ?? ''); $flickr_api_key = conf_safe_token($_GET['flickr_api_key'] ?? ''); $flickr_filter_email = conf_safe_token($_GET["flickr_filter_email"] ?? ''); @@ -75,7 +75,7 @@ function syslog_shell_exec($cmd, $sudo_user = null) { $color_scheme = conf_safe_token($_GET["color_scheme"] ?? ''); $timezone = $_GET["timezone"] ?? ''; $model = conf_safe_token($_GET["model"] ?? ''); - $sf_thresh = conf_safe_number($_GET["sf_thresh"] ?? '', '0.03'); + $sf_thresh = conf_safe_number($_GET["sf_thresh"] ?? '', $config['SF_THRESH'] ?? '0.03'); if(isset($_GET['data_model_version'])) { $data_model_version = 2; } else { diff --git a/scripts/createdb.sh b/scripts/createdb.sh index 661c86c437..36247c75b8 100755 --- a/scripts/createdb.sh +++ b/scripts/createdb.sh @@ -18,6 +18,11 @@ CREATE TABLE IF NOT EXISTS detections ( CREATE INDEX "detections_Com_Name" ON "detections" ("Com_Name"); CREATE INDEX "detections_Sci_Name" ON "detections" ("Sci_Name"); CREATE INDEX "detections_Date_Time" ON "detections" ("Date" DESC, "Time" DESC); +-- Composite (Sci_Name, Date): overview.php - the default landing page - runs two +-- correlated subqueries filtering on BOTH columns. With only the Sci_Name index +-- each probe scans every historical row for that species; this makes them index +-- seeks instead. +CREATE INDEX IF NOT EXISTS "detections_Sci_Date" ON "detections" ("Sci_Name", "Date"); EOF chown $USER:$USER $HOME/BirdNET-Pi/scripts/birds.db chmod g+w $HOME/BirdNET-Pi/scripts/birds.db diff --git a/scripts/disk_check.sh b/scripts/disk_check.sh index 46ab3005ad..fbc0ed4a69 100755 --- a/scripts/disk_check.sh +++ b/scripts/disk_check.sh @@ -22,27 +22,30 @@ if [ "${used}" -ge "$purge_threshold" ]; then if ! grep -qxFe \#\#start $HOME/BirdNET-Pi/scripts/disk_check_exclude.txt; then exit fi - datedirs=$(find ${EXTRACTED}/By_Date/* -maxdepth 0 -type d | wc -l) + datedirs=$(find ${EXTRACTED}/By_Date/* -maxdepth 0 -type d 2>/dev/null | wc -l) # Guard the divisor: with no date dirs this was a division by zero, which # left filestodelete empty and made the [ -ge ] test below error instead # of ever breaking out of the loop. - if [ "${datedirs}" -eq 0 ]; then - echo "No date directories to purge" - exit 0 - fi - filestodelete=$(( $(find ${EXTRACTED}/By_Date/* -type f | wc -l) / datedirs )) - iter=0 - for i in */*/*; do - if [ $iter -ge $filestodelete ]; then - break - fi - if ! grep -qxFe "$i" $HOME/BirdNET-Pi/scripts/disk_check_exclude.txt; then - rm "$i" - fi - ((iter++)) - done - find "${RECS_DIR:-$HOME/BirdSongs}/" -type d -empty -mtime +90 -delete - find ${EXTRACTED}/By_Date/ -empty -type d -delete;; + # Skip only THIS loop when there is nothing to walk - never exit the + # script, or we skip the PROCESSED purge below, which is the fallback + # that actually frees space when By_Date is already empty. + if [ "${datedirs}" -gt 0 ]; then + filestodelete=$(( $(find ${EXTRACTED}/By_Date/* -type f | wc -l) / datedirs )) + iter=0 + for i in */*/*; do + if [ $iter -ge $filestodelete ]; then + break + fi + if ! grep -qxFe "$i" $HOME/BirdNET-Pi/scripts/disk_check_exclude.txt; then + rm "$i" + fi + ((iter++)) + done + find "${RECS_DIR:-$HOME/BirdSongs}/" -type d -empty -mtime +90 -delete + find ${EXTRACTED}/By_Date/ -empty -type d -delete + else + echo "No date directories to purge" + fi;; #rm -drfv "$(find ${EXTRACTED}/By_Date/* -maxdepth 1 -type d -prune \ # | sort -r | tail -n1)";; diff --git a/scripts/dump_logs.sh b/scripts/dump_logs.sh index 5d67a6c2a6..9e7428c61b 100755 --- a/scripts/dump_logs.sh +++ b/scripts/dump_logs.sh @@ -39,7 +39,19 @@ SOUND_CARD="$(aplay -L \ | grep -ve 'vc4' -e 'Head' -e 'PCH' \ | uniq)" echo "SOUND_CARD=${SOUND_CARD}" > ${LOG_DIR}/soundcard -script -c "arecord -D ${SOUND_CARD} --dump-hw-params" -a ${LOG_DIR}/soundcard &> /dev/null +# --dump-hw-params opens the capture device, which on a *running* station is +# always held by the recorder, so arecord blocks indefinitely and dump_logs +# never returns - i.e. you could not collect logs from a live station, which is +# exactly when you need them. Bound it, and say so in the output rather than +# silently omitting the section. +if [ -n "${SOUND_CARD}" ]; then + if ! timeout 10 arecord -D "${SOUND_CARD}" --dump-hw-params >> ${LOG_DIR}/soundcard 2>&1; then + echo "(hw params unavailable: device busy or timed out - expected while the recorder is running)" \ + >> ${LOG_DIR}/soundcard + fi +else + echo "(no capture card detected)" >> ${LOG_DIR}/soundcard +fi # Get system info CALLS=("df -h" "free -h" "ifconfig" "find ${RECS_DIR}") diff --git a/scripts/plotly_streamlit.py b/scripts/plotly_streamlit.py index f638fa554b..d631db2d11 100755 --- a/scripts/plotly_streamlit.py +++ b/scripts/plotly_streamlit.py @@ -440,7 +440,12 @@ def hms_to_str(t): fig = go.Figure(data=[heatmap, sunrise_sunset]) number_of_y_ticks = 12 - y_downscale_factor = int(len(saved_time_labels) / number_of_y_ticks) + # max(1, ...): saved_time_labels only covers the 15-min buckets this + # species actually occupies, so a species detected within a <3h window on + # a single day yields <12 columns -> int(n/12) == 0 -> the [::0] slices + # below raise "slice step cannot be zero". That is exactly the rare + # species someone opens this view to look at. + y_downscale_factor = max(1, int(len(saved_time_labels) / number_of_y_ticks)) fig.update_layout( yaxis=dict( tickmode='array', diff --git a/scripts/stop_core_services.sh b/scripts/stop_core_services.sh index 9cd7b01472..c08a056113 100755 --- a/scripts/stop_core_services.sh +++ b/scripts/stop_core_services.sh @@ -1,6 +1,12 @@ #!/usr/bin/env bash # Restarts ALL services and removes ALL unprocessed audio +# This script never sourced the config, and install_config.sh sets RECS_DIR +# WITHOUT export - so ${RECS_DIR} was empty here even when a parent had sourced +# birdnet.conf. The rm below therefore expanded to an absolute path like +# `sudo rm -rf /July-2026/16-Thursday/*`: the documented cleanup silently never +# happened, and it sat one path-layout change away from doing real damage as root. +source /etc/birdnet/birdnet.conf services=(birdnet_recording.service custom_recording.service @@ -11,4 +17,10 @@ spectrogram_viewer.service) for i in "${services[@]}";do sudo systemctl stop ${i} done -sudo rm -rf ${RECS_DIR}/$(date +%B-%Y/%d-%A)/* + +# Refuse to run the rm unless RECS_DIR is actually a real directory. +if [ -z "${RECS_DIR}" ] || [ ! -d "${RECS_DIR}" ]; then + echo "RECS_DIR is unset or not a directory ('${RECS_DIR}') - refusing to purge" >&2 + exit 1 +fi +sudo rm -rf "${RECS_DIR}/$(date +%B-%Y/%d-%A)"/* diff --git a/scripts/update_birdnet_snippets.sh b/scripts/update_birdnet_snippets.sh index fec853fb59..d5e847473a 100755 --- a/scripts/update_birdnet_snippets.sh +++ b/scripts/update_birdnet_snippets.sh @@ -267,6 +267,12 @@ fi sqlite3 $HOME/BirdNET-Pi/scripts/birds.db << EOF CREATE INDEX IF NOT EXISTS "detections_Sci_Name" ON "detections" ("Sci_Name"); +-- createdb.sh DROPs and recreates the table, so it only ever helps NEW installs. +-- Existing databases must be migrated here. See createdb.sh for the rationale: +-- overview.php's correlated subqueries filter on (Sci_Name, Date) together. +CREATE INDEX IF NOT EXISTS "detections_Com_Name" ON "detections" ("Com_Name"); +CREATE INDEX IF NOT EXISTS "detections_Date_Time" ON "detections" ("Date" DESC, "Time" DESC); +CREATE INDEX IF NOT EXISTS "detections_Sci_Date" ON "detections" ("Sci_Name", "Date"); EOF # update snippets above diff --git a/scripts/weekly_report.php b/scripts/weekly_report.php index 2d03fd968a..7c43d200f9 100644 --- a/scripts/weekly_report.php +++ b/scripts/weekly_report.php @@ -27,41 +27,73 @@ function safe_percentage($count, $prior_count) { $db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READONLY); $db->busyTimeout(1000); -$statement1 = $db->prepare('SELECT Sci_Name, Com_Name, COUNT(*) FROM detections WHERE Date BETWEEN "' . date("Y-m-d", $startdate) . '" AND "' . date("Y-m-d", $enddate) . '" GROUP By Sci_Name ORDER BY COUNT(*) DESC'); +$this_start = date("Y-m-d", $startdate); +$this_end = date("Y-m-d", $enddate); +$prev_start = date("Y-m-d", $startdate - (7 * 86400)); +$prev_end = date("Y-m-d", $enddate - (7 * 86400)); + +/* This was 1 + 2N queries: the prior-week count and the first-seen check each + ran once PER SPECIES inside the loop below (~100 species => ~200 extra + prepared statements per report). Pre-aggregate each into a lookup instead, so + the whole report costs 3 grouped queries regardless of species count. + Values are bound rather than interpolated while we're here. */ + +# prior week counts, grouped once +$prior = []; +$statement2 = $db->prepare('SELECT Sci_Name, COUNT(*) AS Count FROM detections WHERE Date BETWEEN :ps AND :pe GROUP BY Sci_Name'); +ensure_db_ok($statement2); +$statement2->bindValue(':ps', $prev_start, SQLITE3_TEXT); +$statement2->bindValue(':pe', $prev_end, SQLITE3_TEXT); +$result2 = $statement2->execute(); +while ($row = $result2->fetchArray(SQLITE3_ASSOC)) { + $prior[$row['Sci_Name']] = $row['Count']; +} + +# first/last detection date per species, grouped once. A species is "first seen" +# when it has no detection outside this week - i.e. its whole range sits inside +# it. Equivalent to the old per-species "COUNT(*) outside the week == 0". +$span = []; +$statement3 = $db->prepare('SELECT Sci_Name, MIN(Date) AS mn, MAX(Date) AS mx FROM detections GROUP BY Sci_Name'); +ensure_db_ok($statement3); +$result3 = $statement3->execute(); +while ($row = $result3->fetchArray(SQLITE3_ASSOC)) { + $span[$row['Sci_Name']] = $row; +} + +$statement1 = $db->prepare('SELECT Sci_Name, Com_Name, COUNT(*) AS Count FROM detections WHERE Date BETWEEN :s AND :e GROUP BY Sci_Name ORDER BY COUNT(*) DESC'); ensure_db_ok($statement1); +$statement1->bindValue(':s', $this_start, SQLITE3_TEXT); +$statement1->bindValue(':e', $this_end, SQLITE3_TEXT); $result1 = $statement1->execute(); $detections = []; while ($detection = $result1->fetchArray(SQLITE3_ASSOC)) { $com_name = $detection["Com_Name"]; $sci_name = $detection["Sci_Name"]; - $scount = $detection["COUNT(*)"]; + $scount = $detection["Count"]; - # previous week - $statement2 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Sci_Name == "' . $detection["Sci_Name"] . '" AND Date BETWEEN "' . date("Y-m-d", $startdate - (7 * 86400)) . '" AND "' . date("Y-m-d", $enddate - (7 * 86400)) . '"'); - ensure_db_ok($statement2); - $result2 = $statement2->execute(); - $priorweekcount = $result2->fetchArray(SQLITE3_ASSOC)['COUNT(*)']; + $priorweekcount = $prior[$sci_name] ?? 0; $percentagediff = safe_percentage($scount, $priorweekcount); - # is_first_seen? - $statement3 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Sci_Name == "'.$sci_name.'" AND Date NOT BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"'); - ensure_db_ok($statement3); - $result3 = $statement3->execute(); - $totalcount = $result3->fetchArray(SQLITE3_ASSOC)['COUNT(*)']; - $is_first_seen = $totalcount === 0; + $is_first_seen = isset($span[$sci_name]) + && $span[$sci_name]['mn'] >= $this_start + && $span[$sci_name]['mx'] <= $this_end; $detections[$com_name] = ["count" => $scount, "percentagediff" => $percentagediff, "is_first_seen" => $is_first_seen]; } -$statement4 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"'); +$statement4 = $db->prepare('SELECT COUNT(*) AS Count FROM detections WHERE Date BETWEEN :s AND :e'); ensure_db_ok($statement4); +$statement4->bindValue(':s', $this_start, SQLITE3_TEXT); +$statement4->bindValue(':e', $this_end, SQLITE3_TEXT); $result4 = $statement4->execute(); -$totalcount = $result4->fetchArray(SQLITE3_ASSOC)['COUNT(*)']; +$totalcount = $result4->fetchArray(SQLITE3_ASSOC)['Count']; -$statement5 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate- (7*86400)).'" AND "'.date("Y-m-d",$enddate- (7*86400)).'"'); +$statement5 = $db->prepare('SELECT COUNT(*) AS Count FROM detections WHERE Date BETWEEN :ps AND :pe'); ensure_db_ok($statement5); +$statement5->bindValue(':ps', $prev_start, SQLITE3_TEXT); +$statement5->bindValue(':pe', $prev_end, SQLITE3_TEXT); $result5 = $statement5->execute(); -$priortotalcount = $result5->fetchArray(SQLITE3_ASSOC)['COUNT(*)']; +$priortotalcount = $result5->fetchArray(SQLITE3_ASSOC)['Count']; $statement6 = $db->prepare('SELECT COUNT(DISTINCT(Sci_Name)) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"'); ensure_db_ok($statement6); From c9d03db570a01cd586bf933bdfa8a82574fc7bb6 Mon Sep 17 00:00:00 2001 From: hydrospheric0 Date: Thu, 16 Jul 2026 15:23:12 -0700 Subject: [PATCH 7/7] Remove comments; make Caddy site block host-agnostic Strip the explanatory comments added across 66eba70, 23c810d, d5b121f, 99dc2ff and 93076c2. They should not have been added: the stated preference for this repo is comment-free code. Pre-existing comments are preserved. The reasoning they carried is recorded in ~/GITHUB/birdnet-optimization-TODO.md instead, where it belongs. update_caddyfile.sh emitted `http:// ${BIRDNETPI_URL}`, pinning the site block to one hardcoded address. The deployed Caddyfile still carried a stale 192.168.12.27 from before BIRDNETPI_URL was corrected, and the host now has several addresses that change with the network (eth0 on one LAN, wlan0 on another). Caddy already listens on *:80, so bind the site to :80 and match any host rather than swapping one hardcoded IP for another that breaks on the next move. Verified: php -l clean on the target PHP 7.4.33, py_compile and bash -n clean. --- homepage/index.php | 4 -- homepage/views.php | 4 -- scripts/advanced.php | 11 ----- scripts/api.php | 12 ------ scripts/birdnet_analysis.py | 20 --------- scripts/birdnet_changeidentification.sh | 7 ---- scripts/cleanup.sh | 2 - scripts/common.php | 55 +------------------------ scripts/config.php | 6 --- scripts/custom_recording.sh | 2 - scripts/disk_check.sh | 11 ----- scripts/dump_logs.sh | 11 ----- scripts/history.php | 3 -- scripts/play.php | 13 ------ scripts/plotly_streamlit.py | 5 --- scripts/restart_services.sh | 2 - scripts/spectrogram.php | 3 -- scripts/spectrogram.sh | 3 -- scripts/stats.php | 2 - scripts/stop_core_services.sh | 6 --- scripts/system_controls.php | 4 -- scripts/todays_detections.php | 6 --- scripts/update_caddyfile.sh | 4 +- scripts/utils/db.py | 4 -- scripts/utils/notifications.py | 5 --- scripts/utils/reporting.py | 11 ----- scripts/weekly_report.php | 12 ------ 27 files changed, 3 insertions(+), 225 deletions(-) diff --git a/homepage/index.php b/homepage/index.php index 3ef31d933a..fbf52eab05 100644 --- a/homepage/index.php +++ b/homepage/index.php @@ -7,10 +7,6 @@ die(); } -/* Prevent XSS input. - FILTER_SANITIZE_STRING is deprecated as of PHP 8.1 and slated for removal, at - which point this would silently stop filtering. The `?: []` matters too: - filter_input_array returns null (not []) when there is no query string. */ $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; require_once 'scripts/common.php'; diff --git a/homepage/views.php b/homepage/views.php index d921429697..0f1f9863fb 100644 --- a/homepage/views.php +++ b/homepage/views.php @@ -1,9 +1,5 @@ with no credentials. So: allow the - loopback caller, require authentication for anyone else. */ function api_is_local() { $ip = $_SERVER['REMOTE_ADDR'] ?? ''; return $ip === '127.0.0.1' || $ip === '::1' || $ip === '::ffff:127.0.0.1'; @@ -31,16 +23,12 @@ function api_is_local() { echo json_encode(["message" => "Unauthorized"]); exit; } - /* Every other call site guards on this; without it the image feature's - off-switch simply did not reach this endpoint. */ if (empty($config["IMAGE_PROVIDER"])) { http_response_code(404); echo "Error 404! Image provider disabled."; exit; } $sci_name = urldecode($matches[1]); - /* Bound the input: a scientific name, not an arbitrary \S+ that becomes a - URL path suffix in the upstream request. */ if (!preg_match('/^[A-Za-z .\'-]{1,64}$/', $sci_name)) { http_response_code(400); echo "Error 400! Invalid species name."; diff --git a/scripts/birdnet_analysis.py b/scripts/birdnet_analysis.py index 74edaedcec..86105ea5dd 100644 --- a/scripts/birdnet_analysis.py +++ b/scripts/birdnet_analysis.py @@ -36,9 +36,6 @@ def main(): backlog = get_wav_files() - # maxsize bounds the queue so reporting cannot fall behind: put() blocks once - # a chunk is already waiting. This replaces an explicit join() per file, which - # forced analysis and reporting to run strictly serially. report_queue = Queue(maxsize=1) thread = threading.Thread(target=handle_reporting_queue, args=(report_queue, )) thread.start() @@ -93,18 +90,12 @@ def process_file(file_name, report_queue): analyzing.write(file_name) file = ParseFileName(file_name) detections = run_analysis(file) - # The queue is bounded (maxsize=1), so this blocks only if reporting is a - # full chunk behind - same guarantee the old join() gave, but the next - # chunk's inference can overlap this chunk's reporting. report_queue.put((file, detections)) enqueued = True except Exception as e: stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" log.exception(f'Unexpected error: {stderr}', exc_info=e) finally: - # On success the reporting thread owns the file and removes it there. - # Only clean up here when we failed before handing it off - otherwise a - # failed analysis strands the wav forever (nothing else reaps StreamData). if not enqueued: try: os.remove(file_name) @@ -124,11 +115,6 @@ def handle_reporting_queue(queue): update_json_file(file, detections) reported = [] for detection in detections: - # Contain per detection: write_to_db now raises on persistent - # failure, and without this one bad row would drop every later - # detection in the chunk AND skip apprise/bird_weather/heartbeat - # below - a wider desync than the silent drop it replaced, and a - # missed heartbeat can trip a false "station down" alert. try: detection.file_name_extr = extract_detection(file, detection) log.info('%s;%s', summary(file, detection), os.path.basename(detection.file_name_extr)) @@ -137,9 +123,6 @@ def handle_reporting_queue(queue): reported.append(detection) except Exception as e: log.exception('dropping detection %s', detection.common_name, exc_info=e) - # Only pass on detections that actually made it: apprise() and - # bird_weather() read detection.file_name_extr, which is unset if - # extract_detection() was the thing that failed. if reported: apprise(file, reported) bird_weather(file, reported) @@ -148,9 +131,6 @@ def handle_reporting_queue(queue): stderr = e.stderr.decode('utf-8') if isinstance(e, CalledProcessError) else "" log.exception(f'Unexpected error: {stderr}', exc_info=e) finally: - # This is the ONLY place StreamData wavs get removed (cleanup.sh only - # reaps PROCESSED), so it must run even when reporting above fails - - # otherwise any error strands the wav permanently. try: os.remove(file.file_name) except OSError: diff --git a/scripts/birdnet_changeidentification.sh b/scripts/birdnet_changeidentification.sh index 5f62634580..992cb2a25c 100755 --- a/scripts/birdnet_changeidentification.sh +++ b/scripts/birdnet_changeidentification.sh @@ -48,9 +48,6 @@ elif [[ "$2" != *"_"* ]]; then fi # Check if $NEWNAME is found in the file $LABELS_FILE -# -F: without it the name is treated as a REGEX, so a crafted value could satisfy -# this guard via alternation/optional groups while still smuggling a quote into -# the SQL built below. -- stops a leading dash being read as an option. if ! grep -qF -- "$NEWNAME" "$LABELS_FILE"; then echo "Error: $NEWNAME not found in $LABELS_FILE" exit 1 @@ -67,10 +64,6 @@ fi # EXECUTE SCRIPT # ################## -# SQL-escape a value for a single-quoted sqlite literal by doubling any quote. -# The caller (play.php) escapeshellarg's these, which protects the SHELL layer - -# but the values then land raw inside the SQL below, against a DB opened for -# WRITE. Shell escaping is not SQL escaping. sql_lit() { printf '%s' "${1//\'/\'\'}"; } # Intro diff --git a/scripts/cleanup.sh b/scripts/cleanup.sh index 2d585dc7df..35ab881c86 100755 --- a/scripts/cleanup.sh +++ b/scripts/cleanup.sh @@ -1,7 +1,5 @@ #!/usr/bin/env bash source /etc/birdnet/birdnet.conf -# set -x # was unconditional: this runs on a timer/at every restart, and every -# traced line is a journal write (SD-card wear). Uncomment to debug. cd "${PROCESSED}" || exit 1 empties=($(find ${PROCESSED} -size 57c)) diff --git a/scripts/common.php b/scripts/common.php index aef0916be3..ef5478b67b 100644 --- a/scripts/common.php +++ b/scripts/common.php @@ -2,8 +2,6 @@ define('__ROOT__', dirname(dirname(__FILE__))); -/* PHP 8 string helpers, polyfilled for PHP 7.4 (Debian 11 ships 7.4). - Guarded so this stays correct if/when the host moves to PHP 8+. */ if (!function_exists('str_contains')) { function str_contains($haystack, $needle) { return $needle === '' || strpos($haystack, $needle) !== false; @@ -23,54 +21,28 @@ function str_ends_with($haystack, $needle) { if (session_status() !== PHP_SESSION_ACTIVE) session_start(); -/* ---------- birdnet.conf value sanitisers ---------- - /etc/birdnet/birdnet.conf has three consumers with three different parsers: - - bash `source /etc/birdnet/birdnet.conf` (restart_services.sh et al) - - PHP parse_ini_string() (get_config below) - - python ConfigParser + value.strip('"') (utils/helpers.py) - That forces the KEY="value" convention: single-quoting would be shell-safe but - python only strips double quotes, so 'x' would arrive as a literal "'x'". - And inside bash double quotes $(...), `...` and $VAR still expand - so the - file being sourced means quoting alone cannot make a value safe. - Therefore: sanitise values at the point they are read from $_GET. - This also removes the preg_replace() backreference hazard for free, since a - sanitised value can no longer contain '$' or '\'. */ - -/* Free text destined for a double-quoted value. */ + function conf_safe_string($v) { $v = (string)$v; - // Everything bash would still act on inside double quotes. $v = str_replace(array('"', '$', '`', '\\'), '', $v); - // A newline would inject an entirely new assignment line. return trim(preg_replace('/[\r\n]+/', ' ', $v)); } -/* A bare, unquoted numeric value. - Pass the CURRENT config value as $default: on a rejected input we must not - silently write a plausible-looking constant. '0' is outside the legal range - for SENSITIVITY (0.5-1.5) and would mean "record everything" for CONFIDENCE. - Keeping the existing value preserves "never write an unsafe value" without - destroying a working configuration. - Accepts a leading '.' (".5") and a trailing '.' which bash/INI tolerate. */ function conf_safe_number($v, $default = '0') { $v = trim((string)$v); return preg_match('/^-?(\d+(\.\d*)?|\.\d+)$/', $v) ? $v : $default; } -/* A bare, unquoted identifier (model names, colour schemes, ids, ...). */ function conf_safe_token($v, $default = '') { $v = trim((string)$v); return preg_match('/^[A-Za-z0-9._@+-]*$/', $v) ? $v : $default; } -/* A bare, unquoted host / URL (BIRDNETPI_URL). */ function conf_safe_url($v, $default = '') { $v = trim((string)$v); return preg_match('#^[A-Za-z0-9._:/\[\]-]*$#', $v) ? $v : $default; } -/* An ALSA device id, e.g. "default" or "plughw:CARD=MeC,DEV=0". Needs : = , - which conf_safe_token would reject, but must still exclude shell metachars. */ function conf_safe_device($v, $default = 'default') { $v = trim((string)$v); return preg_match('/^[A-Za-z0-9_:=,.-]*$/', $v) ? $v : $default; @@ -163,8 +135,6 @@ function debug_log($message) { } function get_com_en_name($sci_name) { - /* static: the label file is ~331KB. Without it the cache never survives the - call and we re-read + re-decode it once per detection row. */ static $_labels_flickr = null; if ($_labels_flickr === null) { $_labels_flickr = json_decode(file_get_contents(get_home() . "/BirdNET-Pi/model/l18n/labels_en.json"), true) ?: []; @@ -194,7 +164,6 @@ function get_label($record, $sort_by, $date=null) { } function get_db() { - /* static: otherwise every caller opens its own SQLite handle. */ static $_db = null; if ($_db === null) { $_db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READONLY); @@ -203,13 +172,6 @@ function get_db() { return $_db; } -/* These three used prepare() with the value interpolated straight into the SQL, - which makes prepare() decorative - no placeholder, no bind. Callers reach them - with htmlspecialchars_decode($_GET[...]), which deliberately restores the very - quote characters the input filter had encoded, so the string literal could be - closed. Bind properly instead; species_tools.php already did it this way. - $sort_by/$date only ever select a fixed branch or a bound value - they never - reach the SQL text. */ function fetch_species_array($sort_by, $date=null) { $db = get_db(); @@ -307,10 +269,6 @@ class ImageProvider { public function __construct() { $this->set_db(); - /* An explicit timeout matters: these are blocking outbound fetches made from - inside a PHP-FPM worker. Without it they inherit default_socket_timeout - (60s), so a slow upstream pins a worker for a minute - and on a 1GB Pi the - worker pool is small enough that a handful of those stall the whole UI. */ $opts = ['http' => [ 'header' => "User-Agent: BirdNET-Pi", 'timeout' => 5, @@ -522,9 +480,6 @@ class Wikipedia extends ImageProvider { protected $db_path = __ROOT__ . '/scripts/wikipedia.db'; protected function get_from_source($sci_name) { - /* rawurlencode: this value becomes a path segment in the upstream request. - Unencoded, dot-segments and query separators in the name let a caller - reach arbitrary paths on the target host. */ $page_title = rawurlencode(str_replace(' ', '_', $sci_name)); $data = $this->get_json("https://en.wikipedia.org/api/rest_v1/page/summary/$page_title"); if ($data == false or !isset($data['originalimage'])) @@ -588,16 +543,8 @@ function get_info_url($sciname){ $engname = get_com_en_name($sciname); $config = get_config(); if ($config['INFO_SITE'] === 'EBIRD'){ - /* `require` (not require_once) inside the function body rebuilt this ~6,500 - entry / 243KB array literal on EVERY call - and callers invoke this once - per rendered row. Load it once into a static. - Also __DIR__: the old relative path silently depended on the caller's CWD - being homepage/. */ static $ebirds_cache = null; if ($ebirds_cache === null) { - /* plain require, guarded by the static: require_once would silently become - a no-op (leaving $ebirds undefined) if anything else ever includes this - file first. The static already guarantees we only pay for it once. */ $ebirds = null; require __DIR__ . '/ebird.php'; $ebirds_cache = $ebirds; diff --git a/scripts/config.php b/scripts/config.php index a26295b1d9..86082281d8 100644 --- a/scripts/config.php +++ b/scripts/config.php @@ -55,14 +55,10 @@ function syslog_shell_exec($cmd, $sudo_user = null) { # Basic Settings if(isset($_GET["latitude"])){ - /* Everything below lands in /etc/birdnet/birdnet.conf, which bash `source`s - - so an unsanitised value here is remote code execution (e.g. LATITUDE=$(id)). - Sanitise by type at the point of read; see conf_safe_* in common.php. */ $latitude = conf_safe_number($_GET["latitude"], $config['LATITUDE'] ?? '0'); $longitude = conf_safe_number($_GET["longitude"], $config['LONGITUDE'] ?? '0'); $site_name = conf_safe_string($_GET["site_name"] ?? ''); $birdweather_id = conf_safe_token($_GET["birdweather_id"] ?? ''); - /* written to apprise.txt / body.txt, not to the sourced conf */ $apprise_input = $_GET['apprise_input'] ?? ''; $apprise_notification_title = conf_safe_string($_GET['apprise_notification_title'] ?? ''); $apprise_notification_body = htmlspecialchars_decode($_GET['apprise_notification_body'] ?? '', ENT_QUOTES); @@ -81,8 +77,6 @@ function syslog_shell_exec($cmd, $sudo_user = null) { } else { $data_model_version = 1; } - /* decode first so apostrophes in species names survive ("Anna's Hummingbird"), - then strip what bash would still expand inside the double-quoted value */ $only_notify_species_names = conf_safe_string(htmlspecialchars_decode($_GET['only_notify_species_names'] ?? '', ENT_QUOTES)); $only_notify_species_names_2 = conf_safe_string(htmlspecialchars_decode($_GET['only_notify_species_names_2'] ?? '', ENT_QUOTES)); diff --git a/scripts/custom_recording.sh b/scripts/custom_recording.sh index eed55d7ccf..94b7c10c90 100755 --- a/scripts/custom_recording.sh +++ b/scripts/custom_recording.sh @@ -1,6 +1,4 @@ #!/usr/bin/env bash -# set -x # was unconditional: this runs on a timer/at every restart, and every -# traced line is a journal write (SD-card wear). Uncomment to debug. source /etc/birdnet/birdnet.conf STAMP="%H:%M:%S" diff --git a/scripts/disk_check.sh b/scripts/disk_check.sh index fbc0ed4a69..e3178502d1 100755 --- a/scripts/disk_check.sh +++ b/scripts/disk_check.sh @@ -1,6 +1,4 @@ #!/usr/bin/env bash -# set -x # was unconditional: this runs on a timer/at every restart, and every -# traced line is a journal write (SD-card wear). Uncomment to debug. source /etc/birdnet/birdnet.conf @@ -23,12 +21,6 @@ if [ "${used}" -ge "$purge_threshold" ]; then exit fi datedirs=$(find ${EXTRACTED}/By_Date/* -maxdepth 0 -type d 2>/dev/null | wc -l) - # Guard the divisor: with no date dirs this was a division by zero, which - # left filestodelete empty and made the [ -ge ] test below error instead - # of ever breaking out of the loop. - # Skip only THIS loop when there is nothing to walk - never exit the - # script, or we skip the PROCESSED purge below, which is the fallback - # that actually frees space when By_Date is already empty. if [ "${datedirs}" -gt 0 ]; then filestodelete=$(( $(find ${EXTRACTED}/By_Date/* -type f | wc -l) / datedirs )) iter=0 @@ -54,9 +46,6 @@ if [ "${used}" -ge "$purge_threshold" ]; then esac fi sleep 1 -# Re-measure: the purge above may already have freed enough. Re-using the stale -# reading made this second, more destructive purge (rm -rf $PROCESSED) fire -# unconditionally whenever the first one did. used="$(disk_used_pct)" if [ "${used}" -ge "$purge_threshold" ]; then case $FULL_DISK in diff --git a/scripts/dump_logs.sh b/scripts/dump_logs.sh index 9e7428c61b..515f7e20b3 100755 --- a/scripts/dump_logs.sh +++ b/scripts/dump_logs.sh @@ -4,10 +4,6 @@ source /etc/birdnet/birdnet.conf &> /dev/null LOG_DIR="${HOME}/BirdNET-Pi/logs" my_dir=$HOME/BirdNET-Pi/scripts -# Must be an ARRAY: as a plain string, "${services[@]}" below expands to a single -# element holding every service name joined by newlines, so the -L test never -# matched and the bundle shipped with no journals at all. (uninstall.sh does this -# correctly.) services=($(awk '/service/ && /systemctl/ && !/php/ {print $3}' ${my_dir}/install_services.sh | sort -u)) # Create logs directory @@ -22,8 +18,6 @@ for i in "${services[@]}";do done # Create password-removed birdnet.conf -# Prefer the canonical location the rest of the tree sources; fall back to the -# in-tree copy so this keeps working on older layouts. CONF=/etc/birdnet/birdnet.conf [ -f "${CONF}" ] || CONF="${HOME}/BirdNET-Pi/birdnet.conf" sed -e '/PWD=/d' "${CONF}" > ${LOG_DIR}/birdnet.conf @@ -39,11 +33,6 @@ SOUND_CARD="$(aplay -L \ | grep -ve 'vc4' -e 'Head' -e 'PCH' \ | uniq)" echo "SOUND_CARD=${SOUND_CARD}" > ${LOG_DIR}/soundcard -# --dump-hw-params opens the capture device, which on a *running* station is -# always held by the recorder, so arecord blocks indefinitely and dump_logs -# never returns - i.e. you could not collect logs from a live station, which is -# exactly when you need them. Bound it, and say so in the output rather than -# silently omitting the section. if [ -n "${SOUND_CARD}" ]; then if ! timeout 10 arecord -D "${SOUND_CARD}" --dump-hw-params >> ${LOG_DIR}/soundcard 2>&1; then echo "(hw params unavailable: device busy or timed out - expected while the recorder is running)" \ diff --git a/scripts/history.php b/scripts/history.php index 4596c61026..d304408c2b 100644 --- a/scripts/history.php +++ b/scripts/history.php @@ -4,9 +4,6 @@ $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?: []; -/* error_reporting is process-global and this file is include()d by views.php, so - E_ALL + display_errors here sprayed notices (and absolute filesystem paths) - into the rendered page for the rest of the request. Match every other view. */ error_reporting(E_ERROR); ini_set('display_errors', 0); require_once 'scripts/common.php'; diff --git a/scripts/play.php b/scripts/play.php index aac21da93f..3d30ba1151 100644 --- a/scripts/play.php +++ b/scripts/play.php @@ -11,12 +11,6 @@ $config = get_config(); $user = get_user(); -/* Reject a user-supplied relative path that could escape its base directory. - This guard was previously inline (and duplicated) on the delete and rename - paths, while the shift path had none at all - hence the drift. Keep one - copy so every caller gets the same rules. - NB FILTER_SANITIZE_FULL_SPECIAL_CHARS above encodes & < > " ' but NOT - ; | ` $ ( ) or newline, so it is not a substitute for this. */ function reject_unsafe_relpath($p) { return $p === '' || $p === null || str_contains($p, "\0") @@ -35,9 +29,6 @@ function reject_unsafe_relpath($p) { die(); } $db_writable = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_READWRITE); - /* was setting the timeout on $db (the read-only handle), leaving the writable - one with none - so the DELETE below failed instantly with SQLITE_BUSY - exactly when the analysis service was mid-insert. */ $db_writable->busyTimeout(1000); $statement1 = $db_writable->prepare('DELETE FROM detections WHERE File_Name = :file_name LIMIT 1'); ensure_db_ok($statement1); @@ -124,8 +115,6 @@ function reject_unsafe_relpath($p) { ensure_authenticated('You cannot shift files for this installation'); $filename = urldecode($_GET['shiftfile']); - /* Previously unvalidated: $dir below is derived from this and was - concatenated raw into a shell_exec running under sudo. */ if (reject_unsafe_relpath($filename)) { echo "Error"; die(); @@ -139,8 +128,6 @@ function reject_unsafe_relpath($p) { if(isset($_GET['doshift'])) { $freqshift_tool = $config['FREQSHIFT_TOOL']; - /* These come from birdnet.conf, which the settings pages write - so they are - not inherently trustworthy either. Escape rather than interpolate raw. */ $mkdir_cmd = "sudo mkdir -p ".escapeshellarg($shifted_path.$dir); if ($freqshift_tool == "ffmpeg") { diff --git a/scripts/plotly_streamlit.py b/scripts/plotly_streamlit.py index d631db2d11..bf65cad801 100755 --- a/scripts/plotly_streamlit.py +++ b/scripts/plotly_streamlit.py @@ -440,11 +440,6 @@ def hms_to_str(t): fig = go.Figure(data=[heatmap, sunrise_sunset]) number_of_y_ticks = 12 - # max(1, ...): saved_time_labels only covers the 15-min buckets this - # species actually occupies, so a species detected within a <3h window on - # a single day yields <12 columns -> int(n/12) == 0 -> the [::0] slices - # below raise "slice step cannot be zero". That is exactly the rare - # species someone opens this view to look at. y_downscale_factor = max(1, int(len(saved_time_labels) / number_of_y_ticks)) fig.update_layout( yaxis=dict( diff --git a/scripts/restart_services.sh b/scripts/restart_services.sh index 7748c96755..55f421724f 100755 --- a/scripts/restart_services.sh +++ b/scripts/restart_services.sh @@ -1,8 +1,6 @@ #!/usr/bin/env bash # Restarts ALL services and removes ALL unprocessed audio source /etc/birdnet/birdnet.conf -# set -x # was unconditional: this runs on a timer/at every restart, and every -# traced line is a journal write (SD-card wear). Uncomment to debug. my_dir=$HOME/BirdNET-Pi/scripts diff --git a/scripts/spectrogram.php b/scripts/spectrogram.php index 52ce5a3920..92230d01c2 100644 --- a/scripts/spectrogram.php +++ b/scripts/spectrogram.php @@ -20,9 +20,6 @@ $look_in_directory = $STREAM_DATA_DIR; $files = glob($look_in_directory . "*.wav.json"); if (count($files) !== 0) { - /* glob() sorts ascending and the names are date-time prefixed, so $files[0] - was the OLDEST - despite the variable name, and despite the RTSP branch - below deliberately keeping the newest. Take the last entry. */ $newest_file = end($files); reset($files); } diff --git a/scripts/spectrogram.sh b/scripts/spectrogram.sh index df752a9f61..5acbe387bc 100755 --- a/scripts/spectrogram.sh +++ b/scripts/spectrogram.sh @@ -15,9 +15,6 @@ fi next=0 looptime=$(( RECORDING_LENGTH * 2 / 3 )) -# Derive from RECS_DIR so this stays in step with the python side -# (utils/helpers.py:get_analyzing_now_path). Hardcoding $HOME/BirdSongs meant a -# relocated RECS_DIR silently broke the watch. ANALYZING_NOW="${RECS_DIR:-$HOME/BirdSongs}/StreamData/analyzing_now.txt" touch "${ANALYZING_NOW}" diff --git a/scripts/stats.php b/scripts/stats.php index a86ac7382e..5c8de077af 100644 --- a/scripts/stats.php +++ b/scripts/stats.php @@ -194,8 +194,6 @@ function setModalText(iter, title, text, authorlink) {
    reset(); while($results=$result->fetchArray(SQLITE3_ASSOC)) { diff --git a/scripts/stop_core_services.sh b/scripts/stop_core_services.sh index c08a056113..a25ccbc84a 100755 --- a/scripts/stop_core_services.sh +++ b/scripts/stop_core_services.sh @@ -1,11 +1,6 @@ #!/usr/bin/env bash # Restarts ALL services and removes ALL unprocessed audio -# This script never sourced the config, and install_config.sh sets RECS_DIR -# WITHOUT export - so ${RECS_DIR} was empty here even when a parent had sourced -# birdnet.conf. The rm below therefore expanded to an absolute path like -# `sudo rm -rf /July-2026/16-Thursday/*`: the documented cleanup silently never -# happened, and it sat one path-layout change away from doing real damage as root. source /etc/birdnet/birdnet.conf services=(birdnet_recording.service @@ -18,7 +13,6 @@ for i in "${services[@]}";do sudo systemctl stop ${i} done -# Refuse to run the rm unless RECS_DIR is actually a real directory. if [ -z "${RECS_DIR}" ] || [ ! -d "${RECS_DIR}" ]; then echo "RECS_DIR is unset or not a directory ('${RECS_DIR}') - refusing to purge" >&2 exit 1 diff --git a/scripts/system_controls.php b/scripts/system_controls.php index 0d2cfe8443..37cdeaa0f5 100644 --- a/scripts/system_controls.php +++ b/scripts/system_controls.php @@ -7,10 +7,6 @@ $user = get_user(); $home = get_home(); -/* This used to run a *blocking, networked* `git fetch` on every single render, - so with a slow or absent uplink the page hung for the full DNS+TCP timeout. - views.php already solved this: background the fetch and cache the result in - the session for a day. Reuse that instead of duplicating it differently. */ $num_commits_behind = $_SESSION['behind'] ?? '0'; if (!isset($_SESSION['behind']) || !isset($_SESSION['behind_time']) || time() > $_SESSION['behind_time'] + 86400) { diff --git a/scripts/todays_detections.php b/scripts/todays_detections.php index 81e16ecc14..069aa4ac12 100644 --- a/scripts/todays_detections.php +++ b/scripts/todays_detections.php @@ -129,9 +129,6 @@ function relativeTime($ts) if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" ) { $searchterm = null; if(isset($_GET['searchterm'])) { - /* Decode first: the input filter turns ' into ', so searching for - e.g. "Anna's Hummingbird" was matching the literal ' and always - returned nothing. */ $searchterm = htmlspecialchars_decode($_GET['searchterm'], ENT_QUOTES); if(strtolower(explode(" ", $searchterm)[0]) == "not") { $not = "NOT "; @@ -141,9 +138,6 @@ function relativeTime($ts) $not = ""; $operator = "OR"; } - /* Bound below - previously the raw value was concatenated into the LIKE - literal, which only the input filter's quote-encoding kept from being a - live injection. $not/$operator are internal constants, not user input. */ $searchquery = "AND (Com_name ".$not."LIKE :term ".$operator." Sci_name ".$not."LIKE :term ".$operator." Confidence ".$not."LIKE :term ".$operator." File_Name ".$not."LIKE :term ".$operator." Time ".$not."LIKE :term)"; } else { $searchquery = ""; diff --git a/scripts/update_caddyfile.sh b/scripts/update_caddyfile.sh index 3f5e7016bf..4ab96bb509 100755 --- a/scripts/update_caddyfile.sh +++ b/scripts/update_caddyfile.sh @@ -9,7 +9,7 @@ fi if ! [ -z ${CADDY_PWD} ];then HASHWORD=$(caddy hash-password --plaintext ${CADDY_PWD}) cat << EOF > /etc/caddy/Caddyfile -http:// ${BIRDNETPI_URL} { +:80 { root * ${EXTRACTED} file_server browse handle /By_Date/* { @@ -45,7 +45,7 @@ http:// ${BIRDNETPI_URL} { EOF else cat << EOF > /etc/caddy/Caddyfile -http:// ${BIRDNETPI_URL} { +:80 { root * ${EXTRACTED} file_server browse handle /By_Date/* { diff --git a/scripts/utils/db.py b/scripts/utils/db.py index 127a720c87..c0e2828525 100644 --- a/scripts/utils/db.py +++ b/scripts/utils/db.py @@ -19,10 +19,6 @@ def get_db(): def get_records(select_sql): - # Previously this swallowed the error, slept 2s (in the analysis critical - # path, retrying nothing) and returned [] - which callers cannot tell apart - # from a genuine "no rows", so a DB hiccup silently dropped notifications. - # Log properly and let the caller's handler decide. con = get_db() try: cur = con.execute(select_sql) diff --git a/scripts/utils/notifications.py b/scripts/utils/notifications.py index 30db523926..1a473ed228 100644 --- a/scripts/utils/notifications.py +++ b/scripts/utils/notifications.py @@ -97,9 +97,6 @@ def render_template(template, reason=""): resp = requests.get(url=url, timeout=10).json() images[com_name] = resp['data']['image_url'] except Exception as e: - # Cache the failure too. Otherwise a down image API means a fresh - # 10s timeout on EVERY detection of this species, in the analysis - # critical path. images[com_name] = "" log.warning("image API lookup failed for %s: %s", sci_name, e) image_url = images.get(com_name, "") @@ -113,8 +110,6 @@ def render_template(template, reason=""): APPRISE_NOTIFICATION_NEW_SPECIES_DAILY_COUNT_LIMIT = 1 # Notifies the first N per day. if settings_dict.get('APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY') == "1": - # A failed count must only skip this notification - never abort the - # caller's reporting for the detection as a whole. try: numberDetections = get_todays_count_for(sci_name) except sqlite3.Error: diff --git a/scripts/utils/reporting.py b/scripts/utils/reporting.py index c23a2b3451..08ebc03c97 100644 --- a/scripts/utils/reporting.py +++ b/scripts/utils/reporting.py @@ -54,8 +54,6 @@ def spectrogram(in_file, title, comment, raw=0): '-t', '', '-c', '', '-o', tmp_file] args += ['-r'] if int(raw) else [] - # /tmp is a tmpfs, so a leaked temp file is leaked RAM. sox failing - # (check=True) or the RuntimeError below must not skip the cleanup. try: result = subprocess.run(args, check=True, capture_output=True) ret = result.stdout.decode('utf-8') @@ -101,19 +99,13 @@ def write_to_db(file: ParseFileName, detection: Detection): last_error = None for attempt_number in range(3): try: - # `with` closes the connection even when execute/commit raises, which - # is exactly the contended case this retry loop exists for. with closing(sqlite3.connect(DB_PATH, timeout=5)) as con: - # Let SQLite wait out a competing writer instead of failing instantly. con.execute("PRAGMA busy_timeout=5000") cur = con.cursor() cur.execute("INSERT INTO detections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (detection.date, detection.time, detection.scientific_name, detection.common_name, detection.confidence, conf['LATITUDE'], conf['LONGITUDE'], conf['CONFIDENCE'], str(detection.week), conf['SENSITIVITY'], conf['OVERLAP'], os.path.basename(detection.file_name_extr))) - # (Date, Time, Sci_Name, Com_Name, str(score), - # Lat, Lon, Cutoff, Week, Sens, - # Overlap, File_Name)) con.commit() return @@ -121,9 +113,6 @@ def write_to_db(file: ParseFileName, detection: Detection): last_error = e log.warning("Database busy (attempt %d/3): %s", attempt_number + 1, e) sleep(2) - # Previously the loop just fell through here: the detection was dropped from - # the DB while its wav/extraction/spectrogram/BirdDB.txt line all still - # existed, silently desyncing the DB from the filesystem. Fail loudly instead. raise RuntimeError( f'failed to write detection {detection.common_name} ' f'({detection.file_name_extr}) to the database after 3 attempts' diff --git a/scripts/weekly_report.php b/scripts/weekly_report.php index 7c43d200f9..a05d963f99 100644 --- a/scripts/weekly_report.php +++ b/scripts/weekly_report.php @@ -1,7 +1,4 @@ ~200 extra - prepared statements per report). Pre-aggregate each into a lookup instead, so - the whole report costs 3 grouped queries regardless of species count. - Values are bound rather than interpolated while we're here. */ -# prior week counts, grouped once $prior = []; $statement2 = $db->prepare('SELECT Sci_Name, COUNT(*) AS Count FROM detections WHERE Date BETWEEN :ps AND :pe GROUP BY Sci_Name'); ensure_db_ok($statement2); @@ -49,9 +40,6 @@ function safe_percentage($count, $prior_count) { $prior[$row['Sci_Name']] = $row['Count']; } -# first/last detection date per species, grouped once. A species is "first seen" -# when it has no detection outside this week - i.e. its whole range sits inside -# it. Equivalent to the old per-species "COUNT(*) outside the week == 0". $span = []; $statement3 = $db->prepare('SELECT Sci_Name, MIN(Date) AS mn, MAX(Date) AS mx FROM detections GROUP BY Sci_Name'); ensure_db_ok($statement3);