/
index.php
894 lines (836 loc) · 24.3 KB
/
index.php
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
<?php
require_once "config.php";
define("QUERY_RETURN_ROWS_AFFECTED" ,1);
define("QUERY_RETURN_DATA_ARRAY" ,2);
define("QUERY_RETURN_INSERT_ID" ,3);
date_default_timezone_set(TIMEZONE);
$shrtnr = new shrtnr();
if ($shrtnr->getParameter("include") !== false) {
$shrtnr->includeLink();
} elseif ($shrtnr->getParameter("remove") !== false) {
$shrtnr->removeLink();
} elseif ($shrtnr->getParameter("install") !== false) {
$shrtnr->installShrtnr();
} elseif ($shrtnr->getParameter("listLinks") !== false) {
$shrtnr->listLinks();
} elseif ($shrtnr->getParameter("listLinksHTML") !== false) {
$shrtnr->listLinksHTML();
} else {
$shrtnr->routeLink();
}
class shrtnr {
public function routeLink() {
$link = $this->parseREST();
if (strlen($link) == 0) $this->redirectToErrorPage();
if (!$this->validateLink($link)) $this->redirectToErrorPage();
$lnk = $this->getURL($link);
if ($lnk === false) $this->redirectToErrorPage();
if ($lnk["lnkSingleUse"] === 1) {
$this->removeLink($lnk["lnkID"]);
} else {
$this->updateCounter($link);
}
header("Location: ".$lnk["lnkURL"], TRUE, (CACHE_REDIRECT ? 301 : 307));
}
private function generateRandomID() {
$rnd = abs(rand(0, MAX_DB_ID));
return $rnd;
}
public function includeLink() {
if (INSERTION_PWD_REQUIRED && !$this->checkPassword()) $this->error("Invalid password");
$url = $this->getParameter('url');
if ($url === false) $this->error("Invalid call - missing URL parameter");
if (!filter_var($url, FILTER_VALIDATE_URL)) $this->error("Invalid URL");
$singleUse = $this->getParameter('singleUse') === false ? 0 : 1;
$customURL = $this->getParameter('customURL');
if ($customURL && substr($customURL, 0, 1) == LINK_PADDING)
$this->error("Custom links cannot begin with '".LINK_PADDING."'");
if ($this->isCustomURLAlreadyInDB($customURL)) $this->error("Custom URL '$customURL' is already being used");
$fields = array("lnkURL", "lnkTimestamp", "lnkIP", "lnkClicks", "lnkSingleUse");
$values = array($url, date("YmdHis"), $_SERVER['REMOTE_ADDR'], 0, $singleUse);
if ($customURL !== false) {
$fields[] = "lnkCustomURL";
$values[] = $customURL;
}
if (!SEQUENTIAL_LINKS) {
$fields[] = "lnkID";
$lnkID = null;
while ($this->isIDAlreadyInDB($lnkID)) {
$lnkID = $this->generateRandomID();
}
$values[] = $lnkID;
}
$result = $this->insertLinkIntoDatabase($fields, $values);
if ($result === false) error("Error inserting link into database");
$this->success($customURL !== false ? $customURL : $this->intToBase($result));
}
public function removeLink($lnkID=null) {
if (!CAN_DELETE) $this->error("Links cannot be removed");
if (DELETION_PWD_REQUIRED && !$this->checkPassword()) $this->error("Invalid password");
$link = ($lnkID == null ? $this->getParameter("link") : $lnkID);
if ($link === false) $this->error("Invalid call - missing shortened link to remove");
$result = $this->removeLinkFromDatabase($link, $lnkID==null);
if ($lnkID != null) return true;
if ($result) {
$this->success(null, true);
} else {
$this->error("Error removing link");
}
}
public function installShrtnr() {
$script = "
CREATE TABLE `links` (
`lnkID` int(11) NOT NULL AUTO_INCREMENT,
`lnkURL` varchar(50000) NOT NULL,
`lnkTimestamp` datetime NOT NULL,
`lnkIP` varchar(15) NOT NULL,
`lnkClicks` int(11) NOT NULL,
`lnkCustomURL` varchar(10) DEFAULT NULL,
`lnkSingleUse` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`lnkID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
if (dbconnection::execSQLUnprepared($script) === true) {
$this->success("", false, "Database was prepared successfully! You can start using shrtnr!");
} else {
$this->error("Error creating shrtnr tables... maybe do it by hand?");
}
exit;
}
public function listLinks() {
$this->success(null, false, json_encode($this->listLinksRaw()));
}
public function listLinksHTML() {
$data = $this->listLinksRaw();
$headers = array("Link", "URL", "Creation date", "Creator IP", "Clicks", "Custom URL", "Single use");
if (file_exists("shrtnr.css")) echo "<link rel='stylesheet' type='text/css' href='shrtnr.css'>";
echo $this->printToTable($data, $headers);
}
private function updateCounter($link) {
$query = new updatequery();
$query->setTable("links");
$query->addNewValueNoPrepare("lnkClicks", "lnkClicks + 1");
if ($this->isCustomURL($link)) {
$query->addWhere("lnkCustomURL", "=", $link);
} else {
$query->addWhere("lnkID", "=", $this->baseToInt($link));
}
$query->runQuery();
}
private function getURL($link) {
$customURL = ($this->isCustomURL($link));
$query = new selectquery();
$query->setTable("links");
$query->addField("lnkID", "lnkURL", "lnkSingleUse");
if ($customURL) {
$query->addWhere("lnkCustomURL", "=", $link);
} else {
$id = $this->baseToInt($link);
$query->addWhere("lnkID", "=", $id);
}
$result = $query->getArrayResult();
if (count($result) == 0) return false;
return $result[0];
}
private function insertLinkIntoDatabase($fields, $values) {
$query = new insertquery();
$query->setTable("links");
$query->setFields($fields);
$query->setValues($values);
$result = $query->runQuery();
if ($result === false) $this->error("Error inserting link into database");
return $result;
}
private function removeLinkFromDatabase($link, $chkCustomURL=true) {
$customURL = ($chkCustomURL ? $this->isCustomURL($link) : false);
$query = new deletequery();
$query->setTable("links");
if ($customURL) {
$query->addWhere("lnkCustomURL", "=", $link);
} else {
if (substr($link, 0 ,1) == LINK_PADDING) {
$id = $this->BaseToInt($link);
} else {
$id = $link;
}
$query->addWhere("lnkID", "=", $id);
}
$result = $query->runQuery();
return $result;
}
private function listLinksRaw() {
if (LIST_PWD_REQUIRED) {
if (!$this->checkDateOffset()) $this->error("Invalid timestamp - now it's ".date("YmdHis"));
if (!$this->checkPassword()) $this->error("Invalid password");
}
$query = new selectquery();
$query->setTable("links");
$query->addOrderBy("lnkTimestamp");
$result = $query->getArrayResult();
$output = [];
foreach($result as $row) {
$row['lnkID'] = $this->intToBase($row['lnkID']);
$output[] = $row;
}
return $output;
}
private function intToBase($num) {
$radix = strlen(SYMBOLS);
$pos = 0;
$symbols= SYMBOLS;
$out = "";
if ($num==0) {
$out[$pos] = $symbols[0];
} else {
while ($num > 0) {
$r = bcmod($num, $radix);
$out .= $symbols[$r];
$num = ($num - $r) / $radix;
$pos--;
}
}
$out = str_pad($out, URL_PADDING - 1, "0", STR_PAD_LEFT);
$out = LINK_PADDING.$out;
return $out;
}
private function baseToInt($base) {
$base = ltrim($base, LINK_PADDING);
$base = ltrim($base, "0");
$radix = strlen(SYMBOLS);
$arr = str_split($base,1);
$i = 0;
$out = 0;
foreach($arr as $char) {
$pos = strpos(SYMBOLS, $char);
$partialSum = $pos * pow($radix, $i);
$out += $partialSum;
$i++;
}
return $out;
}
private function parseREST() {
$a = str_replace(HTTPD_FILES_PATH, "", $_SERVER['REQUEST_URI']);
$b = explode("/", $a);
return $b[0];
}
private function isCustomURL($link) {
return substr($link, 0, 1) != LINK_PADDING;
}
private function validateLink($link) {
if ($this->isCustomURL($link)) return true;
if (strlen($link) != URL_PADDING) return false;
$link = ltrim($link, LINK_PADDING);
foreach(str_split($link) as $char) {
if (strpos(SYMBOLS, $char) === false) return false;
}
return true;
}
public function getParameter($param) {
if (USE_POST) {
if (!isset($_POST[$param])) return false;
return $_POST[$param];
} else {
if (!isset($_GET[$param])) return false;
return $_GET[$param];
}
}
private function isAlreadyInDB($checkForCustom, $data) {
$query = new selectquery();
$query->setTable("links");
$query->addField("lnkID");
$query->addWhere($checkForCustom ? "lnkCustomURL" : "lnkID", "=", $data);
$result = $query->getArrayResult(true);
return count($result) > 0;
}
private function isCustomURLAlreadyInDB($customURL) {
if (strlen($customURL) == 0) return false;
return $this->isAlreadyInDB(true, $customURL);
}
private function isIDAlreadyInDB($lnkID) {
if ($lnkID == null) return true;
return $this->isAlreadyInDB(false, $lnkID);
}
private function checkDateOffset() {
$time = $this->getParameter("timestamp");
if ($time === false) $this->error("Invalid call - missing timestamp");
$timestamp = DateTime::createFromFormat("YmdHis", $time);
$offsetMinus = new DateTime();
$offsetMinus->modify("-5 minutes");
$offsetPlus = new DateTime();
$offsetPlus->modify("+5 minutes");
return ($timestamp > $offsetMinus && $timestamp < $offsetPlus);
}
private function printToTable($arrData, $arrHeaders) {
$output = "<table><thead><tr>";
foreach($arrHeaders as $header) {
$output .= "<th>$header</th>";
}
$output .= "</tr></thead><tbody>";
foreach($arrData as $row) {
$output .= "<tr>";
foreach($row as $cell) {
$output .= "<td>$cell</td>";
}
$output .= "</tr>";
}
$output .= "</tbody></table>";
return $output;
}
private function redirectToErrorPage() {
header("Location: ".ERROR_PAGE, TRUE, 301);
exit;
}
private function error($msg) {
$output = [
'status' => 0,
'error' => $msg
];
echo json_encode($output);
exit;
}
private function success($link=null, $remove=false, $customMsg=null) {
$output = ['status' => 1];
if ($link != null) $output['shrtnrURL'] = $link;
if ($customMsg !== null) $output['message'] = $customMsg;
echo json_encode($output);
exit;
}
private function checkPassword() {
$pwd = $this->getParameter("pwd");
if ($pwd === false) $this->error("Password needed to perform the action");
$hash = md5(PWD_HASH.$this->getParameter("url").$this->getParameter("link").$this->getParameter("customURL").$this->getParameter("timestamp"));
return ($hash == $pwd);
}
}
class dbconnection {
private static $instance = null;
public static $lasterror = "";
public static function getInstance() {
if (!(self::$instance instanceof MySQLi)) {
self::createInstance();
}
return self::$instance;
}
private static function createInstance() {
require_once "config.php";
self::$instance = new mysqli(DB_HOST, DB_USER, DB_PWD, DB_DB);
self::$instance->set_charset("UTF8");
}
public static function getResults($query, $forceUTF8Conversion = false, $args = []) {
$output = [];
if ($args !== []) {
$types = self::getBindTypes($args);
array_unshift($args, $types);
}
$returnData = substr($query, 0, 6);
switch ($returnData) {
case "SELECT":
$returnData = QUERY_RETURN_DATA_ARRAY;
break;
case "UPDATE":
case "DELETE":
$returnData = QUERY_RETURN_ROWS_AFFECTED;
break;
case "INSERT":
$returnData = QUERY_RETURN_INSERT_ID;
break;
}
$result = self::execSQL($query, $args, $returnData);
if ($returnData == QUERY_RETURN_DATA_ARRAY) {
if (!is_array($result)) {
$result = [];
}
foreach($result as $row) {
$output[] = $row;
}
} else {
$output = $result;
}
return $output;
}
public static function sqlEscape($data) {
if (!isset($data) || empty($data)) return '';
if (is_numeric($data)) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/'
); // 14-31
foreach ($non_displayables as $regex)
$data = preg_replace($regex, '', $data);
$data = str_replace("'", "''", $data);
return $data;
}
public static function getBindTypes($array) {
$types = '';
foreach ($array as $par) {
if (is_int($par)) {
$types .= 'i';
} elseif (is_float($par)) {
$types .= 'd';
} elseif (is_string($par)) {
$types .= 's';
} else {
$types .= 'b';
}
}
return $types;
}
public static function execSQLUnprepared($sql) {
$mysqli = self::getInstance();
return $mysqli->query($sql);
}
private static function execSQL($sql, $params, $returnMode) {
$mysqli = self::getInstance();
if (!$stmt = $mysqli->prepare($sql)) return false;
if ($params !== []) {
call_user_func_array(array(
$stmt,
'bind_param'
), self::refValues($params));
}
$stmt->execute();
switch ($returnMode) {
case QUERY_RETURN_ROWS_AFFECTED:
$result = $mysqli->affected_rows;
break;
case QUERY_RETURN_INSERT_ID:
$result = $stmt->insert_id;
break;
case QUERY_RETURN_DATA_ARRAY:
$meta = $stmt->result_metadata();
$parameters = [];
$row = [];
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array(
$stmt,
'bind_result'
), self::refValues($parameters));
$results = [];
while ($stmt->fetch()) {
$x = [];
foreach ($row as $key=>$val) {
$x[$key] = $val;
}
$results[] = $x;
}
$result = $results;
break;
default:
$result = [];
break;
}
$error = $mysqli->error;
if ($error != "") {
self::$lasterror = $error;
}
$stmt->close();
self::closeConnection();
return ($error != "" ? false : $result);
}
private static function closeConnection() {
self::$instance->close();
self::$instance = null;
}
private static function refValues($arr) {
if (strnatcmp(phpversion(), '5.3') >= 0) {
$refs = [];
foreach (array_keys($arr) as $key)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
}
class selectquery{
private $where;
private $orderBy;
private $table;
private $fields;
private $groups;
private $joins = [];
private $lowerlimit = null;
private $limitQtd = null;
private $args = [];
private $stmt;
private $formatter = [];
private $runFunc = [];
public function addWhere($field, $type, $condition, $level=null, $fixedValue=true) {
if ($level == null) {
$newLevel = rand();
} else {
$newLevel = $level;
}
$this->where[$newLevel][] = array("field"=>$field,"type"=>$type,"condition"=>$condition,"fixedValue"=>$fixedValue);
}
public function addOrderBy($field,$rule="ASC"){
$this->orderBy[] = array($field,$rule);
}
public function addField($fields) {
if (is_array($fields)) {
foreach ($fields as $field) {
$this->fields[] = $field;
}
} else {
foreach(func_get_args() as $field) {
$this->fields[] = $field;
}
}
}
public function addJoin($type, $outertable, $srcfield, $dstfield=null){
$dstfield = ($dstfield == null ? $srcfield : $dstfield);
$this->joins[] = "$type $outertable ON $outertable.$dstfield = $this->table.$srcfield";
}
public function addJoinAdvanced($type, $outertable, $outertablealias, $arrConditions) {
$conditions = "";
if (is_array($arrConditions)) {
foreach($arrConditions as $cond) {
$conditions .= "$cond AND ";
}
$conditions = substr($conditions,0,-4);
} else {
$conditions = $arrConditions;
}
$this->joins[] = "$type $outertable $outertablealias ON $conditions";
}
public function addGroupBy($field) {
$this->groups[] = $field;
}
public function setTable($table) {
$this->table = $table;
}
public function addFormatter($field, $type) {
$this->formatter[$field] = $type;
}
public function addFunction($field, $strFunction, $arrArgs) {
$this->runFunc[$field] = array("function"=>$strFunction, "args"=>$arrArgs);
}
private function finalJoins() {
$joinClause = "";
foreach ($this->joins as $join) {
$joinClause .= $join." ";
}
return $joinClause;
}
private function finalGroups() {
if (!is_array($this->groups) || count($this->groups) == 0) return null;
$groupClause = "GROUP BY ";
foreach ($this->groups as $group) {
$groupClause .= $group.", ";
}
return substr($groupClause,0,-2);
}
private function finalWhere() {
$whereClause = "";
$this->args = [];
if (count($this->where) != 0) {
$whereClause = " WHERE ";
foreach($this->where as $level) {
$whereClause .= "(";
foreach($level as $clause) {
if ($clause['fixedValue']) {
$whereClause .= $clause['field']." ".$clause['type']." ? OR ";
$this->args[] = $clause['condition'];
} else {
$whereClause .= $clause['field']." ".$clause['type']." ".$clause['condition']." OR ";
}
}
$whereClause = substr($whereClause,0,-4).") AND ";
}
$whereClause = substr($whereClause,0,-4);
}
return $whereClause;
}
private function finalOrder() {
$orderClause = "";
if (is_array($this->orderBy) && count($this->orderBy) != 0) {
$orderClause = " ORDER BY ";
foreach($this->orderBy as $clause) {
$orderClause .= "$clause[0] $clause[1],";
}
$orderClause = substr($orderClause,0,-1);
}
return $orderClause;
}
private function finalFields() {
$fields = "";
if (count($this->fields) != 0) {
foreach($this->fields as $field) {
$fields .= "$field,";
}
$fields = substr($fields,0,-1);
} else {
$fields = "*";
}
return $fields;
}
private function finalQry() {
if ($this->lowerlimit !== null && $this->limitQtd !== null) {
$init = $this->lowerlimit;
$offset = "LIMIT $init,$this->limitQtd";
} elseif ($this->lowerlimit != null) {
$offset = "LIMIT $this->lowerlimit;";
} else {
$offset = null;
}
$fields = $this->finalFields();
$table = $this->table;
$joins = $this->finalJoins();
$where = $this->finalWhere();
$order = $this->finalOrder();
$group = $this->finalGroups();
return "SELECT $fields FROM $table $joins $where $group $order $offset";
}
private function getResultParamArray() {
$meta = $this->stmt->result_metadata();
$fields = [];
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
return $fields;
}
public function getObjResult() {
$query = $this->finalQry();
return dbconnection::getResults($query, false, $this->args);
}
private function recreateSingleColumn($array) {
$output = [];
foreach($array as $row) {
$keys = array_keys($row);
$output[] = $row[$keys[0]];
}
return $output;
}
private function getBindTypes() {
$par = [];
foreach($this->where as $level) {
foreach($level as $param) {
$par[] = $param['condition'];
}
}
return dbconnection::getBindTypes($par);
}
private function formatOutput($array) {
$a = [];
$b = [];
foreach($array as $row) {
foreach($row as $key=>$val) {
$a[$key] = $val;
}
$b[] = $a;
}
return $b;
}
private function runFunctions($array) {
$a = [];
$b = [];
foreach($array as $row) {
foreach($row as $key=>$val) {
if(isset($this->runFunc[$key])) {
$args = [];
$f = $this->runFunc[$key];
foreach($f["args"] as $arg) {
$args[] = ($arg === "%FIELD%" ? $val : $arg);
}
$a[$key] = call_user_func_array($f["function"], $args);
} else {
$a[$key] = $val;
}
}
$b[] = $a;
}
return $b;
}
public function getArrayResult($singleField=false) {
$array = $this->getObjResult();
if ($this->runFunc!= []) $array = $this->runFunctions($array);
if ($this->formatter!= []) $array = $this->formatOutput($array);
if ($singleField) return $this->recreateSingleColumn($array);
return $array;
}
public function setLimit($lower, $limit=null) {
$this->lowerlimit = $lower;
$this->limitQtd = $limit;
}
public function getQuery() {
return $this->finalQry();
}
public function getFields() {
return $this->fields;
}
}
class insertquery {
private $values = [];
private $fields = [];
private $table;
private $fromValues = true;
private $stmt;
public function setFromValues($boolean) {
$this->fromValues = $boolean;
}
public function setValues($values) {
if (is_array($values)) {
$this->values = $values;
} else {
$this->values = func_get_args();
}
}
public function setFields($fields) {
if (is_array($fields)) {
$this->fields = $fields;
} else {
$this->fields = func_get_args();
}
}
public function setTable($table) {
$this->table = $table;
}
private function finalValues() {
if (count($this->values) == 0) return;
$val = "(";
for($i=0; $i<count($this->values); $i++) {
$val .= "?,";
}
$val = substr($val,0,-1).")";
return $val;
}
private function finalFields() {
if (count($this->fields) == 0) return;
$fie = "(";
foreach ($this->fields as $field) {
$fie .= "$field,";
}
$fie = substr($fie,0,-1).")";
return $fie;
}
private function finalQry() {
$fields = $this->finalFields();
$values = $this->finalValues();
$valuesFinal = ($this->fromValues ? "VALUES$values" : $values);
$query = "INSERT INTO $this->table$fields $valuesFinal";
return $query;
}
public function runQuery($getInsertedID = true) {
$query = $this->finalQry();
return dbconnection::getResults($query, false, $this->values);
}
public function getQuery() {
return $this->finalQry();
}
}
class deletequery {
private $table;
private $where;
private $stmt;
private $args = [];
public function setTable($table) {
$this->table = $table;
}
public function addWhere($field, $condition, $value) {
$this->where[] = array("field"=>$field, "condition"=>$condition);
$this->args[] = $value;
}
private function finalWhere() {
$whereClause = "";
if (count($this->where) != 0) {
$whereClause = "WHERE ";
foreach($this->where as $clause) {
$whereClause .= $clause['field'].$clause['condition']."? AND ";
}
$whereClause = substr($whereClause,0,-4);
}
return $whereClause;
}
public function getQuery() {
$where = $this->finalWhere();
return "DELETE FROM $this->table $where";
}
public function runQuery($returnAffectedRows=false) {
$query = $this->getQuery();
return dbconnection::getResults($query, false, $this->args);
}
public static function getInstance() {
return new deletequery();
}
}
class updatequery {
private $table;
private $where = [];
private $values = [];
private $valuesNoPrepare = [];
private $args = [];
private $stmt;
public function setTable($table) {
$this->table = $table;
}
public function addWhere($field, $condition, $value) {
$this->where[] = array("field"=>$field, "condition"=>$condition, "value"=>$value);
}
public function clearWhere() {
$this->where = [];
}
public function clearValues() {
$this->values = [];
}
public function addNewValueNoPrepare($field, $value) {
$this->valuesNoPrepare[] = array("field"=>$field, "value"=>$value);
}
public function addNewValue($field, $value) {
$this->values[] = array("field"=>$field, "value"=>$value);
}
private function getFinalFields() {
$output = "";
foreach($this->values as $value) {
$output .= $value['field']."=?, ";
$this->args[] = $value['value'];
}
foreach($this->valuesNoPrepare as $value) {
$output .= $value['field']."=".$value['value'].", ";
}
return substr($output,0,-2);
}
private function getFinalWhere() {
$output = "WHERE ";
if (count($this->where) == 0) return null;
foreach($this->where as $clause) {
$output .= $clause['field'].$clause['condition']."? AND ";
$this->args[] = $clause['value'];
}
return substr($output,0,-5);
}
private function getFinalQuery() {
$this->args = [];
$table = $this->table;
$values = $this->getFinalFields();
$where = $this->getFinalWhere();
return "UPDATE $table SET $values $where";
}
public function getQuery() {
return $this->getFinalQuery();
}
public function runQuery() {
$query = $this->getQuery();
return dbconnection::getResults($query, false, $this->args);
}
private function getBindTypes() {
$types = '';
foreach($this->args as $par) {
if(is_int($par)) {
$types .= 'i';
} elseif (is_float($par)) {
$types .= 'd';
} elseif (is_string($par)) {
$types .= 's';
} else {
$types .= 'b';
}
}
return $types;
}
}