-
Notifications
You must be signed in to change notification settings - Fork 0
/
framework.php
3595 lines (3214 loc) · 124 KB
/
framework.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
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
/**
* framework.php
* This file is part of the FreeSentral Project http://freesentral.com
*
* FreeSentral - is a Web Graphical User Interface for easy configuration of the Yate PBX software
* Copyright (C) 2008-2014 Null Team
*
* This software is distributed under multiple licenses;
* see the COPYING file in the main directory for licensing
* information for this specific distribution.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
?>
<?php
/**
* the base classes for the database framework
*/
if (is_file("defaults.php"))
require_once("defaults.php");
if (is_file("config.php"))
require_once("config.php");
if (!isset($enforce_basic_constrains))
$enforce_basic_constrains = false;
if (!isset($critical_col_diff))
$critical_col_diff = false;
if (!isset($check_col_diff))
$check_col_diff = true;
require_once("debug.php");
// class for defining a variable that will be mapped to a column in a sql table
// name of variable must not be a numer or a numeric string
class Variable
{
public $_type;
public $_value;
public $_key;
public $_owner;
public $_critical;
public $_matchkey;
public $_join_type;
public $_required;
/**
* Constructor for Variable class. Name of variable must not be a string
* @param $type Text representing the type of object: serial, text, int2, bool, interval etc
* @param $def_value Text or number representing the default value. Exception: if $def_value is set to !null then $required parameter is considered true. Exception was added so that we don't set a list false and null default params and to maintain compatibility
* @param $foreign_key Name of the table this column is a foreign key to. Unless $match_key is defined, this is a foreign
* key to a column with the same name in the $foreign_key table
* @param $critical Bool value.
* true for ON DELETE CASCADE, if referenced row is deleted then this one will also be deleted
* false for ON DELETE SET NULL, if referenced is deleted then this column will be set to null
* @param $match_key Referenced variable name (Text representing the name of the column from the $foreign_key table to which this variable(column) will
* be a foreign key to).If not given the name is the same as this variable's
* @param $join_type Usually set when extending objects. Possible values: LEFT, RIGHT, FULL, INNER. Default is LEFT is queries.
* @param $required Bool value specifing whether this field can't be null in the database. Default value is false
*/
function __construct($type, $def_value = NULL, $foreign_key = NULL, $critical = false, $match_key = NULL, $join_type = NULL, $required = false)
{
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
$this->_type = $type;
$this->_value = (strtolower($def_value) != "!null") ? $def_value : NULL;
$this->_key = $foreign_key;
$this->_critical = $critical;
$this->_owner = null;
$this->_matchkey = $match_key;
$this->_join_type = $join_type;
$this->_required = ($required === true || strtolower($def_value) == "!null") ? true : false;
}
public static function varCopy($var)
{
$new_var = new Variable($var->_type, $var->_value, $var->_key, $var->_critical, $var->_matchkey, $var->_join_type, $var->_required);
return $new_var;
}
/**
* Returns the correctly formated value of a Variable object. Value will be used inside a query. Formating is done
* according to the type of the object
* @param $value Instance of Variable class
* @return Text or number to be used inside a query
*/
public function escape($value)
{
global $db_type;
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
if (!strlen($value) && ($value!==false && $this->_type!="bool"))
return 'NULL';
$value = trim($value);
if ($this->_type == "bool") {
switch ($db_type) {
case "mysql":
if ($value === true || $value == 't' || $value == "1")
return "1";
else
return "0";
break;
case "postgresql":
if ($value === true || $value == 't' || $value == "1")
return "'t'";
else
return "'f'";
break;
}
} elseif ( (substr($this->_type,0,3) == "int" && $this->_type!="interval") || substr($this->_type,-3) == "int" || substr($this->_type,0,5) == "float" || substr($this->_type,0,7)=="tinyint" || $this->_type == "serial" || $this->_type == "bigserial" || substr($this->_type,0,6) == "bigint") {
$value = str_replace(',','',$value);
return 1*$value;
} elseif (($this->_type == "timestamp" || $this->_type == "date") && $value == "now()")
return $value;
elseif ($this->_type == "bit(1)") {
if ($value == 1 || $value == "1" || $value == "bit(1)")
return 1;
else
return 0;
} elseif (substr($this->_type,0,4) == "bit(")
return 1*$value;
return "'" . Database::escape($value) . "'";
}
public function isRequired()
{
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
return $this->_required;
}
}
// class that does the operations with the database
class Database
{
protected static $_connection = true;
protected static $_object_model = "Model";
public static $_in_transaction = false;
// this library uses mostly postgresql types
// if type is not in the below list make sure that given type of a variables mathches real type in database
// Ex: in mysl if you use "bool" the column type will be tinyint(1) or int is int(11)
private static $_translate_sql_types = array(
"mysql" => array(
"int2" => "int(4)",
"int4" => "int(11)",
"int8" => "bigint(20)",
"float4" => "float",
"float8" => "double precision",
"bool" => "tinyint(1)",
"int" => "int(11)",
// mysql doesn't know bigserial
// postgresql has both serial and bigserial. check documentation for type limits
"serial" => "bigint(20) unsigned NOT NULL auto_increment",
"bigserial" => "bigint(20) unsigned NOT NULL auto_increment",
"interval" => "time"
)
);
/**
* Disconnect current database connection
*/
public static function disconnect()
{
global $db_type;
Debug::func_start(__METHOD__,func_get_args(),"framework");
if (!self::$_connection || self::$_connection===true)
return;
switch ($db_type) {
case "mysql":
mysqli_close(self::$_connection);
break;
case "postgresql":
pg_close(self::$_connection);
break;
}
self::$_connection = NULL;
Model::reset_modified();
}
/**
* Make database connection
* @param $connection_index Numeric. Mark connection index in case backup connection is available
* Default value is ''. Valid values '',2,3 .. (1 is excluded)
* @return The connection to the database. If the connection is not possible, backup connection is tried if set, else return NULL if $exit_gracefully is set, otherwise page dies
*/
public static function connect($connection_index="")
{
global $db_type, $cb_when_backup, $exit_gracefully;
Debug::func_start(__METHOD__,func_get_args(),"framework");
if (self::$_connection && self::$_connection!==true)
return self::$_connection;
if ($connection_index!='' && (!is_int($connection_index) || $connection_index<2 )) {
Debug::trigger_report('critical', "Invalid connection index in Database::connect(): $connection_index");
return;
}
$db_data = array("db_host","db_user","db_database","db_passwd","db_type");
for ($i=0; $i<count($db_data); $i++) {
$db_setting = $db_data[$i].$connection_index;
global ${$db_setting};
if (!isset(${$db_setting}) && isset(${$db_data[$i]}) && $db_data[$i]!="db_host")
${$db_setting} = ${$db_data[$i]};
if ($db_data[$i]=="db_type" && $connection_index!="")
$db_type = ${$db_setting};
if (!isset(${$db_setting})) {
Debug::Output("config", _("Missing setting")." '$".$db_setting."' ");
return;
}
}
$next_index = ($connection_index=="") ? 2 : $connection_index+1;
switch ($db_type) {
case "mysql":
if (!function_exists("mysqli_connect")) {
Debug::Output("config", _("You don't have mysqli package for php installed."));
die("You don't have mysqli package for php installed.");
}
if (self::$_connection === true || !self::$_connection)
self::$_connection = mysqli_connect(${"db_host$connection_index"}, ${"db_user$connection_index"}, ${"db_passwd$connection_index"}, ${"db_database$connection_index"});
break;
case "postgresql":
if (!function_exists("pg_connect")) {
Debug::Output("config", _("You don't have php-pgsql package installed."));
die("You don't have php-pgsql package installed.");
}
if (self::$_connection === true || !self::$_connection)
self::$_connection = pg_connect("host='".${"db_host$connection_index"}."' dbname='".${"db_database$connection_index"}."' user='".${"db_user$connection_index"}."' password='".${"db_passwd$connection_index"}."'");
break;
default:
Debug::Output("config", _("Unsupported or unspecified database type")." db_type='$db_type'");
die("Unsupported or unspecified database type: db_type='$db_type'");
break;
}
if (!self::$_connection) {
Debug::Output("config", _("Could not connect to the database")." $connection_index");
self::$_connection = self::connect($next_index);
if (!self::$_connection) {
if (!isset($exit_gracefully) || !$exit_gracefully)
die("Could not connect to the database");
else
return;
} elseif (isset($cb_when_backup) && is_callable($cb_when_backup))
call_user_func_array($cb_when_backup, array($next_index));
}
return self::$_connection;
}
/**
* Disconnect existing connection and connect to another database
* @param $connection_index Mark connection index in case backup connection is available
* Default value is ''. Valid values '',2,3 .. (1 is excluded)
* @return The connection to new database. If the connection is not possible, backup connection is tried if set, else return NULL if $exit_gracefully is set, otherwise page dies
*/
public static function switchDatabase($connection_index='')
{
global $db_identifier;
Database::disconnect();
if (!isset($_SESSION["ansql_default_db_identifier"]) && $db_identifier) {
$_SESSION["ansql_default_db_identifier"] = $db_identifier;
}
if ($connection_index != '') {
global ${"db_identifier$connection_index"};
$db_identifier = ${"db_identifier$connection_index"};
if (!$db_identifier) {
Debug::trigger_report ("critical", "No indentifier for connection_index=$connection_index");
}
Debug::xdebug("switch_database", "db_identifier='$db_identifier', default_db_identifier='".$_SESSION['ansql_default_db_identifier']."'");
} else {
if (!$_SESSION["ansql_default_db_identifier"]) {
Debug::trigger_report("critical", "No default identifier in switch_database(), $connection_index=$connection_index");
}
$db_identifier = $_SESSION["ansql_default_db_identifier"];
unset($_SESSION["ansql_default_db_identifier"]);
Debug::xdebug("switch_database", "db_identifier='$db_identifier'");
}
return Database::connect($connection_index);
}
/**
* Start transaction
*/
public static function transaction()
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
if (self::$_in_transaction===true)
return;
self::$_in_transaction = true;
return Database::query("BEGIN WORK");
}
/**
* Perform roolback on the current transaction
*/
public static function rollback()
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
self::$_in_transaction = false;
return Database::query("ROLLBACK");
}
/**
* Commit current tranction
*/
public static function commit()
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
self::$_in_transaction = false;
return Database::query("COMMIT");
}
/**
* Perform query.If query fails, unless query is a ROLLBACK, it is supposed that the database structure changed. Try to
* modify database structure, then perform query again using the queryRaw() method
* @param $query Text representing the query to perform
* @param $retrieve_last_id false or Array (Name of id field, table name) -- just for INSERT queries
* @return Result received after the performing of the query
*/
public static function query($query, $retrieve_last_id=false)
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
if (!self::connect())
return false;
if(isset($_SESSION["debug_all"]))
Debug::Output("query", $query);
// if (!self::is_single_query($query))
// return false;
$res = self::db_query($query);
$res = self::query_result($query, $res, $retrieve_last_id);
if ($res!==false && $res!==NULL)
return $res;
elseif ($query != "ROLLBACK")
{
$model = self::$_object_model;
if(!call_user_func(array($model,"modified")))
{
call_user_func(array($model,"updateAll"));
$res = self::queryRaw($query, $retrieve_last_id);
if ($res===false || $res===NULL) {
$mess = $query;
$err = self::get_last_db_error();
if ($err)
$mess .= ". Error: ".$err;
Debug::Output("query failed", $mess);
}
return $res;
}
else
return $res;
}
}
public static function setObjModel($model)
{
self::$_object_model = $model;
}
/**
* Make sure queries separated by ; won't we run
* @param $query String that will be verified
* @return Bool - true if single query, false otherwise
*/
/*public static function is_single_query($query)
{
$pattern = "/'[^']*'/";
$replacement = "";
// all that is in between '' is ok
$mod_query = preg_replace($pattern,$replacement,$query);
// after striping all '..' if we still have ; then query is composed of multiple queries
if (strpos($mod_query,";"))
return false;
return true;
}*/
public static function get_last_db_error()
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
global $db_type;
switch ($db_type) {
case "mysql":
return mysqli_error(self::$_connection);
case "postgresql":
return pg_last_error(self::$_connection);
}
return false;
}
/**
* Make query taking into account the database type
* @param $query String - query to pe performed
* @return Result of function that performs query for set database type
*/
public static function db_query($query)
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
global $db_type;
switch ($db_type) {
case "mysql":
$res = mysqli_query(self::$_connection,$query);
$warn_count = mysqli_warning_count(self::$_connection);
if ($warn_count) {
$warnings = array();
$warning = mysqli_get_warnings(self::$_connection);
do {
$warnings[] = $warning->message;
} while ($warning->next());
$warning = "$warn_count warning(s) when running query: '$query'. ".implode(", ",$warnings);
Debug::trigger_report('critical', $warning);
}
return $res;
break;
case "postgresql":
return pg_query(self::$_connection,$query);
}
return false;
}
/**
* Build array describing query result
* @param $query String - query that was performed
* @param $res Returned value by db_query
* @param $retrieve_last_id false or Array (Name of id field, table name) -- just for INSERT queries
* @return false - if $res is false <=> query failed
* for INSERT/UPDATE/DELETE array(bool, affected_rows) or array(bool, affected_rows, last_id) for INSERT
* with $retrieve_last_id specified
* otherwise Array(0=>array(col1_name=>col1_value, col2_name=>col2_value ..), 1=>...)
*/
private static function query_result($query, $res, $retrieve_last_id)
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
global $db_type, $func_query_result;
if (!isset($func_query_result))
$func_query_result = "htmlentities";
if (!$res)
return false;
$query = strtolower($query);
$query = trim($query); // trim white spaces and \n and a few others
if (substr($query,0,6) == "insert" && $retrieve_last_id) {
switch ($db_type) {
case "mysql":
$last_id = mysqli_insert_id(self::$_connection);
break;
case "postgresql":
$oid = pg_last_oid($res);
$query2 = "SELECT ".$retrieve_last_id[0]." FROM ".$retrieve_last_id[1]." WHERE oid=$oid";
$res2 = self::queryRaw($query2);
if (!$res2)
return false;
$last_id = pg_fetch_result($res2,0,0);
break;
}
}
if (substr($query,0,6) == "delete" || substr($query,0,6) ==
"update" || substr($query,0,6) == "insert") {
// return type = array(bool, int2)
switch ($db_type) {
case "mysql":
$affected = mysqli_affected_rows(self::$_connection);
break;
case "postgresql":
$affected = pg_affected_rows($res);
break;
}
$status = ($res) ? true : false;
if (substr($query,0,6) == "insert" && $retrieve_last_id) {
return array($status, $affected, $last_id);
}else
return array($status, $affected);
} elseif (substr($query,0,6) == "select" || substr($query,0,4)== "show") {
if (!$res)
return false;
$array = array();
$i = 0;
switch ($db_type) {
case "mysql":
if (mysqli_num_rows($res))
while ($row = mysqli_fetch_assoc($res))
{
$array[$i] = array();
foreach ($row as $var_name=>$value)
$array[$i][$var_name] = ($func_query_result && is_callable($func_query_result)) ? call_user_func($func_query_result, self::unescape($value)) : self::unescape($value);
$i++;
}
break;
case "postgresql":
for($i=0; $i<pg_num_rows($res); $i++)
{
$array[$i] = array();
for($j=0; $j<pg_num_fields($res); $j++)
$array[$i][pg_field_name($res,$j)] = ($func_query_result && is_callable($func_query_result)) ? call_user_func($func_query_result, self::unescape(pg_fetch_result($res,$i,$j))) : self::unescape(pg_fetch_result($res,$i,$j));
}
break;
}
return $array;
}
return true;
}
/**
* Perform query without verifying if it failed or not
* @param $query Text representing the query to perform
* @param $retrieve_last_id false or Array (Name of id field, table name) -- just for INSERT queries
* @return Result received after the performinng of the query
*/
public static function queryRaw($query, $retrieve_last_id=false)
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
if (!self::connect())
return false;
if(isset($_SESSION["debug_all"]))
Debug::Output("queryRaw", $query);
//if (!self::is_single_query($query))
// return false;
$res = self::db_query($query);
$res = self::query_result($query, $res, $retrieve_last_id);
return $res;
}
/**
* Create corresponding sql table for this object
* @param $table Name of the table
* @param $vars Array of variables for this object
* @return Result returned by performing the query to create this $table
*/
public static function createTable($table,$vars)
{
Debug::func_start(__METHOD__,func_get_args(),"dbstruct");
global $db_type, $enforce_basic_constrains;
if (!self::connect())
return false;
$query = "";
$nr_serial_fields = 0;
foreach ($vars as $name => $var)
{
if(is_numeric($name))
{
Debug::trigger_report('critical',"You are trying to add a column named $name, numeric names of columns are not allowed");
// do not allow numeric names of columns
exit(_("You are trying to add a column named ").$name.", "._("numeric names of columns are not allowed").".");
}
$type = $var->_type;
if (isset(self::$_translate_sql_types[$db_type][$type]))
$type = self::$_translate_sql_types[$db_type][$type];
$type = strtolower($type);
switch ($type)
{
case "timestamp":
$type = "$type NULL DEFAULT NULL";
break;
case "serial":
if ($var->_key != "")
$type = "int4";
break;
case "bigserial":
if ($var->_key != "")
$type = "int8";
break;
case "bigint(20) unsigned not null auto_increment":
if ($var->_key != "")
$type = "bigint(20)";
break;
}
if ($query != "")
$query.= ",";
if ($type=="serial" || $type=="bigserial" || $type=="bigint(20) unsigned not null auto_increment") {
$nr_serial_fields++;
$query.= esc($name)." $type";
if ($type == "bigint(20) unsigned not null auto_increment")
$query.= ", primary key ($name)";
} else {
if (substr($table,0,6)=="_temp_" && ($name == 'inserted' || $name == 'deleted')) {
$old_enforce_basic_constrains = $enforce_basic_constrains;
$enforce_basic_constrains = true;
}
$query.= esc($name)." $type";
if (!$enforce_basic_constrains)
continue;
if ($var->_required)
$query.= " NOT NULL";
if ((strlen($var->_value) || $var->_value===true || $var->_value===false) && !in_array($var->_type,array("timestamp","date","datetime"))) {
$value = $var->escape($var->_value);
$query.= " DEFAULT ".$value;
}
if (substr($table,0,6)=="_temp_" && ($name == 'inserted' || $name == 'deleted'))
$enforce_basic_constrains = $old_enforce_basic_constrains;
}
}
// do not allow creation of tables with more than one serial field
// protection is inforced here because i rely on the fact that there is just one numeric id or none
if($nr_serial_fields > 1) {
Debug::trigger_report('critical', "Table $table has $nr_serial_fields serial or bigserial fields. You can use 1 serial or bigserial field per table or none. ");
exit(_("Error").": "._("Table ").$table." "._("has")." ".$nr_serial_fields." ".("serial or bigserial fields. You can use 1 serial or bigserial field per table or none."));
}
$query = "CREATE TABLE $table ($query)";
if ($db_type == "postgresql")
$query.= " WITH OIDS";
elseif ($db_type == "mysql") {
if (substr($table,0,6)!="_temp_")
$obj = Model::getObject($table);
else
$obj = TemporaryModel::getObject(substr($table,6));
$engine = call_user_func(array($obj,"getDbEngine"));
if ($engine)
$query.= "ENGINE $engine";
}
$res = self::queryRaw($query) !== false;
if (!$res)
Debug::Output(_("Could not create table")." '$table'. "._("Query failed").": $query". " .Error: ".Database::get_last_db_error());
return $res;
}
/**
* Update the structure of the table
* @param $table Name of the table
* @param $vars Array of variables for this object
* @return Bool value showing if the update succeeded or not
*/
public static function updateTable($table,$vars)
{
Debug::func_start(__METHOD__,func_get_args(),"dbstruct");
global $db_type, $critical_col_diff, $error_sql_update, $enforce_basic_constrains;
if (!self::connect())
return false;
switch ($db_type) {
case "mysql":
$query = "SHOW COLUMNS FROM $table";
$res = self::queryRaw($query);
if (!$res)
{
Debug::Output('dbstruct', _("Table")." '$table' "._("does not exist, we'll create it"));
return self::createTable($table,$vars);
}
$cols = array();
for ($i=0; $i<count($res); $i++)
$cols[$res[$i]["Field"]] = array("type"=>$res[$i]["Type"], "not_null"=>(($res[$i]["Null"]=="NO") ? true : false), "default"=>$res[$i]['Default']);
break;
case "postgresql":
$query = "SELECT pg_attribute.attname as name, pg_type.typname as type, (CASE WHEN atthasdef IS TRUE THEN pg_get_expr(adbin,'pg_catalog.pg_class'::regclass) ELSE NULL END) as default, pg_attribute.attnotnull as not_null FROM pg_class, pg_type, pg_attribute LEFT OUTER JOIN pg_attrdef ON pg_attribute.attnum=pg_attrdef.adnum WHERE pg_class.oid=pg_attribute.attrelid and pg_class.relname='$table' and pg_class.relkind='r' and pg_type.oid=pg_attribute.atttypid";
$res = self::db_query($query);
if (!$res || !pg_num_rows($res))
{
Debug::Output('dbstruct', _("Table")." '$table' "._("does not exist, we'll create it"));
return self::createTable($table,$vars);
}
for ($i=0; $i<pg_num_rows($res); $i++) {
$row = pg_fetch_array($res,$i);
$default = $row["default"];
$default = explode("'::",$default);
if (count($default)>1) {
$default = $default[0];
$default = substr($default,1);
} else
$default = $default[0];
$cols[$row["name"]] = array("type"=>$row["type"], "not_null"=>(($row["not_null"]=="t") ? true : false), "default"=>$default);
}
break;
}
foreach ($vars as $name => $var)
{
$type = $var->_type;
if (isset(self::$_translate_sql_types[$db_type][$type]))
$type = self::$_translate_sql_types[$db_type][$type];
$type = strtolower($type);
if (!isset($cols[$name]))
{
if ($type == "timestamp")
$type = "$type NULL DEFAULT NULL";
if ($type == "serial")
$type = "int4";
if ($type == "bigserial")
$type = "int8";
if ($type == "bigint(20) unsigned not null auto_increment") {
if ($db_type!="mysql" || strlen($var->_key)) {
$type = "bigint(20)";
} else {
$type .= ", ADD primary key ($name)";
}
}
Debug::Output('dbstruct', _("No field")." '$name' "._("in table")." '$table'".(", we'll create it"));
$query = "ALTER TABLE ".esc($table)." ADD COLUMN ".esc($name)." $type";
if ($enforce_basic_constrains) {
if ($var->_required)
$query.= " NOT NULL";
if ((strlen($var->_value) || $var->_value===true || $var->_value===false) && !in_array($var->_type,array("timestamp","date","datetime"))) {
$value = $var->escape($var->_value);
$query.= " DEFAULT ".$value;
}
}
if (!self::queryRaw($query)) {
Debug::Output('critical', _("Could not update table")." '$table'. ".("Query failed").": '$query'". " .Error: ".Database::get_last_db_error());
$error_sql_update = true;
continue;
}
if ($var->_value !== null)
{
$val = $var->escape($var->_value);
$query = "UPDATE ".esc($table)." SET ".esc($name)."=$val";
if (!self::queryRaw($query)) {
Debug::Output('critical', _("Could not update table fields to default value for")." '$table'. "._("Query failed").": '$query'". " .Error: ".Database::get_last_db_error());
$error_sql_update = true;
}
}
}
else
{
$orig_type = $type;
// we need to adjust what we expect for some types
switch ($type)
{
case "serial":
$type = "int4";
break;
case "bigserial":
$type = "int8";
break;
}
if ($enforce_basic_constrains && $critical_col_diff) {
$dbtype = $cols[$name]["type"];
if ($dbtype=="bool")
$cols[$name]["default"] = ($cols[$name]["default"]=="true" || $cols[$name]["default"]=="1") ? true : false;
$db_default = $var->escape($cols[$name]["default"]);
$db_not_null = $cols[$name]["not_null"];
$class_default = $var->escape($var->_value);
if ($dbtype == $type && $db_default==$class_default && $db_not_null===$var->_required)
continue;
elseif (($dbtype == "bigint(20) unsigned" || $dbtype == "bigint(20)") && $type == "bigint(20) unsigned not null auto_increment")
continue;
elseif ($dbtype!=$type) {
if ($db_type=='postgresql')
$query = "ALTER TABLE ".esc($table)." ALTER COLUMN ".esc($name)." TYPE $type";
else
$query = "ALTER TABLE ".esc($table)." CHANGE ".esc($name)." ".esc($name)." $type";
if (!self::queryRaw($query)) {
Debug::Output('critical', _("Could not change table field $name from $dbtype to $type for")." '$table'. "._("Query failed").": '$query'". " .Error: ".Database::get_last_db_error());
$error_sql_update = true;
}
continue;
}
elseif ($orig_type=="serial" || $orig_type=="bigserial")
continue;
$db_str_not_null = ($db_not_null) ? " NOT NULL" : "";
$db_str_default = (strlen($db_default)) ? " DEFAULT ".$db_default : "";
$str_not_null = ($var->_required) ? " NOT NULL" : "";
$str_default = (strlen($class_default)) ? " DEFAULT ".$class_default : "";
Debug::Output('critical', _("Field")." '".$name."' "._("in table")." "."'$table' "._("is of type")." $dbtype$db_str_not_null$db_str_default ".strtoupper(_("but should be"))." $type$str_not_null$str_default");
} else {
// Maintain compatibility with previous implementation
// Don't force user to set DEFAULT VALUES and NOT NULL for columns when their projects didn't need to
$dbtype = $cols[$name]["type"];
if ($dbtype == $type)
continue;
elseif (($dbtype == "bigint(20) unsigned" || $dbtype == "bigint(20)") && $type == "bigint(20) unsigned not null auto_increment")
continue;
elseif ($dbtype!=$type) {
if ($db_type=='postgresql')
$query = "ALTER TABLE ".esc($table)." ALTER COLUMN ".esc($name)." TYPE $type";
else
$query = "ALTER TABLE ".esc($table)." CHANGE ".esc($name)." ".esc($name)." $type";
if (!self::queryRaw($query)) {
Debug::Output('critical', _("Could not change table field $name from $dbtype to $type for")." '$table'. "._("Query failed").": '$query'". " .Error: ".Database::get_last_db_error());
$error_sql_update = true;
}
continue;
}
Debug::Output('critical', _("Field")." '".$name."' "._("in table")." "."'$table' "._("is of type")." '$dbtype' "._("but should be")." '$type'");
}
$error_sql_update = true;
}
}
return true;
}
/**
* Creates one or more btree indexs on the specified table
* @param $table Name of the table
* @param $columns Array with the columns for defining each index
* Ex: array("time") will create an index with the name "$table-time" on column "time"
* array("index-time"=>"time", "comb-time-user_id"=>"time, user_id") creates an index called "index-time" on column "time"
* and an index called "comb-time-user_id" using both "time" and "user_id" columns
* @return Bool value showing if the creating succeeded or not
*/
public static function createIndex($table, $columns)
{
Debug::func_start(__METHOD__,func_get_args(),"dbstruct");
global $db_type;
$no_error = true;
$make_vacuum = false;
foreach($columns as $index_name=>$index_columns)
{
if ($index_columns == '' || !$index_columns)
continue;
if(is_numeric($index_name))
$index_name = "$table-index";
switch ($db_type) {
case "mysql":
$query = "CREATE INDEX ".esc($index_name)." USING btree ON ".esc($table)."($index_columns)";
break;
case "postgresql":
$query = "CREATE INDEX ".esc($index_name)." ON ".esc($table)." USING btree ($index_columns)";
break;
}
$res = self::queryRaw($query);
if (!$res)
{
$no_error = false;
continue;
}
$make_vacuum = true;
}
if ($make_vacuum)
self::vacuum($table);
return $no_error;
}
public static function vacuum($table)
{
Debug::func_start(__METHOD__,func_get_args(),"dbstruct");
global $db_type;
switch ($db_type) {
case "mysql":
$query = "OPTIMIZE TABLE $table";
break;
case "postgresql":
$query = "VACUUM ANALYZE $table";
break;
default:
$query = null;
}
if ($query)
self::db_query($query);
}
public static function escape($value)
{
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
global $db_type;
switch ($db_type) {
case "mysql":
return mysqli_real_escape_string(self::connect(), $value);
case "postgresql":
return pg_escape_string(self::connect(), $value);
}
return $value;
}
public static function escape_string()
{
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
global $db_type;
if ($db_type == "mysql")
return "`";
else
return "\"";
}
public static function unescape($value)
{
Debug::func_start(__METHOD__,func_get_args(),"paranoid");
return $value;
}
public static function likeOperator()
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
global $db_type;
// we want case insensitive like. Use ILIKE for postgres, LIKE for mysql
switch ($db_type) {
case "mysql":
return "LIKE";
case "postgresql":
return "ILIKE";
}
return "LIKE";
}
public static function boolCondition($value)
{
Debug::func_start(__METHOD__,func_get_args(),"framework");
global $db_type;
switch ($db_type) {
case "mysql":
if ($value)
return "=1";
else
return "=0";
break;
case "postgresql":
case "default":
if ($value)
return " IS TRUE";
else
return " IS NOT TRUE";
break;
}
}
public static function boolValue($value)
{
if ($value==="t" || $value==="1" || $value===1)
return true;
return false;
}
}
function esc($col)
{
Debug::func_start(__FUNCTION__,func_get_args(),"paranoid");
return Database::escape_string().$col.Database::escape_string();
}
// general model for defining an object that will be mapped to an sql table
class Model
{
protected $_model;
//if $_invalid is set to true, this object can't be set as a key for update or delete clauses
protected $_invalid;
//whether the params for a certain object were set or not. It is set to true in setParams dar is called from setObj
protected $_set;
//whether a select or extendedSelect was performed on the object
protected $_retrieved;
//whether to check or not which fields have been modified before making the update
protected $_check_col_diff;
protected $_modified_col = array();
protected static $_models = false;
protected static $_modified = false;
// array with name of objects that are performers when using the ActionLog class
protected static $_performers = array();
/**