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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
|
<?php
/*
** Copyright (C) 1995-2007 by the ITools Authors.
** This file is part of ITools - the Internet Tools Library
**
** ITools is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** ITools 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. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
**
** dbi.class - UltraFlexible Database Interface 3000
*/
class it_dbi
{
var $_found_rows; # public: number of found rows if CALC_FOUND_ROWS was set
var $_data; # semi-public: current result as assoc array
# Default configuration of dbi class
var $_defaultconfig = array
(
'db' => null,
'server' => "localhost",
'server_update' => null,
'user' => "itools",
'pw' => "",
'safety' => 1, # 0= never die, 1=die if query invalid, 2=die also if no results
#'keyfield' => 'ID', # Don't set to null here, filled later by _get_field_info()
#'charset' => # client charset (requires MySQL 5.0.7 or later)
'classprefix' => "",
'getfieldinfo' => true, # do not read schema. only select() allowed
'localized_defaultlanguage' => "de", # Localize fields with this suffix, e.g. copy title_de to title on read
'throttle_writes' => 0, # sleep for 'throttle_writes' multiplied by the execution time after every write
'unbuffered' => false, # use MYSQLI_USE_RESULT (WARNING this is not at all equivalent to normal it_dbi WARNING)
'ignored_warnings' => "", # regex of additional mysql warnings numbers to ignore
);
var $_key; # Key of currently loaded record or null (public readonly)
var $_fields; # Array of name => array(Field,Type,Null,Key,Default,Extra,Length) of fields (public readonly)
var $_fieldnames; # All field names in schema for case mismatch alert
var $_convertfunc; # Array of name => convert function (currently intval and floatval) for this field's values
var $_link; # DB link identifier (private)
var $_dbid; # string identifying db connection. used for _state_purgeshared from outside
var $_affectedrows;# Affected rows (mysql_affected_rows() gets clobbered)
var $_writes; # Number of (non-omittable) writes to sql using this instance
/**
* Constructor: Initialize the DBI interface
* @param $p optional array(key => value) of configuration data
* @param $query Optional initial query to run
*/
function __construct($p = array(), $query = null)
{
# Shortcut: String config means use this table with default values
if (!is_array($p))
$p = array('table' => $p);
if ($p['home'])
$p['db'] = strtr(it::match('/www/([^/]*)', $p['home']), '.-', '__');
# If the global singleton defaults are for this db/server/server_update then use them.
$dp = (array)$GLOBALS['it_dbi']->_p;
if ((!isset($p['db']) || ($p['db'] == $dp['db'])) && (!isset($p['server']) || ($p['server'] == $dp['server'])) && (!isset($p['server_update']) || ($p['server_update'] == $dp['server_update'])))
$p += $dp;
# Combine our settings with user's defaults and class defaults
$p += (array)$GLOBALS['it_dbi_defaultconfig'] + array('db' => $GLOBALS['ULTRADB']) + $this->_defaultconfig + array('charset' => strtr(strtolower(ini_get('default_charset')), array('iso-8859-1' => 'latin1', 'utf-8' => 'utf8mb4', 'utf8' => 'utf8mb4')));
unset($this->_defaultconfig); # to shorten ED() output
$this->_p = $p;
if ($p['table']) # Standard use: create a table object
{
if (!isset($GLOBALS['it_dbi']))
new it_dbi;
if ($p['getfieldinfo'])
$this->_p += $this->_get_field_info(); # Get $this->_fields and p[keyfield, autoincrement, randomid]
if (is_array($query))
{
# Call with all arguments except first one
$args = func_get_args();
array_shift($args);
call_user_func_array(array($this, "select"), $args);
}
elseif (isset($query))
$this->read($query);
}
else
$GLOBALS['it_dbi'] =& $this;
}
/**
* function Tablename($query)
* Constructor. Returns record object from table Tablename.
* If $query is set, it encodes a SELECT to execute and store in the returned object, see select()
* Note: Old second parameter $config has been deprecated and will be removed
*/ #:}
/**
* Factory: Create classes of all database tables. Call statically.
* @param $p array(key => value) of configuration data
*/
function createclasses($p = array())
{
# Make sure singleton exists
$dbi = $GLOBALS['it_dbi'] ? $GLOBALS['it_dbi'] : new it_dbi($p);
$p += $dbi->_p;
$dbid = "{$p['user']}@{$p['server']}:{$p['db']}";
$state = it_dbi::_state_get($dbid);
if (!$tables = $state['tables'])
{
$tables = $dbi->tables($p);
$state = it_dbi::_state_get($dbid); # State could have been modified by $db->tables() call
$state['tables'] = $tables;
it_dbi::_state_put($dbid, $state);
}
foreach ($tables as $table)
{
# Either create class in autoloader or manually just below
if (!class_exists($p['classprefix'] . $table))
it_dbi::createclass(array('table' => $table) + $p);
}
}
/**
* Convert table given by name into a class
*/
static function createclass($p)
{
# Shortcut: String config means use this table with default values
if (!is_array($p))
$p = array('table' => $p);
# Make sure singleton exists
$dbi = $GLOBALS['it_dbi'] ? $GLOBALS['it_dbi'] : new it_dbi(array('table' => null) + $p);
$p += $dbi->_p; # FIXME: (has to be checked for side effects!)
$dbid = $dbi->_dbid = "{$p['user']}@{$p['server']}:{$p['db']}";
if (!isset($dbi->_tables[$dbid]))
{
$state = it_dbi::_state_get($dbid);
$dbi->_tables[$dbid] = array();
if (!($tables = $state['tables']))
{
for ($tables = array(), $res = $dbi->query('SHOW TABLES', $p); $row = mysqli_fetch_row($res);)
$tables[] = $row[0];
$state = it_dbi::_state_get($dbid); # State could have been modified by query above
$state['tables'] = $tables;
it_dbi::_state_put($dbid, $state);
}
foreach ($tables as $table)
$dbi->_tables[$dbid][$table] = true;
}
if ($p['forcecreate'] || $dbi->_tables[$dbid][$p['table']]) # Do not generate classes for non-existant tables (can be overridden by forcecreate => true, used in tests/it_dbi.t)
{
$classname = $p['classprefix'] . $p['table'];
if (substr($classname, 0, 4) != 'PMA_') # It is designed behaviour that an error is generated if this class already exists!
{
$interface = function_exists("interface_exists") && interface_exists("Iterator", false) ? "implements Iterator" : "";
$code = "class $classname extends it_dbi $interface
{
function __construct(/* \$query ... */)
{
\$args = func_get_args();
\$query = array_shift(\$args); # Preserve type (scalar/array) in single parameter case
foreach (\$args as \$arg)
\$query = array_merge((array)\$query, (array)\$arg);
parent::__construct(" . var_export($p, true) . ", \$query);
}
}";
debug("it_dbi::createclass('{$p['table']}'): creating class $classname, dbid=$dbid", 5);
eval($code);
}
}
}
/**
* INTERNAL: Connect to mysql server and maintain a global link cache
*/
function _connect($p = array())
{
$p += $this->_p;
$dbid = "{$p['user']}@{$p['server']}:{$p['db']}";
$state = it_dbi::_state_get($dbid);
if ($p['reconnect'] || !($this->_link = $state['link']))
{
# Force new link if same server/user was seen before (mysql ignores selected db)
if ($GLOBALS['it_dbi']->_connected["{$p['server']}/{$p['user']}"]++)
$this->_link = @mysqli_connect($p['server'], $p['user'], $p['pw']);
else
$this->_link = @mysqli_connect($p['server'], $p['user'], $p['pw']);
if (!$this->_link)
{
# One retry after a short delay
it::log('sqllog', "it_dbi(): retrying DB link (mysqli_connect {$p['server']}, {$p['db']}): " . mysqli_connect_error());
sleep(1);
$this->_link = @mysqli_connect($p['server'], $p['user'], $p['pw']);
}
if (!$this->_link)
$this->_fatal("_connect(): can't create DB link (mysqli_connect {$p['user']}@{$p['server']}, {$p['db']}): " . mysqli_connect_error());
if (!(@mysqli_select_db($this->_link, $p['db'])))
$this->_fatal("_connect(): can't select database \"{$p['db']}\"");
# set charset used for this connection
if ($p['charset'])
if (!mysqli_set_charset($this->_link, $p['charset']))
$this->_fatal("_connect(): can't set charset \"{$p['charset']}\"");
# NOTE: This overwrites old state but that is on purpose. New link means we should refetch all info about connection
$state['link'] = $this->_link;
it_dbi::_state_put($dbid, $state, false); # Store only locally as link is not shared anyway
}
}
/**
* INTERNAL: construct SQL SET clause of changed values from tags array.
* $force = must write all fields, dont try to optimize
*/
function _set($tags, $force = false)
{
$result = array();
$dyndata = $this->_dyndata;
foreach((array)$tags as $field => $value)
{
$f = trim($field, "-");
if (!$this->_fields[$f] && it::match(",$f,", $this->_fieldnames))
it::error("case mismatch on field $f, valid fields $this->_fieldnames");
if ($this->_p['charset'] == "utf8") # NOTE: Mysql charset is simply utf8, not utf-8
$value = it::any2utf8($value, "error in db-field $field");
if (!$this->_fields[$f] && $this->_fields['dyncols'])
{
if (substr($field, 0, 1) === "-")
$newdyns[] = "'\$.$f', " . $value;
else if ($force || isset($value) && isset($dyndata[$f]) ? strval($value) !== strval($dyndata[$f]) : $value !== $dyndata[$f] || !array_key_exists($f, $dyndata))
{
if (is_null($value))
$deldyns[] = "'\$.$f'";
else
$newdyns[] = "'\$.$f', " . $this->escape_string($value);
}
$alldyns[] = $this->escape_string($f) . ", " . (substr($field, 0, 1) === "-" ? $value : $this->escape_string($value));
$dyndata[$f] = $value;
}
else if (substr($field, 0, 1) === '-') # Unquoted value (always added)
$result[] = substr($field, 1) . "=$value";
else if ($force || (isset($value) && isset($this->_data[$field]) ? strval($value) !== strval($this->_data[$field]) : $value !== $this->_data[$field] || !array_key_exists($field, $this->_data)))
$result[] = "`$field`=" . (isset($value) ? $this->escape_string($value) : 'NULL');
}
if ($alldyns)
{
if ($force == "insert") # INSERT/REPLACE
$result[] = "dyncols = JSON_OBJECT(" . join(", ", (array)$alldyns) . ")";
else if ($newdyns || $deldyns)
{
$source = $this->_dyndata ? 'dyncols' : '"{}"';
if ($newdyns)
$source = "JSON_SET($source, " . join(', ', $newdyns) . ')';
if ($deldyns)
$source = "JSON_REMOVE($source, " . join(', ', $deldyns) . ')';
$result[] = "dyncols = $source";
}
}
$this->_writes += $result ? 1 : 0;
return $result ? 'SET ' . implode(', ', $result) : '';
}
/**
* INTERNAL: construct SQL FROM clause of fields JOIN and FROM in query params
* @see select()
*/
function _from($params, $omit_from = false)
{
$result = $this->_p['table'];
if (isset($params['JOIN']) || isset($params['FROM'])) # WARNING: this field gets abused for "tablename USE INDEX (fast2)
$result = trim($params['FROM'] . " " . $params['JOIN']);
return ($omit_from ? "" : "FROM ") . $result;
}
/**
* Create an SQL query (the stuff after 'WHERE') according to an array of selection criteria.
*
* Example:
* $sql = $table->_where(array('Type' => 'bar',
* 'Date >=' => '1999-01-01', '-Date <' => 'NOW()',
* 'Status' => array('foo', 'bar', 'qux'), # same as 'Status IN' => ...
* 'User NI' => 'chris'), 'ORDER BY Date');
*
* @param $params optional array of fieldname => value tupels. These are ANDed to form a WHERE clause.
* fieldname can contain an operator (separated by space), the default operator is '='.
* The special operator 'NI' specifies that the argument must be contained in a comma-separated list.
* @param $link DB link used to escape values (not used anymore)
* @param $omit_where Do not add 'WHERE ' to result
* @return The generated SQL clause
* @see select()
* @see iterate()
*/
function _where($params)
{
$dyncols_enabled = !strlen($params['JOIN'] . $params['FROM']);
unset($params['JOIN'], $params['FROM']);
if (is_array($params) && (count($params) > 0))
{
$query = '';
$stringquery = '';
$sep = '';
foreach($params as $field => $value)
{
if (is_int($field)) /* no key specified; just append */
{
if (strcasecmp($value, 'OR'))
$stringquery .= " $value";
else
$sep = ' OR ';
}
else
{
$needs_where = true;
if (!isset($value))
{
$op = 'IS';
$qval = 'NULL';
}
else
{
if (preg_match('/^(\S+)\s+(\S.*)$/', $field, $regs))
{
$field = $regs[1];
$op = strtoupper($regs[2]);
}
else
$op = is_array($value) ? 'IN' : '=';
# If field name starts with '-', the raw value is taken, no escaping is done and no quotes are put around it.
if (substr($field, 0, 1) == '-')
{
$field = substr($field, 1); # Strip that '-' sign
$qval = $value;
}
else if (!is_array($value))
$qval = $this->escape_string((string)$value);
}
if ($dyncols_enabled && $this->_fields['dyncols'] && !$this->_fields[$field] && strpos($field, '(') === false)
$field = "JSON_EXTRACT(dyncols, " . $this->escape_string('$.' . $field) . ")";
switch ($op)
{
case 'NI':
if ($value)
{
$parts = array();
foreach ((array)$value as $val)
$parts[] = "CONCAT(',',$field,',') LIKE " . $this->escape_string("%,$val,%");
$query .= $sep . "(" . join(" OR ", $parts) . ")";
}
else
$query .= $sep . "1";
break;
case 'MATCH':
$qval = join(' ', (array)$value);
$query .= "$sep$op ($field) AGAINST (" . $this->escape_string($qval) . " IN BOOLEAN MODE)";
break;
case 'IN':
case 'NOT IN':
if (is_array($value))
{
if ($value)
{
$qvals = array();
foreach ($value as $val)
$qvals[] = $this->escape_string($val);
$query .= "$sep$field $op (" . join(",", $qvals) . ")"; # null is mapped to ''
}
else
$query .= $sep . (($op == 'IN') ? "0" : "1");
break;
}
/* FALLTHROUGH */
default:
if (isset($qval))
$query .= "$sep$field $op $qval";
else
it::fatal('Undefined $qval when constructing query due to invalid $value (array)');
break;
}
$sep = ' AND ';
}
}
$query .= $stringquery;
if ($needs_where)
$query = "WHERE $query";
}
return $query;
}
/**
* Internal: Output class name::error message and terminate execution.
*/
function _fatal($text, $body = null)
{
$text = get_class($this).'::'.$text;
if ($this->_link && ($errstr = mysqli_error($this->_link)))
$text = "\"$errstr\" in $text [errno " . mysqli_errno($this->_link) . "]";
if ($this->_link && ($res = @mysqli_fetch_row(mysqli_query($this->_link, 'select database()')))) # dont create extra errs
$text .= ", DB: " . $res[0];
it::fatal(['title' => $text . ", Server: " . $this->_p['server'], 'body' => $body]);
/* NOT REACHED */
}
/**
* Post-process data after reading a record.
* This is a stub-function that can be overloaded.
*/
function _read_post_process()
{
}
/**
* Pre-process data before writing a record.
* This is a stub-function that can be overloaded.
* @param $tags Reference to update/create tags, can be modified as needed
* @param $command SQL command ('INSERT', 'REPLACE' or 'UPDATE')
*/
function _write_pre_process(&$tags, $command) # NOPHPLINT
{
}
/**
* Return an array of all tables of this database
*/
function tables($p = array())
{
for ($qr = $this->query('SHOW TABLES', $p); $row = mysqli_fetch_row($qr);)
$result[] = $row[0];
return (array)$result;
}
/**
* Clear record
*/
function clear($pp = true)
{
foreach ((array)$this->_fields + (array)$this->_localizedfields + (array)$this->_data as $field => $dummy)
unset($this->$field);
unset($this->_key, $this->_data);
$pp && $this->_read_post_process();
}
/**
* Semi-internal: send a raw SQL query and return mysql result value
* @param $query complete SQL query string
* @return raw MySQL result. May die if query fails and safety is big enough
*/
function query($query, $p = array())
{
$p += $this->_p;
$start = gettimeofday(true);
if (($writing = !it::match('^(EXPLAIN|SELECT|SHOW)', $query, array('utf8' => false))))
{
if ($p['server_update'])
{
debug("switching to update server \"{$p['server_update']}\"", 5);
$this->_p['server'] = $p['server'] = $p['server_update'];
unset($this->_p['server_update'], $p['server_update'], $this->_link);
}
else if ($p['server'] == "localhost" && $p['db'] == $GLOBALS['ULTRADB'] && preg_grep('/replicate-do/', (array)@it::file($GLOBALS['ULTRAHOME'] . "/etc/my.cnf")))
if (($t = @it::file($GLOBALS['ULTRAHOME'] . "/doc/machines.txt")) && preg_grep("/^" . gethostname() . "/", array_slice($t, 2)))
it::error("local mysql write on a replication slave machine?");
}
$this->_connect($p); # must be called after update server switching code
debug("{$p['user']}@{$p['server']}:{$p['db']}" . '.' . get_class($this) . "::query(\"$query\")", 4);
if (!($result = mysqli_query($this->_link, $query, $p['unbuffered'] ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT)) && $p['safety'])
{
$errno = mysqli_errno($this->_link);
if (($p['safety'] < 2) && ($errno == 1062)) # Duplicate entry
return false;
if ($errno == 2006) # mysql server has gone away: retry
{
it::log('sqllog', "it_dbi(): reconnecting mysqli_connect {$p['server']}, {$p['db']}");
$this->_connect(array('reconnect' => true));
$result = mysqli_query($this->_link, $query, $p['unbuffered'] ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT);
}
if (!$result)
$this->_fatal("query(\"$query\") failed");
}
else if (it::match('^(CREATE|ALTER|DROP) ', $query, array('utf8' => false)))
{
# Purge cache for schema changes (after modifying table)
$dbid = "{$p['user']}@{$p['server']}:{$p['db']}";
it_dbi::_state_purgeshared($dbid);
}
$this->_affectedrows = $this->_link->affected_rows; # get_warnings() clobbers this
if (($warning = $this->_link->get_warnings()))
{
do {
if (!it::match(trim($this->_p['ignored_warnings'] . "|1364|1261|1051|1062", "|"), $warning->errno))
$messages[] = $warning->message . " [error $warning->errno]";
} while ($warning->next() && ++$checked < 20);
if ($messages)
it::error(['title' => "Mysql warning: " . $messages[0], 'body' => "$query\n\n" . join("\n", $messages) . "\n"]);
}
if ($writing && $this->_p['throttle_writes'])
usleep(1000000 * (gettimeofday(true) - $start) * $this->_p['throttle_writes']);
$msec = round(1000 * (gettimeofday(true) - $start));
$slow = $msec >= 2000;
if ($GLOBALS['debug_sqllog'] || $GLOBALS['debug_sqltrace'] || $slow)
{
$backtrace = (EDC('sqltrace') || $slow) ? it_debug::backtrace(1) : null;
$truncquery = strlen($query) > 1000 ? mb_substr($query, 0, 1000) . '...' : $query;
it::log('sqllog', "$msec\t$truncquery\t$backtrace\t" . $this->_p['server'] . ($slow ? "\tSLOW" : ""));
$this->_sqllog[] = array(
'time' => $msec,
'query' => $query,
) + ($backtrace ? array('backtrace' => $backtrace) : array());
}
return $result;
}
/**
* Read a single record by primary key, not destroying old query result $this->_result
* @param $id primary key. If null, record is cleared
* @return True if record could be read, false if not.
*/
function read($id=null)
{
$old_result = $this->_result;
$old_nofetch = $this->_nofetch;
$result = $this->select(array($this->_p['keyfield'] => $id));
$this->_result = $old_result;
$this->_nofetch = $old_nofetch;
return $result;
}
/**
* Select a set of records from table and fetch the first one
* @param $query One or more optional arrays of (field => value) or sqlstring pairs. Defaults to null (select all records)
* Fields will be joined by AND
* Fields can contain a compare operator: 'name LIKE' => "j%" or 'amount >' => 100
* Fields can start with - to prevent quoting of right side: '-modified' => "CURDATE()"
* $query can contain magic field 'SELECT' for things like 'COUNT(*)' or 'DISTINCT foo', defaults to '*'
* $query can contain magic field 'FROM' or 'JOIN' for things like 'tableA LEFT JOIN tableB ON a=b', defaults to table name
* $query can contain 'CALC_FOUND_ROWS', if true member var _found_rows contains number of matching rows before LIMIT
* $query can contain 'NOFETCH', if true the first row is not prefetched (e.g. when directly using _result)
* @return Number of matching rows, use iterate() to fetch the next record
* @see iterate()
* @see _where()
*/
function select(/* $query = array|string, ... */)
{
$query = array();
foreach (func_get_args() as $arg)
$query = array_merge($query, (array)$arg);
$this->_connect();
$result = 0;
$calc_found_rows = false;
$what = '*';
if (isset($query['SELECT']))
{
$what = $query['SELECT'];
unset($query['SELECT']);
}
unset($this->_found_rows);
if (isset($query['CALC_FOUND_ROWS']) && $query['CALC_FOUND_ROWS'])
{
$calc_found_rows = true;
$what = 'SQL_CALC_FOUND_ROWS '.$what;
}
unset($query['CALC_FOUND_ROWS']); # Always unset, so CALC_FOUND_ROWS => false doesn't generate bogus query
if (EDC('nocache'))
$what = 'SQL_NO_CACHE ' . $what;
$nofetch = $this->_nofetch = $query['NOFETCH'];
unset($query['NOFETCH']);
$this->clear(false);
if ($this->_result = $this->query($sql = "SELECT $what " . $this->_from($query) . " " . $this->_where($query)))
{
$result = $this->_p['unbuffered'] ? true : mysqli_num_rows($this->_result);
if ($calc_found_rows)
{
list($count) = mysqli_fetch_row($this->query('SELECT FOUND_ROWS()'));
$this->_found_rows = intval($count);
}
if (!$this->iterate() && ($this->_p['safety'] >= 2))
$this->_fatal("select(): query produced no results: \"$sql\"");
}
$this->_nofetch = !$nofetch;
return $result;
}
/**
* Puts next result from previous select() in member variables
* @return true if another record was fetched, false if no more records
* @see select()
*/
function iterate()
{
if (!$this->_nofetch)
{
if ($this->_data = mysqli_fetch_assoc($this->_result))
{
if ($localizedfields = $this->_localizedfields)
foreach ($localizedfields as $field => $dummy)
unset($this->$field);
foreach ((array)$this->_dyndata as $field => $dummy)
unset($this->$field);
foreach (($this->_dyndata = ($t = $this->_data['dyncols']) ? (array)json_decode($t, true) : []) as $field => $value)
$this->_data[$field] = $value;
unset($this->_data['dyncols']);
foreach ($this->_data as $field => $value)
$this->$field = (isset($value) && $this->_convertfunc[$field]) ? ($this->_data[$field] = $this->_convertfunc[$field]($value)) : $value;
if ($localizedfields)
{
$lang = T_lang();
foreach ($localizedfields as $field => $dummy)
{
$value = $this->{$field . "_" . $lang};
if (!isset($value))
$value = $this->{$field . "_" . $this->_p['localized_defaultlanguage']};
if (isset($value))
{
if (isset($this->$field))
it::fatal("Field name clash: Overwriting {$this->_p['table']}.$field with {$field}_{$lang}, only use one of those fields");
else
$this->$field = $value;
}
}
}
if (!empty($this->_p['keyfield']))
$this->_key = $this->_data[$this->_p['keyfield']];
}
else
{
$this->clear(false);
if ($this->_p['unbuffered'])
$this->_result->close();
}
$this->_read_post_process();
}
else
$this->_nofetch = false;
return (bool)$this->_data;
}
/**
* Insert a record into table. Values are taken assoc array $tags. Keys in $tags
* should contain row names unless "dyncols" exists in schema (they are stored as
* dynamic columns then). Keys with - prefix suppress quoting of values.
* After inserting, all values are valid (record is read back).
* Does not destroy internal state of last select() call
* @param $tags key => value pairs to set
* @return true for success, false for failure (e.g. duplicate entry for key)
*/
function insert($tags = array(), $command = "INSERT")
{
$this->_connect();
/* Pre-processing, $tags is passed by reference and may be modified here */
$this->_write_pre_process($tags, $command);
if ($this->_p['randomid'] && !isset($tags[$this->_p['keyfield']]))
$tags[$this->_p['keyfield']] = md5(uniqid(mt_rand()));
$set = $this->_set($tags, "insert");
if ($result = $this->query($query = "$command INTO {$this->_p['table']} " . $set))
{
$id = ($this->_p['autoincrement'] && !isset($tags[$this->_p['keyfield']])) ? mysqli_insert_id($this->_link) : $tags[$this->_p['keyfield']];
if ($this->_p['keyfield'] && !$this->read($id) && $this->_p['safety'])
$this->_fatal("insert(): can't read record back (key truncated?), id=\"$id\"", $query);
$this->_touchedids[$this->_key] = true;
}
else
$this->clear(false);
return $result;
}
/**
* Replace a record in a table
* @param $tags Additional key => value pairs
* Does not destroy internal state of last select() call
* @see insert()
*/
function replace($tags = array())
{
return $this->insert($tags, "REPLACE");
}
/**
* Create a record like replace(), but optimize if similar or identical record already exists
* MUST GIVE ALL FIELDS INCLUDING ID
* @param $tags key => value pairs to set
*/
function store($tags = array())
{
return $tags[$this->_p['keyfield']] && $this->read($tags[$this->_p['keyfield']]) ? $this->update($tags) : $this->replace($tags);
}
/**
* Update current record or a number of records given by where condition
* @param $tags key => value pairs (these have priority over changes in member vars)
* @param $where condition to select records to be modified (if not current record)
* @return number of updated records (or false on error). WARNING: read LIMIT docs before using it
* Does not destroy internal state of last select() call
*/
function update($tags = array(), $where = null)
{
$this->_connect();
$result = true;
/* Pre-processing, $tags is passed by reference and may be modified here */
$this->_write_pre_process($tags, 'UPDATE');
if ($set = $this->_set($tags, isset($where)))
{
if (!isset($where))
$where = array($this->_p['keyfield'] => $this->_data[$this->_p['keyfield']]);
if ($result = $this->query("UPDATE " . $this->_from($where, true) . " $set " . $this->_where($where)))
{
$result = $this->_affectedrows;
if (array_key_exists($this->_p['keyfield'], $tags)) # Did we just update the key?
$this->_key = $tags[$this->_p['keyfield']];
if (isset($this->_key) && $this->read($this->_key))
$this->_nofetch = false; # So we can do while(iterate()) update();
}
}
$this->_touchedids[$this->_key] = true;
return $result;
}
/**
* Delete a record
* Does not destroy query result $this->_result
* @param $query optional query for WHERE, default: delete currently loaded record
* @return number of deleted records
*/
function delete($query = null)
{
$this->_connect();
$result = 0;
if (!$query && $this->_p['keyfield'])
{
$query = array($this->_p['keyfield'] => $this->_key);
$this->clear();
}
if ($query && $this->query("DELETE " . $this->_from($query) . " " . $this->_where($query)))
$result = $this->_affectedrows;
return $result;
}
/**
* Delete records matching query which were not touched since creation of t
|