-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.php
More file actions
3112 lines (3060 loc) · 135 KB
/
sql.php
File metadata and controls
3112 lines (3060 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
error_reporting(E_ALL);
if(!extension_loaded('mysqli') && !extension_loaded('pdo_mysql')) die('Install mysqli or pdo_mysql extension!');
session_name('SQL');
session_start();
$bg=2;
$step=20;
$version="3.26";
$bbs=['False','True'];
$deny=['mysql','information_schema','performance_schema','sys'];
class DBT {
public static $sqltype=['mysqli','pdo_mysql'];
private $_cnx,$_query,$_fetch=[],$_num_col,$dbty;
private static $instance=NULL;
public static function factory($host,$user,$pwd,$db=''){
if(!isset(self::$instance))
try{
self::$instance=new DBT($host,$user,$pwd,$db);
}catch(Exception $ex){
return false;
}
return self::$instance;
}
public function __construct($host,$user,$pwd,$db){
$ty=self::$sqltype;
if(extension_loaded($ty[0])) $this->dbty=$ty[0];
else $this->dbty=$ty[1];
$host=explode(":",$host);
if($this->dbty==self::$sqltype[0]){
mysqli_report(MYSQLI_REPORT_ALL);
$this->_cnx=new mysqli($host[0],$user,$pwd,$db,empty($host[1])?3306:$host[1]);
mysqli_report(MYSQLI_REPORT_OFF);
}else{
$this->_cnx=new PDO("mysql:host=".$host[0].";port=".(empty($host[1])?3306:$host[1]).";dbname=".$db,$user,$pwd);
$this->_cnx->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
}
public function db($db){
return $this->_cnx->query("USE `$db`");
}
public function query($sql){
try{
if($this->dbty==self::$sqltype[0]){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->_query=$this->_cnx->query($sql);
mysqli_report(MYSQLI_REPORT_OFF);
}else{
$this->_query=$this->_cnx->query($sql);
}
return $this;
}catch(Exception $e){
return false;
}
}
public function begin(){
if($this->dbty==self::$sqltype[0]){
$this->_cnx->autocommit(FALSE);
return $this->_cnx->begin_transaction();
}else{
return $this->_cnx->beginTransaction();
}
}
public function commit(){
return $this->_cnx->commit();
}
public function last(){
if($this->dbty==self::$sqltype[0]) return $this->_cnx->affected_rows;
else return $this->_query->rowCount();
}
public function fetch($mode=0){
$res=[];
if($this->dbty==self::$sqltype[0]){
if($mode==1){
while($row=$this->_query->fetch_row()){
$res[]=$row;
}
}elseif($mode==2){
while($row=$this->_query->fetch_assoc()){
$res[]=$row;
}
}else{
return $this->_query->fetch_row();
}
return $res;
}else{
if($mode==1 || $mode==2){
switch($mode){
case 1: $this->_query->setFetchMode(PDO::FETCH_NUM); break;
case 2: $this->_query->setFetchMode(PDO::FETCH_ASSOC); break;
}
return $this->_query->fetchAll();
}else{
return $this->_query->fetch(PDO::FETCH_NUM);
}
}
}
public function num_row(){
if($this->dbty==self::$sqltype[0]) return $this->_query->num_rows;
else return $this->_query->rowCount();
}
public function num_col(){
if($this->dbty==self::$sqltype[0]) return $this->_query->field_count;
else return $this->_query->columnCount();
}
}
class ED {
public $con,$path,$sg,$u_db,$fieldtype,$sqlda;
public function __construct(){
$pi=(isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'));
$this->sg=preg_split('!/!',$pi,-1,PREG_SPLIT_NO_EMPTY);
$scheme='http'.(empty($_SERVER['HTTPS'])===true || $_SERVER['HTTPS']==='off' ? '' : 's').'://';
$r_uri=isset($_SERVER['PATH_INFO'])===true ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];
$script=$_SERVER['SCRIPT_NAME'];
$this->path=$scheme.$_SERVER['HTTP_HOST'].(strpos($r_uri,$script)===0 ? $script : rtrim(dirname($script),'/.\\')).'/';
$this->fieldtype=['Numbers'=>['INT','TINYINT','SMALLINT','MEDIUMINT','BIGINT','DOUBLE','DECIMAL','FLOAT'],'Strings'=>['VARCHAR','CHAR','TEXT','TINYTEXT','MEDIUMTEXT','LONGTEXT'],'DateTime'=>['DATE','DATETIME','TIME','TIMESTAMP','YEAR'],'Binary'=>['BIT','BLOB','TINYBLOB','MEDIUMBLOB','LONGBLOB'],'Lists'=>['ENUM','SET'],'Spatial'=>['GEOMETRY','POINT','LINESTRING','POLYGON','MULTIPOINT','MULTILINESTRING','MULTIPOLYGON','GEOMETRYCOLLECTION']];
$this->sqlda=['CONTAINS SQL'=>'CONTAINS SQL','NO SQL'=>'NO SQL','READS SQL DATA'=>'READS SQL DATA','MODIFIES SQL DATA'=>'MODIFIES SQL DATA'];
}
public function sanitize($el){
return preg_replace(['/[^A-Za-z0-9]/'],'_',trim($el));
}
public function utf($fi){
if(function_exists("iconv") && preg_match("~^\xFE\xFF|^\xFF\xFE~",$fi)) $fi=iconv("utf-16","utf-8",$fi);
return $fi;
}
public function form($url,$enc=''){
return "<form action='".$this->path.$url."' method='post'".($enc==1 ? " enctype='multipart/form-data'":"").">";
}
public function fieldtypes($slct=''){
$ft='';
foreach($this->fieldtype as $fdk=>$fdtype){
if(is_array($fdtype)){
$ft.="<optgroup label='$fdk'>";
foreach($fdtype as $fdty) $ft.="<option value='$fdty'".(($slct!='' && $fdty==$slct)?" selected":"").">$fdty</option>";
$ft.="</optgroup>";
}
}
return $ft;
}
public function post($idxk='',$op=''){
if($idxk==='' && !empty($_POST)) return ($_SERVER['REQUEST_METHOD']==='POST' ? TRUE : FALSE);
if(!isset($_POST[$idxk])) return FALSE;
if(is_array($_POST[$idxk])){
if(isset($op) && is_numeric($op)){
return $_POST[$idxk][$op];
}else{
$aout=[];
foreach($_POST[$idxk] as $key=>$val){
if($val !='') $aout[$key]=$val;
}
}
}else $aout=$_POST[$idxk];
if($op=='i') return isset($aout);
if($op=='e') return empty($aout);
if($op=='!i') return !isset($aout);
if($op=='!e') return !empty($aout);
return $aout;
}
public function redir($way='',$msg=[]){
if(count($msg) > 0){
foreach($msg as $ks=>$ms) $_SESSION[$ks]=$ms;
}
header('Location: '.$this->path.$way);exit;
}
public function enco($str){
$salt=$_SERVER['HTTP_USER_AGENT'];
$count=strlen($str);
$str=(string)$str;
$kount=strlen($salt);
$x=0;$y=0;
$eStr="";
while($x < $count){
$char=ord($str[$x]);
$keyS=is_numeric($salt[$y]) ? $salt[$y] : ord($salt[$y]);
$encS=$char + $keyS;
$eStr.=chr($encS);
++$x;++$y;
if($y==$kount) $y=0;
}
return base64_encode(base64_encode($eStr));
}
public function deco($str){
$salt=$_SERVER['HTTP_USER_AGENT'];
$str=base64_decode(base64_decode($str));
$count=strlen($str);
$str=(string)$str;
$kount=strlen($salt);
$x=0;$y=0;
$eStr="";
while($x < $count){
$char=ord($str[$x]);
$keyS=is_numeric($salt[$y]) ? $salt[$y] : ord($salt[$y]);
$decS=$char - $keyS;
$eStr.=chr($decS);
++$x;++$y;
if($y==$kount) $y=0;
}
return $eStr;
}
public function priv($pr,$redir=NULL){
$usr=$_SESSION['user'];
$ho=$_SESSION['host'];
$u_pr=$this->con->query("SELECT PRIVILEGE_TYPE FROM information_schema.USER_PRIVILEGES WHERE `GRANTEE`='\'$usr\'@\'$ho\''")->fetch(1);
$p=[];
if(!empty($u_pr[0][0]) && $u_pr[0][0]=="USAGE"){
if(isset($this->sg[1])){
$db=$this->sg[1];
$s_pr=$this->con->query("SELECT PRIVILEGE_TYPE FROM information_schema.SCHEMA_PRIVILEGES WHERE `GRANTEE`='\'$usr\'@\'$ho\'' AND `TABLE_SCHEMA`='$db'")->fetch(1);
foreach($s_pr as $s_p) $p[]=$s_p[0];
}
}else{
$p=[];
foreach($u_pr as $u_p) $p[]=$u_p[0];
}
if((is_array($pr) && count(array_intersect($pr,$p))<1) || !in_array($pr,$p)){
if($redir!==NULL) $this->redir($redir,["err"=>"No Privileges"]);
return false;
}
return true;
}
public function collate($name,$curr=''){
$se=[];
$sel="<select name='$name'><option value=''> </option>";
$q_clls=$this->con->query("SHOW COLLATION");
foreach($q_clls->fetch(1) as $r_clls) $se[$r_clls[1]][]=$r_clls[0];
ksort($se);
foreach($se as $ke=>$va) asort($se[$ke]);
foreach($se as $k=>$ss){
$sel.="<optgroup label='$k'>";
foreach($ss as $s) $sel.="<option value='$s'".($s==$curr?" selected":"").">$s</option>";
$sel.="</optgroup>";
}
return $sel."</select>";
}
public function check($level=[],$param=[]){
if(isset($_SESSION['token']) && !empty($_SESSION['user'])){//check login
$pwd=$this->deco($_SESSION['token']);
$usr=$_SESSION['user'];
$ho=$_SESSION['host'];
$this->con=DBT::factory($ho,$usr,$pwd);
if($this->con===false) $this->redir("50",['err'=>"Can't connect to the server"]);
$h='HTTP_X_REQUESTED_WITH';
if(isset($_SERVER[$h]) && !empty($_SERVER[$h]) && strtolower($_SERVER[$h]) == 'xmlhttprequest') session_regenerate_id(true);
}else{
$this->redir("50");
}
//list DBs
$this->u_db=$this->con->query("select SCHEMA_NAME,DEFAULT_COLLATION_NAME from information_schema.SCHEMATA")->fetch(1);
$rem=call_user_func_array('array_merge',$this->u_db);
if(!$this->priv("SHOW DATABASES")) unset($this->u_db[array_search('information_schema',$rem)]);
//check db
if(isset($this->sg[1])) $db=$this->sg[1];
if(in_array('1',$level)){
$se=$this->con->db($db);
if(!$se) $this->redir();
}
if(in_array('2',$level)){//check table
if(empty($this->sg[2])) $this->redir("5/$db",['err'=>"No table"]);
$q_com=$this->con->query("SHOW TABLE STATUS FROM `$db` like '".$this->sg[2]."'");
if(!$q_com->num_row()) $this->redir("5/$db");
foreach($q_com->fetch(2) as $r_com){
if(stristr($r_com['Comment'],'Unknown storage')==true) $this->redir("5/$db");
if($r_com['Comment']=='VIEW' && $this->sg[0]!=20) $this->redir("5/$db");//prevent to show view as table
}
$q_=$this->con->query("SELECT COUNT(*) FROM `".$this->sg[2]."`");
if(!$q_) $this->redir("5/$db",['err'=>"No records"]);
}
if(in_array('3',$level)){//check field
$tb=$this->sg[2];
$sq="SHOW FIELDS FROM `$db`.`$tb` LIKE '";
$qr=$this->con->query($sq.$this->sg[3]."'");
if(!$qr->num_row()) $this->redir($param['redir']."/$db/".$tb);
if(isset($this->sg[5])){
$qr2=$this->con->query($sq.$this->sg[5]."'");
if(!$qr2->num_row()) $this->redir($param['redir']."/$db/$tb");
}
}
if(in_array('4',$level)){//check paginate
if(!is_numeric($param['pg']) || $param['pg'] > $param['total'] || $param['pg'] < 1) $this->redir($param['redir']);
}
if(in_array('5',$level)){//check spp
$sp=['view','trigger','procedure','function','event'];
$op=$this->sg[0];
$tb=$this->sg[2];
$sg3=$this->sg[3];
if($op!=49 && ($op==40 && $sg3!=$sp[0])||($op==41 && $sg3!=$sp[1])||($op==42 && $sg3!=$sp[2] && $sg3!=$sp[3])||($op==43 && $sg3!=$sp[4])) $this->redir("5/".$db);
if($sg3==$sp[0]){//check view
$q=$this->con->query("SHOW CREATE VIEW `$tb`");
if(!$q) $this->redir("5/$db");
}elseif($sg3==$sp[1]){//check trigger
$this->priv("TRIGGER","5/$db");
$q=$this->con->query("SHOW TRIGGERS FROM `$db` WHERE `Trigger`='$tb'")->fetch();
if($tb !=$q[0]) $this->redir("5/$db");
}elseif($sg3==$sp[4]){//check event
$this->priv("EVENT","5/$db");
$q=$this->con->query("SHOW EVENTS FROM `$db` LIKE '$tb'")->fetch();
if($tb !=$q[1]) $this->redir("5/$db");
}else{//check routine
$this->priv("CREATE ROUTINE","5/$db");
$q=$this->con->query("SHOW $sg3 STATUS WHERE `Db`='$db' AND `Name`='$tb'")->fetch();
if($tb !=$q[1]) $this->redir("5/$db");
}
}
if(in_array('6',$level)){//check user
$this->priv("CREATE USER","52");
if(empty($this->sg[2])){
$u1='';$h1=base64_decode($this->sg[1]);
}else{
$u1=$this->sg[1];$h1=base64_decode($this->sg[2]);
}
$q_exist=$this->con->query("SELECT EXISTS(SELECT 1 FROM information_schema.USER_PRIVILEGES WHERE `GRANTEE`='\'$u1\'@\'$h1\'');")->fetch();
if($q_exist[0]!=1) $this->redir("52");
}
}
public function menu($db='',$tb='',$left='',$sp=[]){
$str='';
if($db==1 || $db!='') $str.="<div class='l2'><ul><li><a href='{$this->path}'>Databases</a></li>";
if($db!='' && $db!=1) $str.="<li><a href='{$this->path}31/$db'>Export</a></li><li><a href='{$this->path}5/$db'>Tables</a></li>";
$dv="<li class='divider'>---</li>";
if($tb!="") $str.=$dv."<li><a href='{$this->path}10/$db/$tb'>Structure</a></li><li><a href='{$this->path}20/$db/$tb'>Browse</a></li><li><a href='{$this->path}21/$db/$tb'>Insert</a></li><li><a href='{$this->path}24/$db/$tb'>Search</a></li><li><a class='del' href='{$this->path}25/$db/$tb'>Empty</a></li><li><a class='del' href='{$this->path}26/$db/$tb'>Drop</a></li>";//table
if(!empty($sp[1]) && $sp[0]=='view') $str.=$dv."<li><a href='{$this->path}40/$db/".$sp[1]."/view'>Structure</a></li><li><a href='{$this->path}20/$db/".$sp[1]."'>Browse</a></li><li><a class='del' href='{$this->path}49/$db/".$sp[1]."/view'>Drop</a></li>";//view
if($db!='') $str.="</ul></div>";
if($db!="" && $db!=1){//db select
$str.="<div class='l3 auto'><select onchange='location=this.value;'><optgroup label='Databases'>";
foreach($this->u_db as $udb) $str.="<option value='{$this->path}{$this->sg[0]}/".$udb[0]."'".($udb[0]==$db?" selected":"").">".$udb[0]."</option>";
$str.="</optgroup></select>";
$q_tbs=[]; $c_sp=empty($sp) ? "":count($sp);
if($tb!="" || $c_sp >1){//table select
$q_tbs=$this->con->query("SELECT TABLE_NAME,TABLE_TYPE FROM information_schema.tables WHERE `TABLE_SCHEMA`='$db' ORDER BY TABLE_TYPE,TABLE_NAME")->fetch(1);
$sl2="<select onchange='location=this.value;'>";
$qtype='';
foreach($q_tbs as $r_tbs){
if($qtype !=$r_tbs[1]){
if($qtype !='') $sl2.='</optgroup>';
$sl2.='<optgroup label="'.$r_tbs[1].'s">';
}
$in=($r_tbs[1]=='VIEW'?[20,40]:[10,20,21,24]);
$sl2.="<option value='{$this->path}".(in_array($this->sg[0],$in)?$this->sg[0]:20)."/$db/".$r_tbs[0]."'".($r_tbs[0]==$tb || ($c_sp >1 && $r_tbs[0]==$sp[1])?" selected":"").">".$r_tbs[0]."</option>";
$qtype=$r_tbs[1];
}
if($qtype!='') $sl2.='</optgroup>';
if($c_sp <1 || $sp[0]=='view') $str.=$sl2."</select>".((!empty($_SESSION['_sqlsearch_'.$db.'_'.$tb]) && $this->sg[0]==20) ? " [<a href='{$this->path}24/$db/$tb/reset'>reset search</a>]":"");
else $str.=" ".$sp[0].": ".$sp[1];
}
$str.="</div>";
}
$str.="<div class='container'>";
if($left==2) $str.="<div class='col3'>";
$f=1;$nrf_op='';
while($f<50){
$nrf_op.="<option value='$f'>$f</option>";
++$f;
}
if($left==1) $str.="<div class='col1'>".
$this->form("30/$db")."<textarea name='qtxt'></textarea><br/><button type='submit'>Run sql</button></form>
<h3>Import</h3><small>sql, csv, json, xml, gz, zip</small>".$this->form("30/$db",1)."<input type='file' name='importfile'/>
<input type='hidden' name='send' value='ja'/><br/><button type='submit'>Upload (<".ini_get("upload_max_filesize")."B)</button></form>
<h3>Create Table</h3>".$this->form("6/$db")."<input type='text' name='ctab'/><br/>
Number of fields<br/><select name='nrf'>$nrf_op</select><br/><button type='submit'>Create</button></form>
<h3>Rename DB</h3>".$this->form("3/$db")."<input type='text' name='rdb'/><br/>Collation<br/>".$this->collate("rdbcll")."<br/><button type='submit'>Rename</button></form>
<h3>Create</h3><a href='{$this->path}40/$db'>View</a><a href='{$this->path}41/$db'>Trigger</a><a href='{$this->path}42/$db'>Routine</a><a href='{$this->path}43/$db'>Event</a></div><div class='col2'>";
return $str;
}
public function pg_number($pg,$totalpg){
if($totalpg > 1){
if($this->sg[0]==20) $link=$this->path."20/".$this->sg[1]."/".$this->sg[2];
elseif($this->sg[0]==5) $link=$this->path."5/".$this->sg[1];
$pgs='';$k=1;
while($k <= $totalpg){
$pgs.="<option ".(($k==$pg) ? "selected>":"value='$link/$k'>")."$k</option>";
++$k;
}
$lft=($pg>1?"<a href='$link/1'>First</a><a href='$link/".($pg-1)."'>Prev</a>":"");
$rgt=($pg < $totalpg?"<a href='$link/".($pg+1)."'>Next</a><a href='$link/$totalpg'>Last</a>":"");
return "<div class='pg'>$lft<select onchange='location=this.value;'>$pgs</select>$rgt</div>";
}
}
public function imp_csv($fname,$body){
$exist=$this->con->query("SELECT 1 FROM `$fname`");
if(!$exist) $this->redir("5/".$this->sg[1],['err'=>"Table not exist"]);
$fname=$this->sanitize($fname);
$e=[];
if(@is_file($body)) $body=file_get_contents($body);
$body=$this->utf($body);
$body=preg_replace('/^\xEF\xBB\xBF|^\xFE\xFF|^\xFF\xFE/','',$body);
//delimiter
$delims=[';'=> 0,','=> 0];
foreach($delims as $dl=> &$cnt) $cnt=count(str_getcsv($body,$dl));
$mark=array_search(max($delims),$delims);
//data
$data=explode("\n",str_replace(["\r\n","\n\r","\r"],"\n",$body));
$row=null;
foreach($data as $item){
$row.=$item;
if(trim($row)===''){
$row=null;
continue;
}elseif(substr_count($row,'"') % 2 !==0){
$row.=PHP_EOL;
continue;
}
$rows[]=str_getcsv($row,$mark,'"','"');
$row=null;
}
foreach($rows as $k=>$rw){
if($k>0){
$e1="INSERT INTO `$fname`(".implode(',',$rows[0]).") VALUES(";
foreach($rw as $r) $e1.=(is_numeric($r)?$r:"'".str_replace("'","''",$r)."'").',';
$e[]=substr($e1,0,-1).");";
}
}
if(empty($e)) $this->redir("5/".$this->sg[1],['err'=>"Query failed"]);
return $e;
}
public function imp_json($fname,$body){
$exist=$this->con->query("SELECT 1 FROM `$fname`");
if(!$exist) $this->redir("5/".$this->sg[1],['err'=>"Table not exist"]);
$e=[];
if(@is_file($body)) $body=file_get_contents($body);
$body=$this->utf($body);
$rgxj="~^\xEF\xBB\xBF|^\xFE\xFF|^\xFF\xFE|(\/\/).*\n*|(\/\*)*.*(\*\/)\n*|((\"*.*\")*('*.*')*)(*SKIP)(*F)~";
$ex=preg_split($rgxj,$body,-1,PREG_SPLIT_NO_EMPTY);
$lines=json_decode($ex[0],true);
$jr='';
foreach($lines[0] as $k=>$li) $jr.=$k.",";
foreach($lines as $line){
$jv='';
foreach($line as $ky=>$el) $jv.=(is_numeric($el)?$el:"'".$el."'").",";
$e[]="INSERT INTO `$fname`(".substr($jr,0,-1).") VALUES (".substr($jv,0,-1).")";
}
return $e;
}
public function imp_xml($body){
$e=[];
if(@is_file($body)) $body=file_get_contents($body);
$body=$this->utf($body);
libxml_use_internal_errors(false);
$xml=simplexml_load_string($body,"SimpleXMLElement",LIBXML_COMPACT);
$nspace=$xml->getNameSpaces(true);
$ns=key($nspace);
//structure
$db=$xml->children($nspace[$ns])->{'structure_schemas'}->{'database'}->attributes();
$cll=(string)$db->collate;
$db=(string)$db->name;
$se=$this->con->db($db);
if(!$se) $sq[]=["CREATE DATABASE `$db`".(empty($cll)?"":" COLLATE `{$cll}`").";"];
$sq[]=["USE `$db`;"];
if(isset($nspace[$ns]) && isset($xml->children($nspace[$ns])->{'structure_schemas'}->{'database'}->{'table'})){
$stru=$xml->children($nspace[$ns])->{'structure_schemas'}->{'database'}->{'table'};
foreach($stru as $st){
$sq[]=explode(";",str_replace("\t\t\t","",(string)$st));
}
}
$sq=(empty($sq) ? $sq : call_user_func_array('array_merge',$sq));
//data
$data=$xml->xpath('//database/table');
foreach($data as $dt){
$tt=$dt->attributes();
$co='';$va='';
foreach($dt as $dt2){
$tv=$dt2->attributes();
$co.=(string)$tv['name'].",";
$va.="'".$dt2."',";
}
if($co!='' && $va!='') $e[]="INSERT INTO `$db`.`".(string)$tt['name']."`(".substr($co,0,-1).") VALUES(".substr($va,0,-1).");";
}
return array_merge($sq,$e);
}
public function tb_structure($db,$tb,$fopt,$tab,$r_st){
$sql='';
if(in_array('drop',$fopt)){//option drop
$sql.="\n{$tab}DROP TABLE IF EXISTS `$tb`;";
}
$ifnot='';
if(in_array('ifnot',$fopt)){//option if not exist
$ifnot.="IF NOT EXISTS ";
}
$q_ex=$this->con->query("SHOW FULL FIELDS FROM `$tb` FROM `$db`");
if($q_ex){
$sq="\n{$tab}CREATE TABLE ".$ifnot."`".$tb."` (";
foreach($q_ex->fetch(2) as $r_ex){
$nul=($r_ex['Null']=='YES' ? "NULL" : "NOT NULL");
$def='';
if($r_ex['Default']!=''){
$def.=" default ".(stristr($r_ex['Default'],'CURRENT_TIMESTAMP') ? $r_ex['Default']:"'".$r_ex['Default']."'");
}
$clls=(($r_ex['Collation']!='' && $r_ex['Collation']!='NULL' && $r_ex['Collation']!=$r_st[14]) ? " COLLATE '".$r_ex['Collation']."'" : "");
$xtr=($r_ex['Extra']!='' ? " ".$r_ex['Extra'] : "");
$sq.="\n{$tab}`".$r_ex['Field']."` ".$r_ex['Type']." ".$nul.$clls.$def.$xtr.",";
}
$idx1=[];$idx2=[];$idx3=[];$idx4=[];
$q_sidx=$this->con->query("SHOW KEYS FROM `$tb` FROM `$db`");
if($q_sidx){
foreach($q_sidx->fetch(2) as $r_sidx){
if($r_sidx['Key_name']=='PRIMARY') $idx1[]=$r_sidx['Column_name'];
elseif($r_sidx['Index_type']=='FULLTEXT') $idx4[$r_sidx['Key_name']][]=$r_sidx['Column_name'];
elseif($r_sidx['Non_unique']==1) $idx2[$r_sidx['Key_name']][]=$r_sidx['Column_name'];
elseif($r_sidx['Non_unique']==0) $idx3[$r_sidx['Key_name']][]=$r_sidx['Column_name'];
}
}
$sq.=(count($idx1) > 0 ? "\n{$tab}PRIMARY KEY(`".implode("`,`",$idx1)."`),":"");
foreach($idx2 as $k2=>$q2){
if(is_array($q2)) $sq.="\n{$tab}KEY `".$k2."` (`".implode("`,`",$q2)."`),";
else $sq.="\n{$tab}KEY `".$k2."` (`".$q2."`),";
}
foreach($idx3 as $k3=>$q3){
if(is_array($q3)) $sq.="\n{$tab}UNIQUE KEY `".$k3."` (`".implode("`,`",$q3)."`),";
else $sq.="\n{$tab}UNIQUE KEY `".$k3."` (`".$q3."`),";
}
foreach($idx4 as $k4=>$q4){
if(is_array($q4)) $sq.="\n{$tab}FULLTEXT INDEX `".$k4."` (`".implode("`,`",$q4)."`),";
else $sq.="\n{$tab}FULLTEXT INDEX `".$k4."` (`".$q4."`),";
}
$q_kcu=$this->con->query("SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ke JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS re on ke.constraint_name=re.constraint_name WHERE ke.`CONSTRAINT_SCHEMA`='$db' AND ke.`TABLE_NAME`='$tb' AND ke.`REFERENCED_COLUMN_NAME` IS NOT NULL");
if($q_kcu->num_row()){
foreach($q_kcu->fetch(2) as $r_kcu){
$sq.="\n{$tab}CONSTRAINT `".$r_kcu['CONSTRAINT_NAME']."` FOREIGN KEY (`".$r_kcu['COLUMN_NAME']."`) REFERENCES `".$r_kcu['REFERENCED_TABLE_NAME']."`(`".$r_kcu['REFERENCED_COLUMN_NAME']."`)".($r_kcu['DELETE_RULE']=='RESTRICT'?'':' ON DELETE '.$r_kcu['DELETE_RULE']).($r_kcu['UPDATE_RULE']=='RESTRICT'?'':' ON UPDATE '.$r_kcu['UPDATE_RULE']).",";
}
}
$q_chk=$this->con->query("SELECT * FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS WHERE `CONSTRAINT_SCHEMA`='$db' AND `TABLE_NAME`='$tb'");
if($q_chk && $q_chk->num_row()){
foreach($q_chk->fetch(2) as $r_chk){
$sq.="\n{$tab}CONSTRAINT {$r_chk['CONSTRAINT_NAME']} CHECK({$r_chk['CHECK_CLAUSE']}),";
}
}
$sql.=substr($sq,0,-1)."\n{$tab})";
$co=($r_st[17]=='' ? "":" COMMENT='".addslashes($r_st[17])."'");
$auto=(in_array('auto',$fopt) && $r_st[10] > 1 ? " AUTO_INCREMENT=".$r_st[10] : "");//option auto
$sql.=($r_st[17]!='VIEW' ? " ENGINE=".$r_st[1].(empty($r_st[14])?"":" DEFAULT CHARSET=".strtok($r_st[14],'_')).$co.$auto:"").";";
}
return $sql;
}
public function getTables($db){
$tbs=[];$vws=[];
if($this->post('tbs')=='' && $this->post('dbs')!=''){
$tabs=$this->con->query("SHOW TABLES FROM `$db`")->fetch(1);
$tabs=empty($tabs) ? []:call_user_func_array('array_merge',$tabs);
}else{
$tabs=$this->post('tbs');
}
foreach($tabs as $tb){
$r_st=$this->con->query("SHOW TABLE STATUS FROM `$db` like '$tb'")->fetch();
if($r_st){
if(preg_match('/view/i',$r_st[17])){
array_push($vws,$tb);
}else{
array_push($tbs,$tb);
}
}
}
return [$tbs,$vws];
}
public function create_ro($db,$pn){
if(is_numeric(substr($pn,0,1))) $this->redir("5/".$db,['err'=>"Not a valid name"]);
$roty=$this->post('roty');
$rtn="CREATE DEFINER=`".$_SESSION['user']."`@`".$_SESSION['host']."` $roty `".$pn."`";
$rt2="(";
$roc=count($this->post('ropty'));
if($roty=='PROCEDURE'){
$rc2=0;
while($rc2 < $roc){
if($this->post('roppa',$rc2)==''){
$rt2.=' ';
}else{
$rt2.=$this->post('ropin',$rc2)." `".$this->post('roppa',$rc2)."` ".$this->post('ropty',$rc2).($this->post('ropva',$rc2)!=''?"(".$this->post('ropva',$rc2).")":"");
if(in_array($this->post('ropty',$rc2),$this->fieldtype['Numbers'])){
$rt2.=($this->post('rop1',$rc2)!=''?" ".$this->post('rop1',$rc2):"");
}
if(in_array($this->post('ropty',$rc2),$this->fieldtype['Strings'])){
$rt2.=($this->post('rop2',$rc2)!=''?" CHARSET ".$this->post('rop2',$rc2):"");
}
$rt2.=",";
}
++$rc2;
}
$rtn.=substr($rt2,0,-1).") ";
}elseif($roty=='FUNCTION'){
$rc3=0;
while($rc3 < $roc){
$rt2.="`".$this->post('roppa',$rc3)."` ".$this->post('ropty',$rc3).($this->post('ropva',$rc3)!=''?"(".$this->post('ropva',$rc3).")":"");
if(in_array($this->post('ropty',$rc3),$this->fieldtype['Numbers'])){
$rt2.=($this->post('rop1',$rc3)!=''?" ".$this->post('rop1',$rc3):"");
}
if(in_array($this->post('ropty',$rc3),$this->fieldtype['Strings'])){
$rt2.=($this->post('rop2',$rc3)!=''?" CHARSET ".$this->post('rop2',$rc3):"");
}
$rt2.=",";
++$rc3;
}
$rtn.=substr($rt2,0,-1).") RETURNS ".$this->post('rorty').($this->post('rorva','!e')?"(".$this->post('rorva').")":"");
if(in_array($this->post('rorty'),$this->fieldtype['Numbers'])){
$rtn.=($this->post('rorop1','!e')?" ".$this->post('rorop1'):"");
}
if(in_array($this->post('rorty'),$this->fieldtype['Strings'])){
$rtn.=($this->post('rorop2','!e')?" CHARSET ".$this->post('rorop2'):"");
}
}
$rtn.=" ".$this->sqlda[$this->post('rosda')].($this->post('rodet','i')?" DETERMINISTIC":"").($this->post('rosec')=='INVOKER'?" SQL SECURITY INVOKER":"").($this->post('rocom','!e')?" COMMENT '".$this->post('rocom')."'":"")."\n".$this->post('rodf');
return $this->con->query($rtn);
}
}
$ed=new ED;
$head='<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8"><title>EdMyAdmin</title>
<style>
*{margin:0;padding:0;font-size:14px;color:#333;font-family:Arial}
html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;background:#fff}
html,textarea{overflow:auto}
.container{overflow:auto;overflow-y:hidden;-ms-overflow-y:hidden;white-space:nowrap;scrollbar-width:thin}
[hidden],.mn ul{display:none}
.m1{position:absolute;right:0;top:0}
.mn li:hover ul{display:block;position:absolute}
.ce{text-align:center}
.link{float:right;padding:3px 0}
.pg *{margin:0 2px;width:auto}
caption{font-weight:bold;border:2px solid #9be}
.l1 ul,.l2 ul{list-style:none}
.left{float:left}
.left button{margin:0 1px}
h3{margin:2px 0 1px;padding:2px 0}
a{color:#842;text-decoration:none}
a:hover{text-decoration:underline}
a,a:active,a:hover{outline:0}
table a,.l1 a,.l2 a,.col1 a{padding:0 2px}
table{border-collapse:collapse;border-spacing:0;border-bottom:1px solid #555}
td,th{padding:4px;vertical-align:top}
input[type=checkbox],input[type=radio]{position:relative;vertical-align:middle;bottom:1px}
input[type=text],input[type=password],input[type=file],textarea,button,select{width:100%;padding:2px;border:1px solid #9be;outline:none;border-radius:3px;box-sizing:border-box}
optgroup option{padding-left:8px}
textarea,select[multiple]{min-height:90px}
textarea{white-space:pre-wrap;min-width:180px}
.msg{position:fixed;top:0;right:0;z-index:9}
.ok,.err{padding:8px;font-weight:bold}
.ok{background:#efe;color:#080;border-bottom:2px solid #080}
.err{background:#fee;color:#f00;border-bottom:2px solid #f00}
.l1,th,button{background:#9be}
.l2,.c1,.col1,h3{background:#cdf}
.c2,.mn ul{background:#fff}
.l3,tr:hover.r,button:hover{background:#fe3 !important}
.ok,.err,.l2 li,.mn>li{display:inline-block;zoom:1}
.col1,.col2{display:table-cell}
.col1{vertical-align:top;padding:3px}
.col1,.dw{width:180px}
.col2 table{margin:3px}
.col3 table,.dw{margin:3px auto}
.auto button,.auto input,.auto select{width:auto}
.l3.auto select{border:0;padding:0;background:#fe3}
.l1,.l2,.l3,.wi{width:100%}
.msg,.a,.bb{cursor:pointer}
.handle,.bb *{font:1.5rem/1rem Arial;font-weight:bold;vertical-align:middle}
.handle:hover{cursor:move}
tr.dragging{opacity:0.5}
tr.drag-over{background:#9be}
.upr{list-style:none;overflow:auto;overflow-x:hidden;height:90px}
</style>
</head><body>'.(empty($_SESSION['ok'])?'':'<div class="msg ok">'.$_SESSION['ok'].'</div>').(empty($_SESSION['err'])?'':'<div class="msg err">'.$_SESSION['err'].'</div>').'<div class="l1"><b><a href="https://github.com/edmondsql/edmyadmin">EdMyAdmin '.$version.'</a></b>'.(isset($ed->sg[0]) && $ed->sg[0]==50 ? "":'<ul class="mn m1"><li>More <small>▼</small><ul><li><a href="'.$ed->path.'60">Info</a></li><li><a href="'.$ed->path.'60/var">Variables</a></li><li><a href="'.$ed->path.'60/status">Status</a></li><li><a href="'.$ed->path.'60/process">Processes</a></li></ul></li><li><a href="'.$ed->path.'52">Users</a></li><li><a href="'.$ed->path.'51">Logout ['.(isset($_SESSION['user']) ? $_SESSION['user']:"").']</a></li></ul>').'</div>';
$stru="<table><caption>Structure</caption><tr><th>Field</th><th>Type</th><th>Value</th><th>Attributes</th><th>Null</th><th>Default</th><th>Collation</th><th>AI <input type='radio' name='ex[]'/></th>".(isset($ed->sg[0]) && $ed->sg[0]==11?"<th>Position</th>":"")."</tr>";
$inttype=[''=>' ','UNSIGNED'=>'unsigned','ZEROFILL'=>'zerofill','UNSIGNED ZEROFILL'=>'unsigned zerofill','on update CURRENT_TIMESTAMP'=>'on update'];
if(!isset($ed->sg[0])) $ed->sg[0]=0;
switch($ed->sg[0]){
default:
case ""://show DBs
$ed->check();
echo $head.$ed->menu()."<div class='col1'>Create Database".$ed->form("2").
"<input type='text' name='dbc'/><p>Collation</p>".$ed->collate("dbcll").
"<br/><button type='submit'>Create</button></form></div><div class='col2'><table><tr><th>Databases</th><th>Collation</th><th>Tables</th><th><a href='{$ed->path}31'>EXP</a>/ Actions</th></tr>";
foreach($ed->u_db as $r_db){
$db0=$r_db[0];
$bg=($bg==1)?2:1;
$q_tbs=$ed->con->query("SHOW TABLES FROM `$db0`");
echo "<tr class='r c$bg'><td>$db0</td><td>".$r_db[1]."</td><td>".$q_tbs->num_row()."</td><td>
<a href='{$ed->path}31/$db0'>Exp</a><a class='del' href='{$ed->path}4/$db0'>Drop</a>
<a href='{$ed->path}5/$db0'>Browse</a></td></tr>";
}
echo "</table>";
break;
case "2"://created DB
$ed->check();
if($ed->post('dbc','!e')){
$db=$ed->sanitize($ed->post('dbc'));
$q_cc=$ed->con->query("CREATE DATABASE `$db`".($ed->post('dbcll','!e')?" COLLATE '".$ed->post('dbcll')."'":""));
if($q_cc) $ed->redir("",['ok'=>"Created DB"]);
$ed->redir("",['err'=>"Create DB failed"]);
}
$ed->redir("",['err'=>"DB name must not be empty"]);
break;
case "3"://rename DB
$ed->check([1]);
$db=$ed->sg[1];
if($ed->post('rdbcll','!e') && $ed->post('rdb','e')){
$ed->con->query("ALTER DATABASE `$db` COLLATE ".$ed->post('rdbcll'));
$ed->redir("",['ok'=>"Changed collation"]);
}
if($ed->post('rdb','!e')){
$ndb=$ed->sanitize($ed->post('rdb'));
$q_db=call_user_func_array('array_merge',$ed->u_db);
if(in_array($ndb,$q_db)){
$ed->con->query("ALTER DATABASE `$db` COLLATE ".$ed->post('rdbcll'));
$ed->redir("",['ok'=>"Changed collation"]);
}
$q_ren=$ed->con->query("CREATE DATABASE `$ndb`".($ed->post('rdbcll','!e')?" COLLATE '".$ed->post('rdbcll')."'":""));//create DB
if(!$q_ren) $ed->redir("",['err'=>"Don't have privilege to create the DB"]);
//table
$q_tb=$ed->con->query("SELECT TABLE_NAME,TABLE_TYPE FROM information_schema.TABLES WHERE `TABLE_SCHEMA`='$db'");
if($q_tb->num_row()){
foreach($q_tb->fetch(1) as $r_tb){
if($r_tb[1] !='VIEW'){
$r_tb0=$r_tb[0];
$ed->con->query("CREATE TABLE `$ndb`.`$r_tb0` LIKE `$db`.`$r_tb0`");
$ed->con->query("INSERT `$ndb`.`$r_tb0` SELECT * FROM `$db`.`$r_tb0`");
}
}
}
//view
if($ed->priv("CREATE VIEW")){
$q_viv=$ed->con->query("SELECT TABLE_NAME,VIEW_DEFINITION FROM information_schema.VIEWS WHERE `TABLE_SCHEMA`='$db'");
if($q_viv->num_row()){
foreach($q_viv->fetch(1) as $r_vi){
$ed->con->query("CREATE VIEW `$ndb`.`".$r_vi[0]."` AS ".str_replace("`".$db."`","`".$ndb."`",$r_vi[1]));
}
}
}
//routine
if($ed->priv("CREATE ROUTINE") && $ed->priv("ALTER ROUTINE")){
$q_aro=$ed->con->query("SELECT ROUTINE_NAME,ROUTINE_TYPE FROM information_schema.ROUTINES WHERE `ROUTINE_SCHEMA`='$db'");
if($q_aro->num_row()){
foreach($q_aro->fetch(1) as $r_aro){
$q_ros=$ed->con->query("SHOW CREATE ".$r_aro[1]." `$db`.`".$r_aro[0]."`")->fetch();
$ed->con->query("USE `$ndb`");
$ed->con->query($q_ros[2]);
}
}
}
//event
if($ed->priv("EVENT")){
$all_ev=$ed->con->query("SHOW EVENTS FROM `$db`");
if($all_ev->num_row()){
foreach($all_ev->fetch(1) as $aev) $ed->con->query("ALTER EVENT `$db`.`".$aev[1]."` RENAME TO `$ndb`.`".$aev[1]."`");
}
}
//trigger
if($ed->priv("TRIGGER")){
$q_tg=$ed->con->query("SHOW TRIGGERS FROM `$db`");
if($q_tg->num_row()){
foreach($q_tg->fetch(1) as $r_tg){
$ed->con->query("USE `$ndb`");
$ed->con->query("CREATE TRIGGER `".$r_tg[0]."` ".$r_tg[4]." ".$r_tg[1]." ON `$ndb`.`".$r_tg[2]."` FOR EACH ROW ".$r_tg[3]);
}
}
}
//drop old DB
$ed->con->query("DROP DATABASE `$db`");
$ed->redir("",['ok'=>"Successfully renamed"]);
}else $ed->redir("5/$db",['err'=>"DB name must not be empty"]);
break;
case "4"://Drop DB
$ed->check([1]);
$ed->priv("DROP","");
$db=$ed->sg[1];
if(!in_array($db,$deny)){
$q_drodb=$ed->con->query("DROP DATABASE `$db`");
if($q_drodb) $ed->redir("",['ok'=>"Succeful deleted DB"]);
}
$ed->redir('',['err'=>"Delete DB failed"]);
break;
case "5"://Show Tables
$ed->check([1]);
$db=$ed->sg[1];
$q_tbs=$ed->con->query("SELECT TABLE_NAME,TABLE_TYPE,ENGINE,TABLE_COLLATION,TABLE_COMMENT FROM information_schema.TABLES WHERE `TABLE_SCHEMA`='$db'");
$ttalr=$q_tbs->num_row();
$tables=[];
//paginate
if($ttalr > 0){
foreach($q_tbs->fetch(1) as $r_tbs) $tables[]=[0=>$r_tbs[0],1=>$r_tbs[1],2=>$r_tbs[2],3=>$r_tbs[3],4=>$r_tbs[4]];
$ttalpg=ceil($ttalr/$step);
if(empty($ed->sg[2])){
$pg=1;
}else{
$pg=$ed->sg[2];
$ed->check([4],['pg'=>$pg,'total'=>$ttalpg,'redir'=>"5/$db"]);
}
}
echo $head.$ed->menu($db,'',1);
if($ttalr > 0){//start rows
echo "<table><tr><th>Table</th><th>Rows</th><th>Engine</th><th>Collate</th><th>Comments</th><th>Actions</th></tr>";
$ofset=($pg - 1) * $step;
$max=$step + $ofset;
while($ofset < $max){
if(!empty($tables[$ofset][0])){
$bg=($bg==1)?2:1;
$tbs=$tables[$ofset][0];
$_vl="/$db/".$tbs;
if($tables[$ofset][1]=='VIEW'){
$lnk="40{$_vl}/view";$dro="49{$_vl}/view";
}else{
$lnk="10".$_vl;$dro="26".$_vl;
}
$q_rows[0]=0;
$q_t=$ed->con->query("SELECT COUNT(*) FROM `$tbs`");
if($q_t) $q_rows=$q_t->fetch();
echo "<tr class='r c$bg'><td>$tbs</td><td>".$q_rows[0]."</td><td>".$tables[$ofset][2]."</td><td>".$tables[$ofset][3]."</td><td>".$tables[$ofset][4]."</td><td><a href='".$ed->path.$lnk."'>Structure</a><a class='del' href='".$ed->path.$dro."'>Drop</a><a href='".$ed->path."20/$db/$tbs'>Browse</a></td></tr>";
}
++$ofset;
}
echo "</table>".$ed->pg_number($pg,$ttalpg);
}//end rows
//triggers
$q_trg=$ed->con->query("SHOW TRIGGERS FROM `$db`");
if($q_trg->num_row()){
echo "<table><tr><th>Trigger</th><th>Table</th><th>Timing</th><th>Event</th><th>Actions</th></tr>";
foreach($q_trg->fetch(1) as $r_tg){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>".$r_tg[0]."</td><td>".$r_tg[2]."</td><td>".$r_tg[4]."</td><td>".$r_tg[1]."</td><td><a href='{$ed->path}41/$db/".$r_tg[0]."/trigger'>Edit</a><a class='del' href='{$ed->path}49/$db/".$r_tg[0]."/trigger'>Drop</a></td></tr>";
}
echo "</table>";
}
//spp
$tsp='';
$spps=['procedure','function'];
$q_sp=[];
foreach($spps as $spp){
$q_spp=$ed->con->query("SHOW {$spp} STATUS");
if($q_spp){
foreach($q_spp->fetch(1) as $r_spp){
if($r_spp[0]==$db){
$tsp=1;
$q_sp[]=$r_spp;
}
}
}
}
if($tsp==1){
echo "<table><tr><th>Routine</th><th>Type</th><th>Comments</th><th>Actions</th></tr>";
foreach($q_sp as $r_sp){
$bg=($bg==1)?2:1;
if($r_sp[0]==$db){
echo "<tr class='r c$bg'><td>".$r_sp[1]."</td><td>".$r_sp[2]."</td><td>".(strlen($r_sp[7]) > 70 ? substr($r_sp[7],0,70)."[...]":$r_sp[7])
."</td><td><a href='{$ed->path}42/".$r_sp[0]."/".$r_sp[1]."/".strtolower($r_sp[2])."'>Edit</a><a href='{$ed->path}48/".$r_sp[0]."/".$r_sp[1]."/".strtolower($r_sp[2])."'>Execute</a><a class='del' href='{$ed->path}49/".$r_sp[0]."/".$r_sp[1]."/".strtolower($r_sp[2])."'>Drop</a></td></tr>";
}
}
echo "</table>";
}
//events
if(!in_array($db,$deny)){
$q_eve=$ed->con->query("SHOW EVENTS FROM `$db`");
if($q_eve)
if($q_eve->num_row()){
echo "<table><tr><th>Event</th><th>Schedule</th><th>Start</th><th>End</th><th>Actions</th></tr>";
foreach($q_eve->fetch(2) as $r_eve){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>".$r_eve['Name']."</td><td>".
($r_eve['Type']=='RECURRING' ? "Every ".$r_eve['Interval value'].$r_eve['Interval field']."</td><td>".$r_eve['Starts']."</td><td>".$r_eve['Ends']:"AT </td><td>".$r_eve['Execute at']."</td><td>")."</td><td><a href='{$ed->path}43/$db/".$r_eve['Name']."/event'>Edit</a><a class='del' href='{$ed->path}49/$db/".$r_eve['Name']."/event'>Drop</a></td></tr>";
}
echo "</table>";
}
}
break;
case "6"://create table
$ed->check([1]);
$db=$ed->sg[1];
if($ed->post('ctab','!e') && !is_numeric(substr($ed->post('ctab'),0,1)) && $ed->post('nrf','!e') && is_numeric($ed->post('nrf')) && $ed->post('nrf')>0 ){
echo $head.$ed->menu($db,'',2);
if($ed->post('crtb','i')){
$qry1="CREATE TABLE ".$ed->sanitize($ed->post('ctab'))."(";
$nf=0;
while($nf<$ed->post('nrf')){
$c1=$ed->post('fi'.$nf); $c2=$ed->post('ty'.$nf);
$c3=($ed->post('va'.$nf,'!e') ? "(".$ed->post('va'.$nf).")":"");
$c4=($ed->post('at'.$nf,'!e') ? " ".$ed->post('at'.$nf):"");
$c5=$ed->post('nc'.$nf);
$c7=($ed->post('ex','!e') && $ed->post('ex',0)!='on' && $ed->post('ex',0)==$nf ? " AUTO_INCREMENT PRIMARY KEY":"");
$c6=($ed->post('de'.$nf,'!e') ? " default '".$ed->post('de'.$nf)."'":"");
$c8=($ed->post('clls'.$nf,'!e') ? " collate ".$ed->post('clls'.$nf):"");
if(stripos($c4,'on update') || $ed->post('de'.$nf)=='CURRENT_TIMESTAMP'){
$c8.=$c4;$c4='';
$c6=($ed->post('de'.$nf,'!e') ? " default ".$ed->post('de'.$nf):"");
}
$qry1.=$c1." ".$c2.$c3.$c4." ".$c5.$c6.$c7.$c8.",";
++$nf;
}
$qry2=substr($qry1,0,-1);
$qry=$qry2.")".($ed->post('engs')==""?"":" ENGINE=".$ed->post('engs')).($ed->post('tcomm')!=""?" COMMENT='".$ed->post('tcomm')."'":"").";";
echo "<p>".($ed->con->query($qry) ? "<b>OK!</b> $qry" : "<b>FAILED!</b> $qry")."</p>";
}else{
echo $ed->form("6/$db")."
<input type='hidden' name='ctab' value='".$ed->sanitize($ed->post('ctab'))."'/>
<input type='hidden' name='nrf' value='".$ed->post('nrf')."'/>".$stru;
$nf=0;
while($nf<$ed->post('nrf')){
$bg=($bg==1)?2:1;
echo "<tr class='c$bg'><td><input type='text' name='fi".$nf."'/></td>
<td><select name='ty".$nf."'>".$ed->fieldtypes()."</select></td>
<td><input type='text' name='va".$nf."'/></td><td><select name='at".$nf."'>";
foreach($inttype as $intk=>$intt) echo "<option value='$intk'>$intt</option>";
echo "</select></td>
<td><select name='nc".$nf."'><option value='NOT NULL'>NOT NULL</option><option value='NULL'>NULL</option></select></td>
<td><input type='text' name='de".$nf."'/></td><td>".
$ed->collate("clls".$nf)."</td><td><input type='radio' name='ex[]' value='$nf'/></td></tr>";
++$nf;
}
echo "<tr><td colspan='1'>Engine<br/><select name='engs'><option value=''> </option>";
$q_eng=$ed->con->query("SELECT ENGINE FROM information_schema.ENGINES WHERE ENGINE IS NOT NULL AND SUPPORT<>'NO'")->fetch(1);
foreach($q_eng as $r_eng){
echo "<option value='".$r_eng[0]."'>".$r_eng[0]."</option>";
}
echo "</select></td><td colspan='7'>Table Comment:<br/><input type='text' name='tcomm'/></td></tr>
<tr><td colspan='8'><button type='submit' name='crtb'>Create Table</button></td></tr></table></form>";
}
}else{
$ed->redir("5/$db",['err'=>"Create table failed"]);
}
break;
case "9":
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
if($ed->post('cll','i')){//change table collation
$q_altcll=$ed->con->query("ALTER TABLE `$db`.`$tb` CONVERT TO CHARACTER SET ".strtok($ed->post('cll'),'_')." COLLATE ".$ed->post('cll'));
if($q_altcll) $ed->redir("10/$db/".$tb,['ok'=>"Successfully changed"]);
$ed->redir("10/$db/$tb",['err'=>"Change failed"]);
}
if($ed->post('engs','i')){//change table engine
$q_engs=$ed->con->query("ALTER TABLE `$db`.`$tb` ENGINE=".$ed->post('engs'));
if($q_engs) $ed->redir("5/$db/$tb",['ok'=>"Successfully changed"]);
$ed->redir("10/$db/$tb",['err'=>"Change failed"]);
}
if($ed->post('copytab','!e')){//copy table in new DB
$ndb=$ed->post('copytab');
$q_altchk=$ed->con->query("SELECT 1 FROM `$ndb`.`$tb`");
if($q_altchk) $ed->redir("10/$db/".$tb,['err'=>"Table already exists"]);
$q_altcrt=$ed->con->query("CREATE TABLE `$ndb`.`$tb` LIKE `$db`.`$tb`");
$q_altins=$ed->con->query("INSERT `$ndb`.`$tb` SELECT * FROM `$db`.`$tb`");
if($q_altcrt && $q_altins) $ed->redir("10/$db/$tb",['ok'=>"Successfully copied"]);
$ed->redir("10/$db/$tb",['err'=>"Copy table failed"]);
}
if($ed->post('changeb','i') && $ed->post('changec','i')){//table comment
$ed->con->query("ALTER TABLE `$tb` COMMENT=\"".addslashes($ed->post('changec'))."\"");
$ed->redir("10/$db/$tb",['ok'=>"Changed table comment"]);
}
if($ed->post('rtab','!e')){//rename table
$ntb=$ed->sanitize($ed->post('rtab'));
if(is_numeric(substr($ntb,0,1))) $ed->redir("5/$db",['err'=>"Not a valid table name"]);
$q_creatt=$ed->con->query("SELECT count(*) FROM `$ntb`");
if(!$q_creatt){//prevent create duplicate
//create table
$q_ttab=$ed->con->query("SELECT TABLE_NAME,TABLE_TYPE FROM information_schema.TABLES WHERE `TABLE_SCHEMA`='$db' AND `TABLE_NAME`='$tb'");
$r_ttr=$q_ttab->fetch();
$ed->con->query("CREATE TABLE `$ntb` LIKE `".$r_ttr[0]."`");
$ed->con->query("INSERT INTO `$ntb` SELECT * FROM `".$r_ttr[0]."`");
//rename table in view
if($ed->priv("SHOW VIEW") && $ed->priv("CREATE VIEW")){
$q_vtb=$ed->con->query("SELECT TABLE_NAME,VIEW_DEFINITION FROM information_schema.VIEWS WHERE `TABLE_SCHEMA`='$db'");
if($q_vtb->num_row()){
foreach($q_vtb->fetch(1) as $r_tv){
$ed->con->query("DROP VIEW IF EXISTS `$db`.`".$r_tv[0]."`");
$ed->con->query("CREATE VIEW `$db`.`".$r_tv[0]."` AS ".str_replace("`".$tb."`","`".$ntb."`",$r_tv[1]));
}
}
}
//rename table in procedure
if($ed->priv("CREATE ROUTINE") && $ed->priv("ALTER ROUTINE")){
$q_prs=$ed->con->query("SELECT ROUTINE_NAME,ROUTINE_TYPE FROM information_schema.ROUTINES WHERE `ROUTINE_SCHEMA`='$db'");
if($q_prs){
foreach($q_prs->fetch(1) as $r_prs){
$q_ros=$ed->con->query("SHOW CREATE ".$r_prs[1]." `$db`.`".$r_prs[0]."`")->fetch();
$retb=preg_replace("/\`".$tb."\`|\b".$tb."\b/i","`".$ntb."`",$q_ros[2]);
$ed->con->query("DROP ".$r_prs[1]." `".$r_prs[0]."`");
$ed->con->query($retb);
}
}
}
//rename table in event
if($ed->priv("EVENT")){
$q_evn=$ed->con->query("SELECT EVENT_NAME,EVENT_DEFINITION FROM information_schema.EVENTS WHERE `EVENT_SCHEMA`='$db'");
if($q_evn)
if($q_evn->num_row()){
foreach($q_evn->fetch(1) as $r_evn){
$evb=preg_replace("/\`".$tb."\`|\b".$tb."\b/i","`".$ntb."`",$r_evn[1]);
$ed->con->query("ALTER EVENT `".$r_evn[0]."` DO ".$evb);
}
}
}
//rename table in triggers
if($ed->priv("TRIGGER")){
$q_trg=$ed->con->query("SHOW TRIGGERS FROM `$db`");
if($q_trg->num_row()){
foreach($q_trg->fetch(1) as $r_trg){
$ed->con->query("DROP TRIGGER IF EXISTS `$db`.`".$r_trg[0]."`");
$ed->con->query("CREATE TRIGGER `".$r_trg[0]."` ".$r_trg[4]." ".$r_trg[1]." ON `$ntb` FOR EACH ROW ".$r_trg[3]);
}