dolibarr 21.0.0-beta
DoliDB.class.php
Go to the documentation of this file.
1<?php
2/*
3 * Copyright (C) 2013-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
4 * Copyright (C) 2014-2015 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
27require_once DOL_DOCUMENT_ROOT.'/core/db/Database.interface.php';
28
29
33abstract class DoliDB implements Database
34{
39
41 public $db;
43 public $type;
45 public $forcecharset = 'utf8';
47 public $forcecollate = 'utf8_unicode_ci';
48
50 private $_results; // @phpstan-ignore-line
51
53 public $connected;
55 public $database_selected;
57 public $database_name;
59 public $database_user;
61 public $database_host;
63 public $database_port;
65 public $transaction_opened;
67 public $lastquery;
69 public $lastqueryerror;
71 public $lasterror;
73 public $lasterrno;
74
76 public $prefix_db;
77
79 public $ok;
81 public $error;
82
83
84
91 public function prefix()
92 {
93 return (empty($this->prefix_db) ? MAIN_DB_PREFIX : $this->prefix_db);
94 }
95
104 public function ifsql($test, $resok, $resko)
105 {
106 //return 'IF('.$test.','.$resok.','.$resko.')'; // Not sql standard
107 return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
108 }
109
116 public function stddevpop($nameoffield)
117 {
118 return 'STDDEV_POP('.$nameoffield.')';
119 }
120
128 public function hintindex($nameofindex, $mode = 1)
129 {
130 return '';
131 }
132
133
142 public function regexpsql($subject, $pattern, $sqlstring = 0)
143 {
144 if ($sqlstring) {
145 return "(". $subject ." REGEXP '" . $this->escape($pattern) . "')";
146 }
147
148 return "('". $this->escape($subject) ."' REGEXP '" . $this->escape($pattern) . "')";
149 }
150
151
160 public function idate($param, $gm = 'tzserver')
161 {
162 // TODO $param should be gmt, so we should have default $gm to 'gmt' instead of default 'tzserver'
163 return dol_print_date($param, "%Y-%m-%d %H:%M:%S", $gm);
164 }
165
171 public function lasterrno()
172 {
173 return $this->lasterrno;
174 }
175
186 public function sanitize($stringtosanitize, $allowsimplequote = 0, $allowsequals = 0, $allowsspace = 0, $allowschars = 1)
187 {
188 return preg_replace('/[^0-9_\-\.,'.($allowschars ? 'a-z' : '').($allowsequals ? '=' : '').($allowsimplequote ? "\'" : '').($allowsspace ? ' ' : '').']/i', '', $stringtosanitize);
189 }
190
197 public function begin($textinlog = '')
198 {
199 if (!$this->transaction_opened) {
200 $ret = $this->query("BEGIN");
201 if ($ret) {
202 $this->transaction_opened++;
203 dol_syslog("BEGIN Transaction".($textinlog ? ' '.$textinlog : ''), LOG_DEBUG);
204 dol_syslog('', 0, 1);
205 return 1;
206 } else {
207 return 0;
208 }
209 } else {
210 $this->transaction_opened++;
211 dol_syslog('', 0, 1);
212 return 1;
213 }
214 }
215
222 public function commit($log = '')
223 {
224 dol_syslog('', 0, -1);
225 if ($this->transaction_opened <= 1) {
226 $ret = $this->query("COMMIT");
227 if ($ret) {
228 $this->transaction_opened = 0;
229 dol_syslog("COMMIT Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
230 return 1;
231 } else {
232 return 0;
233 }
234 } else {
235 $this->transaction_opened--;
236 return 1;
237 }
238 }
239
246 public function rollback($log = '')
247 {
248 dol_syslog('', 0, -1);
249 if ($this->transaction_opened <= 1) {
250 $ret = $this->query("ROLLBACK");
251 $this->transaction_opened = 0;
252 dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
253 return $ret;
254 } else {
255 $this->transaction_opened--;
256 return 1;
257 }
258 }
259
267 public function plimit($limit = 0, $offset = 0)
268 {
269 global $conf;
270 if (empty($limit)) {
271 return "";
272 }
273 if ($limit < 0) {
274 $limit = $conf->liste_limit;
275 }
276 if ($offset > 0) {
277 return " LIMIT ".((int) $offset).",".((int) $limit)." ";
278 } else {
279 return " LIMIT ".((int) $limit)." ";
280 }
281 }
282
288 public function getVersionArray()
289 {
290 return preg_split("/[\.,-]/", $this->getVersion());
291 }
292
298 public function lastquery()
299 {
300 return $this->lastquery;
301 }
302
310 public function order($sortfield = '', $sortorder = '')
311 {
312 if (!empty($sortfield)) {
313 $oldsortorder = '';
314 $return = '';
315 $fields = explode(',', $sortfield);
316 $orders = (!empty($sortorder) ? explode(',', $sortorder) : array());
317 $i = 0;
318 foreach ($fields as $val) {
319 if (!$return) {
320 $return .= ' ORDER BY ';
321 } else {
322 $return .= ', ';
323 }
324
325 $return .= preg_replace('/[^0-9a-z_\.]/i', '', $val); // Add field
326
327 $tmpsortorder = (empty($orders[$i]) ? '' : trim($orders[$i]));
328
329 // Only ASC and DESC values are valid SQL
330 if (strtoupper($tmpsortorder) === 'ASC') {
331 $oldsortorder = 'ASC';
332 $return .= ' ASC';
333 } elseif (strtoupper($tmpsortorder) === 'DESC') {
334 $oldsortorder = 'DESC';
335 $return .= ' DESC';
336 } else {
337 $return .= ' '.($oldsortorder ? $oldsortorder : 'ASC');
338 }
339
340 $i++;
341 }
342 return $return;
343 } else {
344 return '';
345 }
346 }
347
353 public function lasterror()
354 {
355 return $this->lasterror;
356 }
357
367 public function jdate($string, $gm = 'tzserver')
368 {
369 // TODO $string should be converted into a GMT timestamp, so param gm should be set to true by default instead of false
370 if ($string == 0 || $string == "0000-00-00 00:00:00") {
371 return '';
372 }
373 $string = preg_replace('/([^0-9])/i', '', $string);
374 $tmp = $string.'000000';
375 $date = dol_mktime((int) substr($tmp, 8, 2), (int) substr($tmp, 10, 2), (int) substr($tmp, 12, 2), (int) substr($tmp, 4, 2), (int) substr($tmp, 6, 2), (int) substr($tmp, 0, 4), $gm);
376 return $date;
377 }
378
384 public function lastqueryerror()
385 {
386 return $this->lastqueryerror;
387 }
388
397 public function getRow($sql)
398 {
399 $sql .= ' LIMIT 1';
400
401 $resql = $this->query($sql);
402 if ($resql) {
403 $obj = $this->fetch_object($resql);
404 if ($obj) {
405 $this->free($resql);
406 return $obj;
407 } else {
408 return 0;
409 }
410 }
411
412 return false;
413 }
414
423 public function getRows($sql)
424 {
425 if (!preg_match('/LIMIT \d+(?:(?:,\ *\d*)|(?:\ +OFFSET\ +\d*))?\ *;?$/', $sql)) {
426 trigger_error(__CLASS__ .'::'.__FUNCTION__.'() query must have a LIMIT clause', E_USER_ERROR);
427 }
428
429 $resql = $this->query($sql);
430 if ($resql) {
431 $results = array();
432 if ($this->num_rows($resql) > 0) {
433 while ($obj = $this->fetch_object($resql)) {
434 $results[] = $obj;
435 }
436 }
437 $this->free($resql);
438 return $results;
439 }
440
441 return false;
442 }
443}
Class to manage Dolibarr database access.
commit($log='')
Validate a database transaction.
hintindex($nameofindex, $mode=1)
Return SQL string to force an index.
idate($param, $gm='tzserver')
Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date fiel...
const LABEL
Force subclass to implement LABEL - description of DB type.
ifsql($test, $resok, $resko)
Format a SQL IF.
getVersionArray()
Return version of database server into an array.
lastqueryerror()
Return last query in error.
begin($textinlog='')
Start transaction.
rollback($log='')
Cancel a transaction and go back to initial data values.
lasterror()
Return last error label.
getRow($sql)
Return first result from query as object Note : This method executes a given SQL query and retrieves ...
lasterrno()
Return last error code.
lastquery()
Return last request executed with query()
plimit($limit=0, $offset=0)
Define limits and offset of request.
stddevpop($nameoffield)
Return SQL string to aggregate using the Standard Deviation of population.
prefix()
Return the DB prefix found into prefix_db (if it was set manually by doing $dbhandler->prefix_db=....
sanitize($stringtosanitize, $allowsimplequote=0, $allowsequals=0, $allowsspace=0, $allowschars=1)
Sanitize a string for SQL forging.
regexpsql($subject, $pattern, $sqlstring=0)
Format a SQL REGEXP.
getRows($sql)
Return all results from query as an array of objects.
order($sortfield='', $sortorder='')
Define sort criteria of request.
const VERSIONMIN
Force subclass to implement VERSIONMIN - required DB version.
jdate($string, $gm='tzserver')
Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true) 19700101020000 -...
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Class to manage Dolibarr database access for an SQL database.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
getVersion()
Return version of database server.
escape($stringtoencode)
Escape a string to insert data.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
num_rows($resultset)
Return number of lines for result of a SELECT.
free($resultset=null)
Free last resultset used.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79