-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlite.php
More file actions
1990 lines (1954 loc) · 82.1 KB
/
lite.php
File metadata and controls
1990 lines (1954 loc) · 82.1 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('sqlite3') && !extension_loaded('pdo_sqlite')) die('Install sqlite3 or pdo_sqlite extension!');
session_name('Lite');
session_start();
$bg=2;
$step=20;
$version="3.22";
$bbs=['False','True'];
$deny=['sqlite_sequence'];
class DBT {
public static $litetype=['sqlite3','pdo_sqlite'];
private static $instance=NULL;
private $_cnx,$_query,$_fetch=[],$_num_col,$ltype;
public static function factory($db){
if(!isset(self::$instance)) self::$instance=new DBT($db);
return self::$instance;
}
public function __construct($db){
$ty=self::$litetype[0];
if(extension_loaded($ty)) $this->ltype=$ty;
else $this->ltype=self::$litetype[1];
if($this->ltype==$ty) $this->_cnx=new SQLite3($db);
else $this->_cnx=new PDO("sqlite:".$db);
}
public function exec($sql){
return $this->_cnx->exec($sql);
}
public function query($sql,$single=false){
try{
if($this->ltype==self::$litetype[0]){
if($single==false) $this->_query=@$this->_cnx->query($sql);
else $this->_query=@$this->_cnx->querySingle($sql);
} else {
$this->_query=@$this->_cnx->query($sql);
}
return $this;
}catch(Exception $e){
return false;
}
}
public function last(){
if($this->ltype==self::$litetype[0]) return $this->_cnx->changes();
else return $this->_query->rowCount();
}
public function err(){
if($this->ltype==self::$litetype[0]) return $this->_cnx->lastErrorCode();
else return $this->_cnx->errorInfo();
}
public function fetch($mode=0){
if($this->ltype==self::$litetype[0]){
if($mode==1 || $mode==2){
switch($mode){
case 1: $ty=SQLITE3_NUM; break;
case 2: $ty=SQLITE3_ASSOC; break;
}
$res=[];
while($row=$this->_query->fetchArray($ty)){
$res[]=$row;
}
return $res;
} else {
return $this->_query;
}
} 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->fetchColumn();
}
}
}
public function num_col(){
if($this->ltype==self::$litetype[0]) return $this->_query->numColumns();
else return $this->_query->columnCount();
}
}
class ED {
public $con,$dir,$ext=".sqlite",$sg,$path;
protected $passwd='';
public function __construct(){
$this->dir=getcwd()."/";
if(!file_exists($this->dir)) @mkdir($this->dir,0744);
$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),'/.\\')).'/';
}
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;
}
function isBase64($data){
return (bool) preg_match('/^[a-zA-Z0-9+\/]+={0,2}$/',$data) && (strlen($data) % 4 === 0);
}
public function form($furl,$enc=''){
return "<form action='".$this->path.$furl."' method='post'".($enc==1 ? " enctype='multipart/form-data'":"").">";
}
public function fieldtype($slct=''){
$fieldtype=['Numbers'=>["INTEGER","INT","DECIMAL"],'Strings'=>["VARCHAR","TEXT"],'DateTime'=>["DATE","DATETIME","TIME","TIMESTAMP"],'Binary'=>["BOOLEAN","BLOB"]];
$ft='';
foreach($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($key='',$op=''){
if($key==='' && !empty($_POST)){
return ($_SERVER['REQUEST_METHOD']==='POST' ? TRUE : FALSE);
}
if(!isset($_POST[$key])) return FALSE;
if(is_array($_POST[$key])){
if(isset($op) && is_numeric($op)){
return $_POST[$key][$op];
} else {
$aout=[];
foreach($_POST[$key] as $k=>$val){
if($val !='') $aout[$k]=$val;
}
}
} else {
$aout=$_POST[$key];
}
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 listdb(){
$dbs=[];
$dh=@opendir($this->dir);
while(($dbf=readdir($dh)) != false){
$dbi=pathinfo($dbf);
if(@is_file($this->dir.$dbf) && !empty($dbi['extension']) && ".".$dbi['extension']==$this->ext && (filesize($dbf)==0 || file_get_contents($dbf,false,null,0,16)=="SQLite format 3\x00")) $dbs[]=$dbi['filename'];
}
closedir($dh);
sort($dbs);
return $dbs;
}
public function check($level=[],$param=[]){
if(!empty($_SESSION['ltoken'])){
if($_SESSION['ltoken'] !=base64_encode(md5($_SERVER['HTTP_USER_AGENT'].$this->passwd))) $this->redir("50",['err'=>"Wrong password"]);
$h='HTTP_X_REQUESTED_WITH';
if(isset($_SERVER[$h]) && !empty($_SERVER[$h]) && strtolower($_SERVER[$h]) == 'xmlhttprequest') session_regenerate_id(true);
} else {
$this->redir("50");
}
if(in_array('1',$level)){//check db
$op=$this->sg[0];
$db=$this->sg[1];
$dbx=$this->dir.$db.$this->ext;
if(!is_file($dbx)) $this->redir('',['err'=>"DB not exist"]);
if(is_writable($this->dir) && $op!=3 && $op!=4){
$this->con=DBT::factory($dbx);
$this->con->exec("PRAGMA default_synchronous=OFF");
}
}
if(in_array('2',$level)){//check table
$tb=$this->sg[2];
$obj=(($op==20) ? "(type='table' OR type='view')":"type='table'");
$ist=$this->con->query("SELECT 1 FROM sqlite_master WHERE name='$tb' AND ".$obj,true)->fetch();
if(!$ist) $this->redir("5/$db",['err'=>"Table not exist"]);
}
if(in_array('3',$level)){//check field
$q_fld=$this->con->query("PRAGMA table_info($tb)")->fetch(2);
$meta=[];
foreach($q_fld as $row) $meta[]=$row['name'];
$err=['err'=>"Field not exist"];
if(!in_array($this->sg[3],$meta)) $this->redir($param['redir']."/$db/$tb",$err);
if(isset($this->sg[5])){
if(!in_array($this->sg[5],$meta)) $this->redir($param['redir']."/$db/$tb",$err);
}
}
if(in_array('4',$level)){//check pagination
if(!is_numeric($param['pg']) || $param['pg'] > $param['total'] || $param['pg'] <1) $this->redir($param['redir'],['err'=>"Invalid page number"]);
}
if(in_array('5',$level)){//check view,trigger
$sp=['view','trigger'];
$sg3=$this->sg[3];
if($op!=49 && ($op==40 && $sg3!=$sp[0]) || ($op==41 && $sg3!=$sp[1])) $this->redir("5/$db");
$q_sp=$this->con->query("SELECT 1 FROM sqlite_master WHERE name='".$this->sg[2]."' AND type='$sg3'",true)->fetch();
if(!$q_sp) $this->redir("5/$db",['err'=>"Not available object"]);
}
}
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'){
$nr=@$this->con->query("SELECT COUNT(*) FROM ".$sp[1],true)->fetch();
$str.=$dv."<li><a href='{$this->path}40/$db/".$sp[1]."/view'>Structure</a></li>".
($nr!=false ? "<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){
$str.="<div class='l3 auto'><select onchange='location=this.value;'><optgroup label='databases'>";
foreach($this->listdb() as $udb) $str.="<option value='{$this->path}5/$udb'".($udb==$db?" selected":"").">$udb</option>";
$str.="</optgroup></select>";
$q_ts=[]; $c_sp=!empty($sp) ? count($sp):"";
if($tb!="" || $c_sp >1){
$q_ts=$this->con->query("SELECT name,type FROM sqlite_master WHERE type IN ('table','view','trigger') ORDER BY type,name")->fetch(1);
$sl2="<select onchange='location=this.value;'>";
$qtype='';
foreach($q_ts as $r_ts){
if($qtype !=$r_ts[1]){
if($qtype !='') $sl2.='</optgroup>';
$sl2.='<optgroup label="'.$r_ts[1].'s">';
}
if($r_ts[1]=='view'){
$in=[20,40];
$nr=@$this->con->query("SELECT COUNT(*) FROM ".$r_ts[0],true)->fetch();
}else{
$in=[10,20,21,24];
$nr=true;
}
if($nr!=false){
$sl2.="<option value='".$this->path.($r_ts[1]=='trigger'?"41/$db/".$r_ts[0]."/".$r_ts[1]:(in_array($this->sg[0],$in)?$this->sg[0]:20)."/$db/".$r_ts[0])."'".($r_ts[0]==$tb || ($c_sp >1 && $r_ts[0]==$sp[1])?" selected":"").">".$r_ts[0]."</option>";
$qtype=$r_ts[1];
}
}
if($qtype !='') $sl2.='</optgroup>';
$str.=$sl2."</select>".((!empty($_SESSION["_litesearch_{$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, sqlite, gz, zip</small>".$this->form("30/$db",1)."<input type='file' name='importfile' />
<input type='hidden' name='send' value='ff' /><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></div><div class='col2'>";
return $str;
}
public function pg_number($pg,$totalpg){
if($totalpg > 1){
if($this->sg[0]==20) $lnk=$this->path."20/".$this->sg[1]."/".$this->sg[2];
elseif($this->sg[0]==5) $lnk=$this->path."5/".$this->sg[1];
$pgs='';$k=1;
while($k <=$totalpg){
$pgs.="<option ".(($k==$pg) ? "selected>":"value='$lnk/$k'>")."$k</option>";
++$k;
}
$lft=($pg>1?"<a href='$lnk/1'>First</a><a href='$lnk/".($pg-1)."'>Prev</a>":"");
$rgt=($pg < $totalpg?"<a href='$lnk/".($pg+1)."'>Next</a><a href='$lnk/$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 sqlite_master WHERE name='$fname' AND type='table'",true)->fetch();
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);
$delims=[';'=> 0,','=> 0];//delimiter
foreach($delims as $dl=> &$cnt) $cnt=count(str_getcsv($body,$dl));
$mark=array_search(max($delims),$delims);
$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 sqlite_master WHERE name='$fname' AND type='table'",true)->fetch();
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
$sq=[];
$db=(string)$xml->xpath('//database')[0]->attributes();
$sq[]=["DATABASE $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 \"".(string)$tt['name']."\"(".substr($co,0,-1).") VALUES(".substr($va,0,-1).");";
}
return [array_merge($sq,$e)];
}
public function imp_sqlite($fname,$body){
$res=[];
if(substr($body,0,15) !="SQLite format 3") $res[$fname]="No sqlite file";
$file=pathinfo($fname);
$new=$this->dir.$this->sanitize($file['filename']).$this->ext;
if(!file_exists($new)){
$sfile=fopen($new,"wb");
if(!$sfile) $res[$fname]="Unable to create sqlite file";
fwrite($sfile,$body);
fclose($sfile);
} else $res[$fname]="File already exists";
return $res;
}
public function tb_structure($tb,$fopt,$tab=''){
$val="";
if(in_array('drop',$fopt)){//check option drop
$val.=$tab."DROP TABLE IF EXISTS $tb;\n";
}
$q_tbst=$this->con->query("SELECT sql FROM sqlite_master WHERE name='$tb'",true)->fetch().";";
if(in_array('ifnot',$fopt)){//check option if not
$q_tbst=preg_replace('~(CREATE\sTABLE\s)(.*)~i','${1}IF NOT EXISTS ${2}',$q_tbst);
}
$val.=$tab.str_replace("\n","\n".$tab,$q_tbst)."\n";
$q_tidx=$this->con->query("SELECT sql FROM sqlite_master WHERE tbl_name='$tb' AND type='index'");
$cidx=$q_tidx->num_col();
if($cidx > 0){
foreach($q_tidx->fetch(1) as $r_ix){
if($r_ix[0]) $val.=$tab.$r_ix[0].";\n";
}
}
return $val;
}
public function getTables($dbx){
$tbs=[];$vws=[];
if($this->post('tbs')=='' && $this->post('dbs')!=''){
$tabs=$dbx->query("SELECT name FROM sqlite_master WHERE type IN ('table','view')")->fetch(1);
$tabs=empty($tabs) ? []:call_user_func_array('array_merge',$tabs);
} else {
$tabs=$this->post('tbs');
}
foreach($tabs as $tb){
$q_st=$dbx->query("SELECT name,type FROM sqlite_master WHERE name='$tb'")->fetch(2);
if($q_st[0]['name']==$tb && $q_st[0]['type']=='view'){
array_push($vws,$tb);
} elseif($q_st[0]['name']==$tb && $q_st[0]['type']=='table'){
array_push($tbs,$tb);
}
}
$dbx=NULL;
return [$tbs,$vws];
}
}
$ed=new ED;
$head='<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8"><title>EdLiteAdmin</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}
small{font-size:90%}
.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{width:100%}
.msg,.a{cursor:pointer}
.handle{font:1.25rem/.75rem Arial;font-weight:bold;vertical-align:middle}
.handle:hover{cursor:move}
tr.dragging{opacity:0.5}
tr.drag-over{background:#9be}
</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/edliteadmin">EdLiteAdmin '.$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></ul></li><li><a href="'.$ed->path.'51">Logout</a></li></ul>').'</div>';
$stru="<table><caption>Structure</caption><tr><th>Field</th><th>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'>".$ed->form(2)."<input type='text' name='dbc' placeholder='Database' /><br/><button type='submit'>Create</button></form></div><div class='col2'><table><tr><th>Database</th><th>Tables</th><th><a href='{$ed->path}31'>Exp</a>/ Actions</th></tr>";
foreach($ed->listdb() as $db){
$bg=($bg==1)?2:1;
$dbx=new DBT($ed->dir.$db.$ed->ext);
$qs_nr=$dbx->query("SELECT COUNT(*) FROM sqlite_master WHERE type IN ('table','view')",true)->fetch();
echo "<tr class='r c$bg'><td>$db</td><td>$qs_nr</td><td><a href='{$ed->path}31/$db'>Exp</a><a class='del' href='{$ed->path}4/$db'>Drop</a><a href='{$ed->path}5/$db'>Browse</a></td></tr>";
$dbx=NULL;
}
echo "</table>";
break;
case "2"://create db
$ed->check();
if($ed->post('dbc','!e')){
$db=$ed->dir.$ed->sanitize($ed->post('dbc')).$ed->ext;
if(@is_file($db)) $ed->redir("",['err'=>"DB already exist"]);
new DBT($db);
if(@is_file($db)) $ed->redir("",['ok'=>"Created DB"]);
else $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('rdb','!e') && $ed->sanitize($ed->post('rdb')) !=$db){
$ndb=$ed->sanitize($ed->post('rdb'));
rename($ed->dir.$db.$ed->ext,$ed->dir.$ndb.$ed->ext);
$ed->redir("",['ok'=>"Successfully renamed"]);
} else $ed->redir("5/$db",['err'=>"DB name must not be empty"]);
break;
case "4"://delete db
$ed->check([1]);
$db=$ed->sg[1];
if(@is_file($ed->dir.$db.$ed->ext)){
$fl=$ed->dir.$db.$ed->ext;
chmod($fl,0664);
@unlink($fl);
$ed->redir("",['ok'=>"Successfully deleted"]);
} else $ed->redir("",['err'=>"Missing DB"]);
break;
case "5"://show tables
$ed->check([1]);
$db=$ed->sg[1];
$all=$ed->con->query("SELECT COUNT(*) FROM sqlite_master WHERE type IN ('table','view')",true)->fetch();
$totalpg=ceil($all/$step);
if(empty($ed->sg[2])){
$pg=1;
} else {
$pg=$ed->sg[2];
$ed->check([4],['pg'=>$pg,'total'=>$totalpg,'redir'=>"5/$db"]);
}
$offset=($pg - 1) * $step;
echo $head.$ed->menu($db,'',1);
echo "<table><tr><th>Table/View</th><th>Rows</th><th>Actions</th></tr>";
$q_tabs=$ed->con->query("SELECT name,type FROM sqlite_master WHERE type IN ('table','view') ORDER BY type,name LIMIT $offset,$step")->fetch(1);
foreach($q_tabs as $r_tabs){
if(!in_array($r_tabs[0],$deny)){
$nr=@$ed->con->query("SELECT COUNT(*) FROM ".$r_tabs[0],true)->fetch();
$q_num=($r_tabs[1]=="view" ? $r_tabs[1] : $nr);
$bg=($bg==1)?2:1;
$vl="/$db/".$r_tabs[0];
if($r_tabs[1]=="view"){
$lnk="40{$vl}/view"; $vdel="49{$vl}/view";
} else {
$lnk="10{$vl}"; $vdel="26{$vl}";
}
echo "<tr class='r c$bg'><td>".$r_tabs[0]."</td><td>$q_num</td><td><a href='{$ed->path}{$lnk}'>Structure</a><a class='del' href='{$ed->path}{$vdel}'>Drop</a>".(is_numeric($nr) || ($nr!=false && $q_num=="view") ? "<a href='{$ed->path}20/$db/".$r_tabs[0]."'>Browse</a>":"")."</td></tr>";
}
}
echo "</table>";
$q_tri=$ed->con->query("SELECT name,tbl_name FROM sqlite_master WHERE type='trigger' ORDER BY name")->fetch(1);
$t=0;
$trg_tab="<table><tr><th>Trigger</th><th>Table</th><th>Actions</th></tr>";
foreach($q_tri as $r_tri){
$bg=($bg==1)?2:1;
$trg_tab.="<tr class='r c$bg'><td>".$r_tri[0]."</td><td>".$r_tri[1]."</td><td><a href='{$ed->path}41/$db/".$r_tri[0]."/trigger'>Edit</a><a class='del' href='{$ed->path}49/$db/".$r_tri[0]."/trigger'>Drop</a></td></tr>";
++$t;
}
echo ($t>0 ? $trg_tab."</table>":"").$ed->pg_number($pg,$totalpg);
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 && is_numeric($ed->post('nrf'))){
$q_ch=$ed->con->query("SELECT 1 FROM sqlite_master WHERE name='".$ed->sanitize($ed->post('ctab'))."'",true)->fetch();
if($q_ch) $ed->redir("5/$db",['err'=>"Name already exists"]);
echo $head.$ed->menu($db,'',2);
if($ed->post('crtb','i')){
$q1='';
$n=0;
while($n<$ed->post('nrf')){
$v1=$ed->sanitize($ed->post('fi'.$n));
if(!empty($v1) && !is_numeric(substr($v1,0,1))){
$v2=$ed->post('ty'.$n); $v3=$ed->post('vl'.$n); $v4=$ed->post('nl'.$n); $v5=$ed->post('df'.$n);
$q1.=$v1." ".$v2.($v3!='' ? "(".$v3.")":"").($v4==1 ? " NOT NULL":"").($v5!="" ? " DEFAULT '".$v5."'":"").",";
}
++$n;
}
$q2="CREATE TABLE ".$ed->sanitize($ed->post('ctab'))."(".substr($q1,0,-1).");";
echo "<p>".(strlen($q1) > 5 && $ed->con->query($q2) ? "<b>OK!</b> $q2<br/>":"<b>FAILED!</b> $q2")."</p>";
} else {
echo $ed->form("6/$db")."<input type='hidden' name='ctab' value='".$ed->post('ctab')."'/>
<input type='hidden' name='nrf' value='".$ed->post('nrf')."'/>$stru";
$nr=$ed->post('nrf');
$i=0;
while($i<$nr){
echo "<tr><td><input type=text name='fi$i' /></td><td><select name='ty$i'>".$ed->fieldtype()."</select></td><td><input type=text name='vl$i' /></td><td><select name='nl$i'><option value='0'>Yes</option><option value='1'>No</option></select></td><td><input type=text name='df$i' /></td></tr>";
++$i;
}
echo "<tr><td colspan='5'><button type='submit' name='crtb'>Create table</button></td></tr></table></form>";
}
} else {
$ed->redir("5/$db",['err'=>"Table name must not be empty"]);
}
break;
case "9":
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
if($ed->post('copytab','!e')){//copy table
$cpy=$ed->post('copytab');
$ncpy=basename($cpy,$ed->ext);
$q_tc=$ed->con->query("SELECT sql FROM sqlite_master WHERE name='$tb'",true)->fetch();
$r_sql=preg_split("/\([^()]*\)(*SKIP)(*F)|[()]/",$q_tc,-1,PREG_SPLIT_NO_EMPTY);
$ed->con->exec("ATTACH DATABASE '".$ed->dir.$cpy.$ed->ext."' AS $ncpy");
$q_cc=$ed->con->exec("SELECT 1 FROM {$ncpy}.{$tb}");
if($q_cc) $ed->redir("10/$db/$tb",['err'=>"Table already exists"]);
$ed->con->exec("CREATE TABLE {$ncpy}.{$tb} (".$r_sql[1].");");
$ed->con->exec("INSERT INTO {$ncpy}.{$tb} SELECT * FROM $tb");
$ed->con->exec("DETACH DATABASE $ncpy");
$ed->redir("10/$db/$tb",['ok'=>"Successfully copied"]);
}
if($ed->post('rtab','!e')){//rename table
$new=$ed->sanitize($ed->post('rtab'));
$ren_tb=$ed->con->exec("ALTER TABLE $tb RENAME TO $new");
if($ren_tb===false) $ed->redir("10/$db/$tb",['err'=>"Can't rename"]);
$ed->redir("5/$db",['ok'=>"Successfully renamed"]);
}
if($ed->post('reord','!e')){//reorder
$q_fd=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
$q_fk=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
$post=$ed->post('reord');
$els=explode(",",$post);
$s_fd=[];$n_fd=[];$s_pk=[];$n_pk=[];$fk='';
foreach($q_fd as $r_fd){
$s_fd[$r_fd[1]]=$r_fd[1].' '.$r_fd[2].($r_fd[3]==1 ? ' NOT NULL':'').(empty($r_fd[4]) ? '':' DEFAULT '.$r_fd[4]);
if($r_fd[5]>0) $s_pk[]=$r_fd[1];
}
foreach($q_fk as $r_fk){
$fk.="FOREIGN KEY ({$r_fk['from']}) REFERENCES {$r_fk['table']} ({$r_fk['to']})".(empty($r_fk['on_delete'])?"":" ON DELETE ".$r_fk['on_delete']).(empty($r_fk['on_update'])?"":" ON UPDATE ".$r_fk['on_update']).",";
}
foreach($els as $k=>$el){
$n_fd[$k]=$s_fd[$el];
if(in_array($el,$s_pk)) $n_pk[]=$el;
}
$q_iv=$ed->con->query("SELECT name,sql FROM sqlite_master WHERE type='view'")->fetch(1);
foreach($q_iv as $r_iv) $ed->con->exec("DROP VIEW ".$r_iv[0]);
$q_it=$ed->con->query("SELECT sql FROM sqlite_master WHERE tbl_name='$tb' AND type IN ('index','trigger')")->fetch(1);
$n_fd=implode(',',$n_fd);
$qr=(empty($s_pk) ? "":", PRIMARY KEY (".implode(',',$n_pk)."),").$fk;
$r_qs=["BEGIN TRANSACTION"];
$r_qs[]="CREATE TABLE temp_$tb (".$n_fd.substr($qr,0,-1).")";
$r_qs[]="INSERT INTO temp_$tb SELECT $post FROM $tb";
$r_qs[]="DROP TABLE $tb";
$r_qs[]="ALTER TABLE temp_$tb RENAME TO $tb";
foreach($q_iv as $r_iv) $r_qs[]=$r_iv[1];
foreach($q_it as $r_it) $r_qs[]=$r_it[0];
$r_qs[]="COMMIT";
foreach($r_qs as $r_q) @$ed->con->exec($r_q);
exit;
}
if($ed->post('idx','!e') && is_array($ed->post('idx'))){//create index
$idx=implode(',',$ed->post('idx'));
$idn=implode('_',$ed->post('idx'));
if($ed->post('primary','i')){
$q_pr=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
$r_sql='';$f='';$fk='';
foreach($q_pr as $r_pr){
$r_sql.=$r_pr[1]." ".$r_pr[2].($r_pr[3]>0 ? " NOT NULL":"").($r_pr[4]!='' ? " DEFAULT ".$r_pr[4]:"").",";
$f.=$r_pr[1].",";
}
$f=substr($f,0,-1);
$sqs=$ed->con->query("SELECT sql FROM sqlite_master WHERE tbl_name='$tb' AND type IN ('index','trigger')")->fetch(1);
$q_fk=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
foreach($q_fk as $r_fk){
$fk.="FOREIGN KEY ({$r_fk['from']}) REFERENCES {$r_fk['table']} ({$r_fk['to']})".(empty($r_fk['on_delete'])?"":" ON DELETE ".$r_fk['on_delete']).(empty($r_fk['on_update'])?"":" ON UPDATE ".$r_fk['on_update']).",";
}
$ed->con->exec("BEGIN TRANSACTION");
$ed->con->exec("CREATE TABLE temp_$tb ($r_sql$fk PRIMARY KEY($idx))");
$ed->con->exec("INSERT INTO temp_$tb SELECT $f FROM $tb");
$ed->con->exec("DROP TABLE $tb");
$ed->con->exec("ALTER TABLE temp_$tb RENAME TO $tb");
foreach($sqs as $sq) $ed->con->exec($sq[0]);
$ed->con->exec("COMMIT");
} elseif($ed->post('unique','i')){
$ed->con->exec("CREATE UNIQUE INDEX UNI__$idn ON $tb($idx)");
} elseif($ed->post('index','i')){
$ed->con->exec("CREATE INDEX IDX__$idn ON $tb($idx)");
}
$ed->con->exec("VACUUM");
$ed->redir("10/$db/$tb",['ok'=>"Successfully created"]);
}
if(!empty($ed->sg[3])){//drop index
$s_idx=base64_decode($ed->sg[3]);
$ed->con->exec("PRAGMA foreign_keys=off");
$q_ii=$ed->con->exec("DROP INDEX $s_idx");
$ed->con->exec("PRAGMA foreign_keys=on");
if($q_ii===false) $ed->redir("10/$db/$tb",['err'=>"Can't drop index"]);
else $ed->redir("10/$db/$tb",['ok'=>"Successfully dropped"]);
}
$ed->redir("10/$db/$tb",['err'=>"Wrong action"]);
break;
case "10"://structure
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
echo $head.$ed->menu($db,$tb,1).$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>PK</th><th>Actions</th></tr></thead><tbody class='sort'>";
$q_rec=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
foreach($q_rec as $rec){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg' id='".$rec[1]."'><td><input type='checkbox' name='idx[]' value='".$rec[1]."' /></td><td>".$rec[1]."</td><td>".$rec[2]."</td><td>".($rec[3]==0 ? 'Yes':'No')."</td><td>".$rec[4]."</td><td>".($rec[5]>0 ? 'PK':'')."</td><td><a href='{$ed->path}12/$db/$tb/".$rec[1]."'>change</a><a class='del' href='{$ed->path}13/$db/$tb/".$rec[1]."'>drop</a><a href='{$ed->path}11/$db/$tb/'>add</a><span draggable='true' class='handle' title='move'>⇵</span></td></tr>";
}
echo "</tbody><tfoot><tr><td class='auto' colspan='7'><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/analyze'>Analyze</a></div></td></tr></tfoot></table></form>";
$q_idx=$ed->con->query("PRAGMA index_list($tb)")->fetch(1);
echo "<table><caption>Index</caption><tr><th>Name</th><th>Field</th><th>Unique</th><th>Actions</th></tr>";
foreach($q_idx as $rc){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>".$rc[1]."</td><td>";
$q=$ed->con->query("PRAGMA index_info('".$rc[1]."')")->fetch(1);
foreach($q as $rd) echo $rd[2]."<br/>";
echo "</td><td>".($rc[2]==1 ? 'YES':'NO')."</td><td><a class='del' href='{$ed->path}9/$db/$tb/".base64_encode($rc[1])."'>drop</a></td></tr>";
}
$q_chk=$ed->con->query("SELECT sql FROM sqlite_master WHERE type='table' AND name='$tb'",true)->fetch();
preg_match_all('/\bCHECK\s*\((.+)\)/i',$q_chk,$match);
foreach($match[1] as $r_ch){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>CHECK</td><td colspan='3'>".$r_ch."</td></tr>";
}
$q_fkl=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
echo "</table><table><caption>Foreign Keys</caption><tr><th>Field</th><th>Target</th><th>On delete</th><th>On update</th><th>Actions <a href='{$ed->path}14/$db/$tb'>add</a></th></tr>";
foreach($q_fkl as $r_fkl){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'><td>".$r_fkl['from']."</td><td>".$r_fkl['table'].".".$r_fkl['to']."</td><td>".$r_fkl['on_delete']."</td><td>".$r_fkl['on_update']."</td><td><a href='{$ed->path}14/$db/$tb/{$r_fkl['id']}'>change</a><a class='del' href='{$ed->path}14/$db/$tb/{$r_fkl['id']}/fk'>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><br/>Copy Table<br/>".$ed->form("9/$db/$tb")."<select name='copytab'>";
foreach($ed->listdb() as $dbl) echo "<option value='$dbl'>$dbl</option>";
echo "</select><br/><button type='submit'>Copy</button></form></td></tr></table>";
break;
case "11"://add field
$ed->check([1,2],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
if($ed->post('add','i')){
$f1=$ed->sanitize($ed->post('f1'));
if(!empty($f1)){
$e=$ed->con->query("ALTER TABLE $tb ADD COLUMN $f1 ".$ed->post('f2').($ed->post('f3','!e')?"(".$ed->post('f3').")":"").($ed->post('f4')==1 ? " NOT NULL":"").($ed->post('f5')!='' ? " DEFAULT '".$ed->post('f5')."'":""));
} else $ed->redir("11/$db/$tb",['err'=>"Empty field name"]);
if($e) $ed->redir("10/$db/$tb",['ok'=>"Successfully added"]);
else $ed->redir("10/$db/$tb",['err'=>"Can't add this field"]);
} else {
echo $head.$ed->menu($db,$tb,2).$ed->form("11/$db/$tb").$stru."<tr><td><input type='text' name='f1' /></td><td><select name='f2'>".$ed->fieldtype()."</select></td><td><input type='text' name='f3' /></td><td><select name='f4'><option value='0'>Yes</option><option value='1'>No</option></select></td><td><input type='text' name='f5' /></td></tr><tr><td colspan='5'><button type='submit' name='add'>Add field</button></td></tr></table></form>";
}
break;
case "12"://change field
$ed->check([1,2,3],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$fn1=$ed->sg[3];
$q_t=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
if($ed->post('change','i')){
$qr='';$pk='';$fk='';$pe='';
$fn2=$ed->sanitize($ed->post("cf1"));
$q_fk=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
foreach($q_fk as $r_fk){
$fkr=$r_fk['from']==$fn1 ? $fn2:$r_fk['from'];
$fk.="FOREIGN KEY ($fkr) REFERENCES ".$r_fk['table']." (".$r_fk['to'].")".(empty($r_fk['on_delete'])?"":" ON DELETE ".$r_fk['on_delete']).(empty($r_fk['on_update'])?"":" ON UPDATE ".$r_fk['on_update']).",";
}
foreach($q_t as $e){
if($e[1]==$fn1){
if(empty($fn2) || is_numeric(substr($fn2,0,1))) $ed->redir("10/$db/$tb",['err'=>"Not a valid field name"]);
$qr.=$fn2." ".$ed->post('cf2').($ed->post('cf3','!e')?"(".$ed->post('cf3').")":"").($ed->post('cf4')==1 ? " NOT NULL":"").($ed->post("cf5","e")?"":" DEFAULT '".$ed->post("cf5")."'").",";
} else {
$pe.=$e[1].",";
$qr.=$e[1]." ".$e[2].($e[3]!=0 ? " NOT NULL":"").($e[4]!='' ? " DEFAULT ".$e[4]:"").",";
}
if($e[5]>0){
$pk.=($e[1]==$fn1 ? $fn2:$e[1]).",";
}
}
$qr.=(empty($pk) ? "":" PRIMARY KEY(".substr($pk,0,-1)."),").$fk;
$ed->con->exec("BEGIN TRANSACTION");
$q_iv=$ed->con->query("SELECT name,sql FROM sqlite_master WHERE type='view'")->fetch(1);
foreach($q_iv as $r_it) $ed->con->exec("DROP view ".$r_it[0]);
$q_it=$ed->con->query("SELECT type,name,sql FROM sqlite_master WHERE tbl_name='$tb' AND type IN ('index','trigger')")->fetch(1);
foreach($q_it as $r_it) $ed->con->exec("DROP ".$r_it[0]." ".$r_it[1]);
$ed->con->exec("CREATE TABLE temp_$tb (".substr($qr,0,-1).")");
$ed->con->exec("INSERT INTO temp_$tb($pe$fn2) SELECT $pe$fn1 FROM $tb");
$ed->con->exec("DROP TABLE $tb");
$ed->con->exec("ALTER TABLE temp_$tb RENAME TO $tb");
foreach($q_it as $r_it){
if($r_it[0]=='index'){
$keys=preg_split("/[()]+/",$r_it[2]);
$key=explode(",",$keys[1]);
$el=array_search($fn1,$key);
if($el!==false) $key[$el]=$fn2;
$ed->con->exec($keys[0]."(".implode(",",$key).")");
}else $ed->con->exec($r_it[2]);
}
foreach($q_iv as $r_it) $ed->con->exec($r_it[1]);
$ed->con->exec("COMMIT");
$ed->redir("10/$db/$tb",['ok'=>"Successfully changed"]);
} else {
echo $head.$ed->menu($db,$tb,2).$ed->form("12/$db/$tb/$fn1").$stru;
foreach($q_t as $d){
if($d[1]==$fn1){
$d_val=preg_split("/[()]+/",$d[2],-1,PREG_SPLIT_NO_EMPTY);
echo "<tr><td><input type='text' name='cf1' value='".$d[1]."' /></td><td><select name='cf2'>".$ed->fieldtype(strtoupper($d_val[0]))."</select></td><td><input type='text' name='cf3' value='".(isset($d_val[1])?$d_val[1]:"")."' /></td><td><select name='cf4'><option value='0'>Yes</option><option value='1'".($d[3]!=0 ? " selected":"").">No</option></select></td><td><input type='text' name='cf5' value='".($d[4]==''?'':str_replace("'","",$d[4]))."' /></td></tr>";
}
}
echo "<tr><td colspan='5'><button type='submit' name='change'>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];
$fn=$ed->sg[3];
$obj=[];
$q_iv=$ed->con->query("SELECT name,sql FROM sqlite_master WHERE type='view'")->fetch(1);
foreach($q_iv as $r_iv) $ed->con->exec("DROP VIEW ".$r_iv[0]);
$q_it=$ed->con->query("SELECT type,name,sql FROM sqlite_master WHERE tbl_name='$tb' AND type IN ('index','trigger')")->fetch(1);
foreach($q_it as $r_it) $ed->con->exec("DROP ".$r_it[0]." ".$r_it[1]);
$q_f=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
$qr='';$pk='';$fk='';$re='';
foreach($q_f as $r_f){
if($r_f[1]!=$fn){
$qr.=$r_f[1]." ".$r_f[2].($r_f[3]!=0 ? " NOT NULL":"").($r_f[4]!='' ? " DEFAULT ".$r_f[4]:"").",";
$re.=$r_f[1].",";
if($r_f[5]) $pk.=$r_f[1].",";
}
}
$q_fk=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
foreach($q_fk as $r_fk){
if($r_fk['from']!=$fn) $fk.="FOREIGN KEY (".$r_fk['from'].") REFERENCES ".$r_fk['table']." (".$r_fk['to'].")".(empty($r_fk['on_delete'])?"":" ON DELETE ".$r_fk['on_delete']).(empty($r_fk['on_update'])?"":" ON UPDATE ".$r_fk['on_update']).",";
}
$qr.=(empty($pk) ? "":" PRIMARY KEY(".substr($pk,0,-1)."),").$fk;
$q_r=["BEGIN TRANSACTION"];
$q_r[]="CREATE TABLE temp_$tb (".substr($qr,0,-1).")";
$q_r[]="INSERT INTO temp_$tb SELECT ".substr($re,0,-1)." FROM $tb";
$q_r[]="DROP TABLE $tb";
$q_r[]="ALTER TABLE temp_$tb RENAME TO $tb";
foreach($q_iv as $r_iv) $q_r[]=$r_iv[1];
foreach($q_it as $r_it) $q_r[]=$r_it[0];
$q_r[]="COMMIT";
foreach($q_r as $q) @$ed->con->exec($q);
$ed->redir("5/$db",['ok'=>"Successfully deleted"]);
break;
case "14"://fk
$ed->check([1,2],['redir'=>10]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$fkty=['RESTRICT','NO ACTION','CASCADE','SET NULL','SET DEFAULT'];
$q_t=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
$q_fk=$ed->con->query("PRAGMA foreign_key_list($tb)")->fetch(2);
if(($ed->post('table','!e') && $ed->post('to','!e')) || isset($ed->sg[4])){
$qr='';$pk='';$fk='';$re='';
foreach($q_fk as $r_fk){
if(isset($ed->sg[3]) && $r_fk['id']==$ed->sg[3] && !isset($ed->sg[4])){
$fk.="FOREIGN KEY (".$ed->post('from').") REFERENCES ".$ed->post('table')." (".$ed->post('to').")".($ed->post('drule','!e')?" ON DELETE ".$ed->post('drule'):'').($ed->post('urule','!e')?" ON UPDATE ".$ed->post('urule'):'').",";
} elseif((isset($ed->sg[3]) && $r_fk['id']!=$ed->sg[3]) || !isset($ed->sg[4])){
$fk.="FOREIGN KEY (".$r_fk['from'].") REFERENCES ".$r_fk['table']." (".$r_fk['to'].")".(empty($r_fk['on_delete'])?"":" ON DELETE ".$r_fk['on_delete']).(empty($r_fk['on_update'])?"":" ON UPDATE ".$r_fk['on_update']).",";
}
}
if(!isset($ed->sg[3])){
$fk.="FOREIGN KEY (".$ed->post('from').") REFERENCES ".$ed->post('table')." (".$ed->post('to').")".($ed->post('drule','!e')?" ON DELETE ".$ed->post('drule'):'').($ed->post('urule','!e')?" ON UPDATE ".$ed->post('urule'):'').",";
}
foreach($q_t as $r_t){
$re.=$r_t[1].",";
$qr.=$r_t[1]." ".$r_t[2].($r_t[3]!=0 ? " NOT NULL":"").($r_t[4]!='' ? " DEFAULT ".$r_t[4]:"").",";
if($r_t[5]>0) $pk.=$r_t[1].",";
}
$qr.=(empty($pk) ? "":" PRIMARY KEY(".substr($pk,0,-1)."),").$fk;
$ed->con->exec("PRAGMA foreign_keys=OFF");
$ed->con->exec("BEGIN TRANSACTION");
$q_iv=$ed->con->query("SELECT name,sql FROM sqlite_master WHERE type='view'")->fetch(1);
foreach($q_iv as $r_it) $ed->con->exec("DROP view ".$r_it[0]);
$q_it=$ed->con->query("SELECT type,name,sql FROM sqlite_master WHERE tbl_name='$tb' AND type IN ('index','trigger')")->fetch(1);
foreach($q_it as $r_it) $ed->con->exec("DROP ".$r_it[0]." ".$r_it[1]);
$ed->con->exec("CREATE TABLE temp_$tb(".substr($qr,0,-1).")");
$ed->con->exec("INSERT INTO temp_$tb SELECT ".substr($re,0,-1)." FROM $tb");
$ed->con->exec("DROP TABLE $tb");
$ed->con->exec("ALTER TABLE temp_$tb RENAME TO $tb");
foreach($q_it as $r_it) $ed->con->exec($r_it[2]);
foreach($q_iv as $r_it) $ed->con->exec($r_it[1]);
$ed->con->exec("COMMIT");
$ed->con->exec("PRAGMA foreign_keys=ON");
$ed->redir("10/$db/$tb",['ok'=>"Successfully ".(isset($ed->sg[3])?"changed":"add")]);
}
echo $head.$ed->menu($db,$tb,2).$ed->form("14/$db/$tb".((isset($ed->sg[3]) && $ed->sg[3]>=0)?"/".$ed->sg[3]:''));
echo "<table><caption>TABLE FOREIGN KEY</caption><tr><th>FIELD</th><th>TARGET TABLE</th><th>TARGET FIELD</th><th>ON DELETE</th><th>ON UPDATE</th></tr>";
if(isset($ed->sg[3]) && $ed->sg[3]>=0){
foreach($q_fk as $r_fk){
if($r_fk['id']==$ed->sg[3]){
echo "<tr><td><input type='text' name='from' value='{$r_fk['from']}' /></td><td><input type='text' name='table' value='{$r_fk['table']}' /></td><td><input type='text' name='to' value='{$r_fk['to']}' /></td><td><select name='drule'>";
foreach($fkty as $fkt) echo "<option value='$fkt'".($r_fk['on_delete']==$fkt?" selected":"").">$fkt</option>";
echo "</select></td><td><select name='urule'>";
foreach($fkty as $fkt) echo "<option value='$fkt'".($r_fk['on_update']==$fkt?" selected":"").">$fkt</option>";
echo "</select></td></tr>";
}
}
} else {
echo "<tr><td><input type='text' name='from' /></td><td><input type='text' name='table' /></td><td><input type='text' name='to' /></td><td><select name='drule'>";
foreach($fkty as $fkt) echo "<option value='$fkt'>$fkt</option>";
echo "</select></td><td><select name='urule'>";
foreach($fkty as $fkt) echo "<option value='$fkt'>$fkt</option>";
echo "</select></td></tr>";
}
echo "<tr><td colspan='5'><button type='submit'>Change</button></td></tr></table></form>";
break;
case "20"://table browse
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$where=(!empty($_SESSION["_litesearch_{$db}_{$tb}"])?" ".$_SESSION["_litesearch_{$db}_{$tb}"] : "");
$count=$ed->con->query("SELECT COUNT(*) FROM ".$tb.$where,true);
$all=$count->fetch();
$totalpg=ceil($all/$step);
if(empty($ed->sg[3])){
$pg=1;
} else {
$pg=$ed->sg[3];
$ed->check([4],['pg'=>$pg,'total'=>$totalpg,'redir'=>"20/$db/$tb"]);
}
$offset=($pg - 1) * $step;
$q_rex=$ed->con->query("SELECT * FROM {$tb}{$where} LIMIT $offset,$step");
$cols=$q_rex->num_col();
$r_col=$q_rex->fetch(2);
$q_vws=$ed->con->query("SELECT type FROM sqlite_master WHERE name='$tb'",true)->fetch();
echo $head.$ed->menu($db,($q_vws=='view'?'':$tb),1,($q_vws=='view'?['view',$tb]:''))."<table><tr>";
if($q_vws !='view') echo "<th>Actions</th>";
$q_ti=$ed->con->query("PRAGMA table_info($tb)")->fetch(1);
$rinf=[];
foreach($q_ti as $r_ti){
if($r_col && array_key_exists($r_ti[1],$r_col[0])){
$rinf[$r_ti[1]]=$r_ti[2];
echo "<th>".$r_ti[1]."</th>";
} elseif(empty($r_col)) echo "<th>".$r_ti[1]."</th>";
}
echo "</tr>";
if($r_col){
$key=array_keys($r_col[0]);
foreach($r_col as $row){
$bg=($bg==1)?2:1;
echo "<tr class='r c$bg'>";
if($q_vws !='view'){
$nu=$key[0]."/".($row[$key[0]]=="" && !is_numeric($row[$key[0]])?"isnull":base64_encode($row[$key[0]])).(!empty($key[1]) && !empty($rinf[$key[1]]) && (stristr($rinf[$key[1]],"int") || stristr($rinf[$key[1]],"varchar")) && stristr($rinf[$key[1]],"blob")==false && !empty($row[$key[1]]) ? "/".$key[1]."/".base64_encode($row[$key[1]]):"");
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>";
}
$j=0;
while($j<$cols){
$val=($row[$key[$j]]==''?'':htmlentities($row[$key[$j]]));
echo "<td>";
if(stristr($rinf[$key[$j]],"blob")==true ){
$le=strlen($row[$key[$j]]);
echo "[blob] ";
echo ($le>4)?"<a href='".$ed->path."33/$db/$tb/$nu/".$key[$j]."'>".number_format(($le/1024),2)." KB</a>":number_format(($le/1024),2)." KB";
} elseif(strlen($val) > 70){
echo substr($val,0,70)."[...]";
} else echo $val;
echo "</td>";
++$j;
}
echo "</tr>";
}
}
echo "</table>".$ed->pg_number($pg,$totalpg);
break;
case "21"://insert row
$ed->check([1,2]);
$db=$ed->sg[1];
$tb=$ed->sg[2];
$q_pra=$ed->con->query("PRAGMA table_info($tb)")->fetch(2);
if($ed->post('save','i') || $ed->post('save2','i')){
$qr2="INSERT INTO $tb (";
$qr4="VALUES(";
$i=0;
foreach($q_pra as $r_ra){
if(strtolower($r_ra['type'])=="boolean"){
$qr2.=$r_ra['name'].",";
$qr4.="'".($ed->post('r'.$i,0) ? 1:'')."',";
} elseif(strtolower($r_ra['type'])=="blob"){
if(!empty($_FILES['r'.$i]['tmp_name'])){
$qr2.=$r_ra['name'].",";
$qr4.="'".base64_encode(file_get_contents($_FILES['r'.$i]['tmp_name']))."',";
}
} else {
$qr2.=$r_ra['name'].",";
if($r_ra['pk']==1 && stripos($r_ra['type'],'INTEGER') && $ed->post('r'.$i,'e')){
$max=$ed->con->query("SELECT max(".$q_pra[0]['name'].") FROM ".$tb,true)->fetch();
$qr4.=($max+1).",";
} else {
$qr4.=(($ed->post('r'.$i,'e') && $r_ra['notnull']==0)? "NULL":"'".str_replace("'","''",$ed->post('r'.$i))."'").",";
}
}
++$i;
}
$qr2=substr($qr2,0,-1).") ";