-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg.php
More file actions
2098 lines (2052 loc) · 89.6 KB
/
pg.php
File metadata and controls
2098 lines (2052 loc) · 89.6 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('pdo_pgsql')) die('Install pdo_pgsql extension!');
session_name('PG');
session_start();
$bg=2;
$step=20;
$version="1.2";
$bbs=['False','True'];
$deny=['information_schema','pg_catalog','temp_tables','pg_toast'];
class DBT {
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){
$host=explode(":",$host);
$dsn="pgsql:host={$host[0]};port=".(empty($host[1])?5432:$host[1]).($db==""?"":";dbname={$db}");
$this->_cnx=new PDO($dsn,$user,$pwd);
$this->_cnx->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$this->_cnx->query("SET NAMES 'UTF8'");
}
public function query($sql){
try {
$this->_query=$this->_cnx->query($sql);
return $this;
} catch(Exception $e){
return false;
}
}
public function begin(){
return $this->_cnx->beginTransaction();
}
public function commit(){
return $this->_cnx->commit();
}
public function fetch($mode=0){
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(){
return $this->_query->rowCount();
}
public function num_col(){
return $this->_query->columnCount();
}
}
class ED {
public $con,$path,$sg,$u_db,$fieldtype;
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=["serial","bigserial","\"any\"","\"char\"","abstime","aclitem","anyarray","anyelement","anyenum","anynonarray","anyrange","bigint","bit","bit varying","boolean","box","bytea","character","character varying","cid","cidr","circle","cstring","date","daterange","double precision","event_trigger","fdw_handler","gtsvector","index_am_handler","inet","information_schema.cardinal_number","information_schema.character_data","information_schema.sql_identifier","information_schema.time_stamp","information_schema.yes_or_no","int2vector","int4range","int8range","integer","internal","interval","json","jsonb","language_handler","line","lseg","macaddr","money","name","numeric","numrange","oid","oidvector","opaque","path","pg_ddl_command","pg_lsn","pg_node_tree","point","polygon","real","record","refcursor","regclass","regconfig","regdictionary","regnamespace","regoper","regoperator","regproc","regprocedure","regrole","regtype","reltime","smallint","smgr","text","tid","time with time zone","time without time zone","timestamp with time zone","timestamp without time zone","tinterval","trigger","tsm_handler","tsquery","tsrange","tstzrange","tsvector","txid_snapshot","unknown","uuid","void","xid","xml"];
}
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($slt=''){
$ft='';
foreach($this->fieldtype as $fty){
$ft.="<option value='$fty'".(($slt!='' && $fty==$slt)?" selected":"").">$fty</option>";
}
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 check($level=[],$param=[]){
if(isset($_SESSION['token']) && !empty($_SESSION['user'])){//check login
$usr=$_SESSION['user'];
$pwd=$this->deco($_SESSION['token']);
$ho=$_SESSION['host'];
$this->con=DBT::factory($ho,$usr,$pwd,isset($param['db'])?$param['db']:($this->sg[1]??''));
if(!$this->con) $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
$u_db=$this->con->query("SELECT datname FROM pg_database WHERE has_database_privilege('$usr',datname,'CONNECT') AND datistemplate=FALSE")->fetch(1);
$this->u_db=call_user_func_array('array_merge',$u_db);
//check db
if(isset($this->sg[1])) $db=$this->sg[1];
if(in_array('1',$level)){
if(!in_array($db,$this->u_db)) $this->redir();
}
if(in_array('2',$level)){//check table
$tb=$this->sg[2];
$q_com=$this->con->query("SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_catalog='$db' AND table_name='$tb'");
if(!$q_com->num_row()) $this->redir("5/$db");
$q_=$this->con->query("SELECT COUNT(*) FROM $tb");
if(!$q_) $this->redir("5/$db",['err'=>"No records"]);
}
if(in_array('3',$level)){//check field
$field=$this->sg[3];
$sql1="SELECT 1 FROM pg_attribute WHERE attrelid='{$tb}'::regclass AND attname='{$field}' AND NOT attisdropped";
$qr=$this->con->query($sql1);
if(!$qr || $qr->num_row()==0) $this->redir($param['redir']."/$db/$tb");
if(isset($this->sg[5])){
$field2=$this->sg[5];
$sql2="SELECT 1 FROM pg_attribute WHERE attrelid='{$tb}'::regclass AND attname='{$field2}' AND NOT attisdropped";
$qr2=$this->con->query($sql2);
if(!$qr2 || $qr2->num_row()==0) $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
$tb=$this->sg[2];
$sp=$this->sg[3];
switch($sp){
case 'view':
$q=$this->con->query("SELECT viewname FROM pg_views WHERE schemaname='public' AND viewname='$tb'");
if(!$q || $q->num_row()==0) $this->redir("5/$db");
break;
case 'trigger':
$q=$this->con->query("SELECT 1 FROM pg_trigger WHERE tgname='$tb'");
if(!$q || $q->num_row()==0) $this->redir("5/$db");
break;
case 'procedure': case 'function':
$q=$this->con->query("SELECT 1 FROM information_schema.routines WHERE routine_schema='public' AND routine_type='".strtoupper($sp)."' AND routine_name='$tb'");
if(!$q || $q->num_row()==0) $this->redir("5/$db");
break;
default: $this->redir("5/$db");
}
}
if(in_array('6',$level)){//check user
$u1=base64_decode($this->sg[1]);
$q_e=$this->con->query("SELECT 1 FROM pg_roles WHERE rolname='{$u1}'");
if(!$q_e || $q_e->num_row()==0) $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'".($udb==$db?" selected":"").">$udb</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='public' AND table_catalog='$db' ORDER BY table_type")->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>]":"");
}
$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/><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></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){
if($r=='NULL') $e1.='NULL,';
else $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){
if($el=='NULL') $jv.='NULL,';
else $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
$sq[]=[];
if(isset($nspace[$ns]) && isset($xml->children($nspace[$ns])->{'structure_schemas'}->{'database'}->{'table'})){
$strs=$xml->children($nspace[$ns])->{'structure_schemas'}->{'database'}->{'table'};
foreach($strs 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=='NULL')?"NULL,":"'".$dt2."',";
}
if($co!='' && $va!='') $e[]="INSERT INTO ".(string)$tt['name']."(".substr($co,0,-1).") VALUES(".substr($va,0,-1).");";
}
return array_merge($sq,$e);
}
public function tb_structure($tb,$fopt,$tab){
$sql="";
if(in_array('drop',$fopt)){//option drop
$sql.="\n{$tab}DROP TABLE IF EXISTS $tb;\n";
}
$ifnot='';
if(in_array('ifnot',$fopt)){//option if not exist
$ifnot.="IF NOT EXISTS ";
}
$q_ex=$this->con->query("SELECT a.attname AS column_name,pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type,a.attnotnull AS is_nullable,pg_get_expr(ad.adbin,ad.adrelid) AS column_default FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON a.attrelid=c.oid JOIN pg_catalog.pg_namespace n ON c.relnamespace=n.oid LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid=c.oid AND ad.adnum=a.attnum WHERE n.nspname='public' AND c.relname='$tb' AND a.attnum>0 AND NOT a.attisdropped");
if($q_ex){
$sq="\n{$tab}CREATE TABLE ".$ifnot."".$tb." (";
foreach($q_ex->fetch(2) as $r_ex){
$dty=$r_ex['data_type'];$def=$r_ex['column_default'];
if(!empty($def) && strpos($def,'nextval')!==false){
$def='';
if($dty=='integer') $dty='serial';
elseif($dty=='bigint') $dty='bigserial';
elseif($dty=='smallint') $dty='smallserial';
}
$nul=($r_ex['is_nullable']==1 ? "NOT NULL":"NULL");
if($def!='') $def=" default ".$def;
$sq.="\n{$tab}".$r_ex['column_name']." $dty ".$nul.$def.",";
}
$sql.=substr($sq,0,-1)."\n{$tab});\n\n";
$indexes=[];
$q_constraints=$this->con->query("SELECT conname,contype,conkey,pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conrelid='$tb'::regclass AND contype IN('p','u','c','f')");
if($q_constraints && $q_constraints->num_row()>0){
foreach($q_constraints->fetch(2) as $r_con){
$key_name=$r_con['conname'];
$def=$r_con['def'];
switch($r_con['contype']){
case 'p':$sql.=$tab."ALTER TABLE $tb ADD $def;\n";break;
case 'u':case 'c':case 'f':$sql.=$tab."ALTER TABLE $tb ADD CONSTRAINT $key_name $def;\n";break;
}
$indexes[$key_name]=[];
}
}
$q_idx=$this->con->query("SELECT indexname,indexdef FROM pg_indexes WHERE schemaname='public' AND tablename='$tb'");
if($q_idx && $q_idx->num_row()>0){
foreach($q_idx->fetch(1) as $r_idx){
$index=$r_idx[0];
if(!isset($indexes[$index])){
$sql.=$tab.$r_idx[1].";\n";
}
}
}
$q_comm=$this->con->query("SELECT obj_description('{$tb}'::regclass,'pg_class')")->fetch();
if($q_comm && $q_comm[0]) $sql.=$tab."COMMENT ON TABLE $tb IS '".addslashes($q_comm[0])."';\n";
}
return $sql;
}
public function getTables($db){
$tbs=[];$vws=[];
$q_tb=$this->con->query("SELECT * FROM information_schema.tables WHERE table_schema='public' AND table_catalog='$db'")->fetch(2);
foreach($q_tb as $tb){
$tbn=$tb['table_name'];
if(in_array($tbn,$this->post('tbs'))){
if($tb['table_type']=='VIEW'){
array_push($vws,$tbn);
}else{
array_push($tbs,$tbn);
}
}
}
return [$tbs,$vws];
}
}
$ed=new ED;
$head='<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8"><title>EdPgAdmin</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{cursor:pointer}
</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/edpgadmin">EdPgAdmin '.$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 colspan='2'>Type</th><th>Value</th><th>Null</th><th>Default</th></tr>";
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'/><br/><button type='submit'>Create</button></form></div><div class='col2'><table><tr><th>Databases</th><th>Actions</th></tr>";
foreach($ed->u_db as $udb){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>$udb</td><td>
<a href='{$ed->path}31/$udb'>Exp</a><a class='del' href='{$ed->path}4/$udb'>Drop</a>
<a href='{$ed->path}5/$udb'>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");
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([],['db'=>'']);
$db=$ed->sg[1];
if($ed->post('rdb','!e')){
$ndb=$ed->sanitize($ed->post('rdb'));
$dbs=$ed->con->query("SELECT datname FROM pg_database")->fetch(1);
$dbs=call_user_func_array('array_merge',$dbs);
if(!in_array($ndb,$dbs) && in_array($db,$dbs)){
$ed->con->query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='$db'");
$ed->con->query("ALTER DATABASE $db RENAME TO $ndb");
$ed->redir("",['ok'=>"Renamed database"]);
}else $ed->redir("5/$db",['err'=>"Not valid DB name"]);
}else $ed->redir("5/$db",['err'=>"Name must not be empty"]);
break;
case "4"://Drop DB
$ed->check([],['db'=>'']);
$db=$ed->sg[1];
if(!in_array($db,$deny) && in_array($db,$ed->u_db)){
$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 * FROM information_schema.tables WHERE table_schema='public' AND table_catalog='$db'");
$ttalr=$q_tbs->num_row();
$tables=[];
if($ttalr >0){
foreach($q_tbs->fetch(2) as $r_tbs) $tables[]=[0=>$r_tbs['table_name'],1=>$r_tbs['table_schema'],2=>$r_tbs['table_type']];
}
//paginate
if($ttalr > 0){
$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>Schema</th><th>Type</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][2]=='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][1]."</td><td>".$tables[$ofset][2]."</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("SELECT tgname,relname FROM pg_trigger t JOIN pg_class c ON t.tgrelid=c.oid WHERE NOT tgisinternal ORDER BY tgname");
if($q_trg && $q_trg->num_row()>0){
echo "<table><tr><th>Trigger</th><th>Table</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[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
$spps=['PROCEDURE','FUNCTION'];
$q_sp=[];
foreach($spps as $spp){
$q_spp=$ed->con->query("SELECT routine_name,routine_type FROM information_schema.routines WHERE routine_schema='public' AND routine_type='$spp' ORDER BY routine_name");
if($q_spp){
foreach($q_spp->fetch(1) as $r_spp){
$q_sp[]=[$db,$r_spp[0],$r_spp[1]];
}
}
}
if(!empty($q_sp)){
echo "<table><tr><th>Routine</th><th>Type</th><th>Actions</th></tr>";
foreach($q_sp as $r_sp){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>".$r_sp[1]."</td><td>".$r_sp[2]."</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>";
}
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') && $ed->post('nrf')>0 ){
echo $head.$ed->menu($db,'',2);
if($ed->post('crtb','i')){
$tb=$ed->sanitize($ed->post('ctab'));
$qry1="CREATE TABLE $tb (";
$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).")":"").$ed->post('ar'.$nf);
$c4=$ed->post('nc'.$nf);
$c5=($ed->post('de'.$nf,'!e') ? " default '".$ed->post('de'.$nf)."'":"");
$qry1.=$c1." ".$c2.$c3." ".$c4.$c5.",";
++$nf;
}
$qry2=substr($qry1,0,-1);
$qry=$qry2.");";
echo "<p>".($ed->con->query($qry) ? "<b>OK!</b> $qry":"<b>FAILED!</b> $qry")."</p>";
if($ed->post('tc')!=""){
$ed->con->query("COMMENT ON TABLE $tb IS '".$ed->post('tc')."'");
echo "<p>Comment created!</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><select name='ar".$nf."'><option value=''></option><option value='[]'>[ ]</option></select></td>
<td><input type='text' name='va".$nf."'/></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></tr>";
++$nf;
}
echo "<tr><td colspan='7'>Table Comment:<br/><input type='text' name='tc'/></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('changeb','i') && $ed->post('changec','i')){//table comment
$ed->con->query("COMMENT ON TABLE $tb IS '".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 1 FROM pg_tables WHERE schemaname='public' AND tablename='$ntb'");
if($q_creatt && $q_creatt->num_row()>0) $ed->redir("5/$db",['err'=>"Table already exist"]);
$q_ren=$ed->con->query("ALTER TABLE $tb RENAME TO $ntb");
if($q_ren) $ed->redir("5/$db",['ok'=>"Successfully renamed"]);
else $ed->redir("5/$db",['err'=>"Rename table failed"]);
}
if($ed->post('idx','!e') && is_array($ed->post('idx'))){//create index
$idx=''.implode(',',$ed->post('idx')).'';
$idxn=implode('_',$ed->post('idx'));
if($ed->post('primary','i')){
$ed->con->query("ALTER TABLE $tb ADD PRIMARY KEY ($idx)");
}elseif($ed->post('unique','i')){
$ed->con->query("ALTER TABLE $tb ADD CONSTRAINT unq_$idxn UNIQUE ($idx)");
}elseif($ed->post('index','i')){
$ed->con->query("CREATE INDEX idx_$idxn ON $tb ($idx)");
}
$ed->redir("10/$db/$tb",['ok'=>"Successfully created"]);
}
if(isset($ed->sg[3])){//drop index
$idx=$ed->sg[3];
$q_alt=$ed->con->query("ALTER TABLE $tb DROP CONSTRAINT $idx");
if($q_alt==false) $q_alt=$ed->con->query("DROP INDEX $idx");
if($q_alt) $ed->redir("10/$db/$tb",['ok'=>"Successfully dropped"]);
else $ed->redir("10/$db/$tb",['err'=>"Drop failed"]);
}
$ed->redir("5/$db",['err'=>"Action failed"]);
break;
case "10"://structure
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
echo $head.$ed->menu($db,$tb,1);
echo $ed->form("9/$db/$tb")."<table><caption>Structure</caption><thead><tr><th><input type='checkbox' onclick='toggle(this,\"idx[]\")'/></th><th>Field</th><th>Type</th><th>Null</th><th>Default</th><th>Actions</th></tr></thead><tbody class='sort'>";
$q_fi=$ed->con->query("SELECT a.attname AS column_name,pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type,a.attnotnull AS is_nullable,pg_get_expr(ad.adbin,ad.adrelid) AS column_default FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON a.attrelid=c.oid JOIN pg_catalog.pg_namespace n ON c.relnamespace=n.oid LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid=c.oid AND ad.adnum=a.attnum WHERE n.nspname='public' AND c.relname='$tb' AND a.attnum>0 AND NOT a.attisdropped");
foreach($q_fi->fetch(2) as $r_fi){
$bg=($bg==1)?2:1;
$dty=$r_fi['data_type'];$def=$r_fi['column_default'];
if(!empty($def) && strpos($def,'nextval')!==false){
if($dty=='integer') $dty='serial';
elseif($dty=='bigint') $dty='bigserial';
elseif($dty=='smallint') $dty='smallserial';
}
echo "<tr class='r c$bg' id='{$r_fi['column_name']}'><td><input type='checkbox' name='idx[]' value='{$r_fi['column_name']}'/></td><td>{$r_fi['column_name']}</td><td>$dty</td><td>".($r_fi['is_nullable']==1?"NO":"YES")."</td><td>$def</td><td><a href='{$ed->path}12/$db/$tb/{$r_fi['column_name']}'>change</a><a class='del' href='{$ed->path}13/$db/$tb/{$r_fi['column_name']}'>drop</a><a href='{$ed->path}11/$db/$tb/{$r_fi['column_name']}'>add</a></td></tr>";
}
$q_comm=$ed->con->query("SELECT obj_description('{$tb}'::regclass,'pg_class')")->fetch();
$tb_comment=$q_comm ? $q_comm[0]:'';
echo "</tbody><tfoot><tr><td colspan='3'><button type='submit' name='changeb'>Change Comment</button></td><td colspan='5'><input type='text' name='changec' value=\"".$tb_comment."\"/></td></tr>
<tr><td class='auto' colspan='8'><div class='left'><button type='submit' name='primary'>Primary</button><button type='submit' name='index'>Index</button><button type='submit' name='unique'>Unique</button></div><div class='link'><a href='{$ed->path}27/$db/$tb/vacuum'>Vacuum</a><a href='{$ed->path}27/$db/$tb/analyze'>Analyze</a><a href='{$ed->path}27/$db/$tb/reindex'>Reindex</a></div></td></tr></tfoot></table></form>
<table><caption>Index</caption><tr><th>Key name</th><th>Field</th><th>Type</th><th>Actions</th></tr>";
$indexes=[];
$q_constraints=$ed->con->query("SELECT conname,contype,conkey FROM pg_constraint WHERE conrelid='$tb'::regclass AND contype IN('p','u','f','c','t')");
if($q_constraints && $q_constraints->num_row()>0){
foreach($q_constraints->fetch(2) as $r_con){
$col_numbers=explode(',',trim($r_con['conkey'],'{}'));
$col_names=[];
foreach($col_numbers as $col_num){
$col_name_query=$ed->con->query("SELECT attname FROM pg_attribute WHERE attrelid='$tb'::regclass AND attnum={$col_num}");
if($col_name_query && $col_name_query->num_row()>0) $col_names[]=$col_name_query->fetch()[0];
}
$key_name=$r_con['conname'];
switch($r_con['contype']){
case 'p':$type='PRIMARY';break;
case 'u':$type='UNIQUE';break;
case 'f':$type='FK';break;
case 'c':$type='CHECK';break;
}
$indexes[$key_name]=['type'=>$type,'column'=>$col_names];
}
}
$q_idx=$ed->con->query("SELECT indexname,indexdef FROM pg_indexes WHERE schemaname='public' AND tablename='$tb'");
if($q_idx && $q_idx->num_row()>0){
foreach($q_idx->fetch(2) as $r_idx){
$index=$r_idx['indexname'];
if(!isset($indexes[$index])){
preg_match('/USING\s*\w+\s*\(([^)]+)\)/',$r_idx['indexdef'],$match);
$cols=isset($match[1]) ? array_map('trim',explode(',',str_replace('"','',$match[1]))):[];
$indexes[$index]=['type'=>'INDEX','column'=>$cols];
}
}
}
if(count($indexes)>0){
foreach($indexes as $iNam=>$iCol){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>$iNam</td><td>";
foreach($iCol['column'] as $col) echo $col."<br/>";
echo "</td><td>".$iCol['type'];
echo "</td><td><a class='del' href='{$ed->path}9/$db/$tb/$iNam'>drop</a></td></tr>";
}
}
echo "</table><table class='c1'><tr><td>Rename Table<br/>".$ed->form("9/$db/$tb")."<input type='text' name='rtab'/><br/><button type='submit'>Rename</button></form></td></tr></table>";
break;
case "11"://Add field
$ed->check([1,2,3],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$id=$ed->sg[3];
if($ed->post('fi','!e') && $ed->post('ty','!e') && !is_numeric(substr($ed->post('fi'),0,1))){
$ty=$ed->post('ty').($ed->post('va','e') ? "":"(".$ed->post('va').")").($ed->post('ar','e') ? "":"[]");
$nc=$ed->post('nc');
$de=($ed->post('de','e') ? "":" DEFAULT ".$ed->post('de'));
$e=$ed->con->query("ALTER TABLE $tb ADD COLUMN ".$ed->sanitize($ed->post('fi'))." $ty ".$nc.$de);
if($e) $ed->redir("10/$db/$tb",['ok'=>"Successfully added"]);
else $ed->redir("10/$db/$tb",['err'=>"Add field failed"]);
}else{
echo $head.$ed->menu($db,$tb,2).$ed->form("11/$db/$tb/$id").$stru.
"<tr><td><input type='text' name='fi'/></td><td><select name='ty'>".$ed->fieldtypes()."</select></td>
<td><select name='ar'><option value=''></option><option value='[]'>[ ]</option></select></td>
<td><input type='text' name='va'/></td>
<td><select name='nc'><option value='NOT NULL'>NOT NULL</option><option value='NULL'>NULL</option></select></td>
<td><input type='text' name='de'/></td>
</tr><tr><td colspan='6'><button type='submit'>Add</button></td></tr></table></form>";
}
break;
case "12"://structure change
$ed->check([1,2,3],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
if($ed->post('fi','!e') && $ed->post('ty','!e') && !is_numeric(substr($ed->post('fi'),0,1))){
$fi=$ed->sanitize($ed->post('fi'));
$fi_=$ed->post('fi_');
$ty=$ed->post('ty').($ed->post('va','e') ? "":"(".$ed->post('va').")").($ed->post('ar','e') ? "":"[]");
$nc=$ed->post('nc');
$de=($ed->post('de','e') ? "":" DEFAULT ".$ed->post('de'));
$ed->con->query("ALTER TABLE $tb RENAME COLUMN {$fi_} TO ".$ed->sanitize($ed->post('fi')));
$ed->con->query("ALTER TABLE $tb ALTER COLUMN $fi TYPE $ty");
$ed->con->query("ALTER TABLE $tb ALTER COLUMN $fi ".($nc=='NULL' ? "DROP NOT NULL":"SET NOT NULL"));
$ed->con->query("ALTER TABLE $tb ALTER COLUMN $fi ".(empty($de) ? "DROP DEFAULT":"SET $de"));
$ed->redir("10/$db/$tb",['ok'=>"Successfully changed"]);
}else{//structure form
echo $head.$ed->menu($db,$tb,2);
echo $ed->form("12/$db/$tb/".$ed->sg[3]).$stru;
$r_fe=$ed->con->query("SELECT a.attname AS column_name,pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type,a.attnotnull AS is_nullable,pg_get_expr(ad.adbin,ad.adrelid) AS column_default FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON a.attrelid=c.oid JOIN pg_catalog.pg_namespace n ON c.relnamespace=n.oid LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid=c.oid AND ad.adnum=a.attnum WHERE n.nspname='public' AND c.relname='$tb' AND a.attnum>0 AND NOT a.attisdropped AND a.attname='{$ed->sg[3]}'")->fetch();
$fe_type=preg_split("/[()]+/",$r_fe[1],-1,PREG_SPLIT_NO_EMPTY);
$dty=$fe_type[0];
if(strpos($r_fe[3],'nextval')!==false){
if($dty=='integer') $dty='serial';
elseif($dty=='bigint') $dty='bigserial';
elseif($dty=='smallint') $dty='smallserial';
}
echo "<tr><td><input type='hidden' name='fi_' value='{$r_fe[0]}'/><input type='text' name='fi' value='{$r_fe[0]}' /></td>
<td><select name='ty'>".$ed->fieldtypes($dty)."</select></td>
<td><select name='ar'><option value=''></option><option value='[]'".(empty($fe_type[2])?"":" selected").">[ ]</option></select></td>
<td><input type='text' name='va' value='".(isset($fe_type[1])?$fe_type[1]:"")."' /></td><td><select name='nc'>";
$cc=['NOT NULL','NULL'];
foreach($cc as $c) echo("<option value='$c'".(($r_fe[2]!=1 && $c=="NULL")?" selected":"").">$c</option>");
echo "</select></td><td><input type='text' name='de' value=\"{$r_fe[3]}\"/></td>
</tr><tr><td colspan='8'><button type='submit'>Change field</button></td></tr></table></form>";
}
break;
case "13"://drop field
$ed->check([1,2,3],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$fi=$ed->sg[3];
$q_drop=$ed->con->query("ALTER TABLE $tb DROP COLUMN ".$fi);
if($q_drop) $ed->redir("10/$db/$tb",['ok'=>"Successfully deleted"]);
$ed->redir("10/$db/$tb",['err'=>"Field delete failed"]);
break;
case "20"://table browse
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$where=(empty($_SESSION['_sqlsearch_'.$db.'_'.$tb])?"":" ".$_SESSION['_sqlsearch_'.$db.'_'.$tb]);
$q_cnt=$ed->con->query("SELECT COUNT(*) FROM $tb".$where)->fetch();
$totalr=$q_cnt[0];
$totalpg=ceil($totalr/$step);
if(empty($ed->sg[3])){
$pg=1;
}else{
$pg=$ed->sg[3];
$ed->check([1,4],['pg'=>$pg,'total'=>$totalpg,'redir'=>"20/$db/$tb"]);
}
$offset=($pg - 1) * $step;
$q_vic=$ed->con->query("SELECT relkind FROM pg_class WHERE relname='$tb'")->fetch();
echo $head.$ed->menu($db,($q_vic[0]=='v'?'':$tb),1,($q_vic[0]=='v'?['view',$tb]:''));
echo "<table><tr>";
if($q_vic[0]!='v'){echo "<th>Actions</th>";}
$q_bro=$ed->con->query("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema='public' AND table_name='$tb' ORDER BY ordinal_position");
$r_cl=$q_bro->num_row();
$coln=[];//field
$colt=[];//type
foreach($q_bro->fetch(2) as $r_bro){
$col_name=$r_bro['column_name'];
$col_type=$r_bro['data_type'];
$coln[]=$col_name;
$colt[]=$col_type;
echo "<th>".$col_name."</th>";
}
echo "</tr>";
$q_res=$ed->con->query("SELECT ".implode(",",$coln)." FROM {$tb}$where LIMIT $step OFFSET $offset");
foreach($q_res->fetch(1) as $r_rw){
$bg=($bg==1)?2:1;
$nu=$coln[0]."/".($r_rw[0]==""?"isnull":base64_encode($r_rw[0])).(isset($colt[1]) && ($colt[1]=="int" || $colt[1]=="varchar") && $colt[1]=="bytea" && !empty($coln[1]) && !empty($r_rw[1]) ? "/".$coln[1]."/".base64_encode($r_rw[1]):"");
echo "<tr class='r c$bg'>";
if($q_vic[0]!='v'){
echo "<td><a href='".$ed->path."22/$db/$tb/$nu'>Edit</a><a class='del' href='".$ed->path."23/$db/$tb/$nu'>Delete</a></td>";
}
$i=0;
while($i<$r_cl){
echo "<td>";
if($colt[$i]=="bytea"){
$le=empty($r_rw[$i])?0:strlen(stream_get_contents($r_rw[$i]));
echo "[bytea] ";
if($le > 4){
echo "<a href='".$ed->path."33/$db/$tb/$nu/".$coln[$i]."'>".number_format(($le/1024),2)." KB</a>";
}else{
echo number_format(($le/1024),2)." KB";
}
}elseif($r_rw[$i] && strlen($r_rw[$i]) > 70){
echo substr($r_rw[$i],0,70)."[...]";
}else{
echo empty($r_rw[$i])?'':htmlentities($r_rw[$i]);
}
echo "</td>";
++$i;
}
echo "</tr>";
}
echo "</table>";
echo $ed->pg_number($pg,$totalpg);
break;
case "21"://table insert
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$q_col=$ed->con->query("SELECT column_name,data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='{$tb}' ORDER BY ordinal_position");
$coln=[];//field
$colt=[];//type
$colu=[];//null
foreach($q_col->fetch(2) as $r_brw){
$coln[]=$r_brw['column_name'];
$colt[]=$r_brw['data_type'];
$colu[]=$r_brw['is_nullable'];
}
if($ed->post('save','i') || $ed->post('save2','i')){
$qr1="INSERT INTO $tb (";
$qr2="";
$qr3="VALUES(";
$qr4="";
$n=0;
while($n<count($coln)){
if($ed->post('r'.$n,'!e') || !empty($_FILES["r".$n]['tmp_name'])){
$qr2.=$coln[$n].",";
if($colt[$n]=="bytea"){
if(!empty($_FILES["r".$n]['tmp_name'])){
$qr4.="'\x".bin2hex(file_get_contents($_FILES["r".$n]['tmp_name']))."',";
}else{
$qr4.="'',";
}
}elseif($colt[$n]=='boolean'){
$qr4.=$ed->post('r'.$n,0).",";
}else{
if(!empty($_FILES['r'.$n]['tmp_name'])){
$blb="'\x".bin2hex(file_get_contents($_FILES['r'.$n]['tmp_name']))."',";
$qr4.="'{$blb}',";
}else{
$qr4.=(($ed->post('r'.$n,'e') && $colu[$n]==1)? "NULL":"'".addslashes($ed->post('r'.$n))."'").",";
}
}
}
++$n;
}
$qr2=substr($qr2,0,-1).") ";
$qr4=substr($qr4,0,-1).")";
$q_rins=$ed->con->query($qr1.$qr2.$qr3.$qr4);
if($ed->post('save2','i')) $rr=21;
else $rr=20;
if($q_rins) $ed->redir("$rr/$db/$tb",['ok'=>"Successfully inserted"]);
else $ed->redir("$rr/$db/$tb",['err'=>"Insert failed"]);
}else{
echo $head.$ed->menu($db,$tb,1).$ed->form("21/$db/$tb",1)."<table><caption>Insert Row</caption>";
$j=0;
while($j<count($coln)){
echo "<tr><td>".$coln[$j]."</td><td>";
if($colt[$j]=='boolean'){//boolean
foreach($bbs as $bb) echo "<input type='radio' name='r{$j}[]' value='$bb'/> $bb ";
}elseif($colt[$j]=="bytea" && !in_array($db,$deny)){
echo "<input type='file' name='r{$j}'/>";
}elseif($colt[$j]=="text"){//text
echo "<textarea name='r{$j}'></textarea>";
}else{
echo "<input type='text' name='r{$j}'/>";
}
++$j;
}
echo "<tr><td><button type='submit' name='save'>Save</button></td><td><button type='submit' name='save2'>Save & Insert Next</button></td></tr></table></form>";
}
break;
case "22"://table edit row
$ed->check([1,2,3],['redir'=>'20']);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$nu=$ed->sg[3];
if(empty($nu)) $ed->redir("20/$db/$tb",['err'=>"Can't edit empty field"]);
$id=($ed->sg[4]=="isnull"?"":base64_decode($ed->sg[4]));
$nu1=(empty($ed->sg[5])?"":$ed->sg[5]); $id1=(empty($ed->sg[6])?"":base64_decode($ed->sg[6]));
$q_col=$ed->con->query("SELECT column_name,data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='{$tb}' ORDER BY ordinal_position");
$coln=[];//field
$colt=[];//type
$colu=[];//null
foreach($q_col->fetch(2) as $r_brw){
$coln[]=$r_brw['column_name'];
$colt[]=$r_brw['data_type'];
$colu[]=$r_brw['is_nullable'];
}
$nul=("(".$nu." IS NULL OR ".$nu."='')");
if($ed->post('edit','i')){//update
$qr1="UPDATE $tb SET ";
$qr2="";
$p=0;
while($p<count($coln)){
if($colt[$p]=="bytea"){
if(!empty($_FILES["te".$p]['tmp_name'])){