DoliDB.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/core/db/DoliDB.class.php
  21. * \brief Class file to manage Dolibarr database access
  22. */
  23. require_once DOL_DOCUMENT_ROOT.'/core/db/Database.interface.php';
  24. /**
  25. * Class to manage Dolibarr database access
  26. */
  27. abstract class DoliDB implements Database
  28. {
  29. /** @var bool|resource|SQLite3|PgSql\connection Database handler */
  30. public $db;
  31. /** @var string Database type */
  32. public $type;
  33. /** @var string Charset used to force charset when creating database */
  34. public $forcecharset = 'utf8';
  35. /** @var string Collate used to force collate when creating database */
  36. public $forcecollate = 'utf8_unicode_ci';
  37. /** @var resource Resultset of last query */
  38. private $_results;
  39. /** @var bool true if connected, else false */
  40. public $connected;
  41. /** @var bool true if database selected, else false */
  42. public $database_selected;
  43. /** @var string Selected database name */
  44. public $database_name;
  45. /** @var string Database username */
  46. public $database_user;
  47. /** @var string Database host */
  48. public $database_host;
  49. /** @var int Database port */
  50. public $database_port;
  51. /** @var int >=1 if a transaction is opened, 0 otherwise */
  52. public $transaction_opened;
  53. /** @var string Last successful query */
  54. public $lastquery;
  55. /** @var string Last failed query */
  56. public $lastqueryerror;
  57. /** @var string Last error message */
  58. public $lasterror;
  59. /** @var string Last error number. For example: 'DB_ERROR_RECORD_ALREADY_EXISTS', '12345', ... */
  60. public $lasterrno;
  61. /** @var string If we need to set a prefix specific to the database so it can be reused (when defined instead of MAIN_DB_PREFIX) to forge requests */
  62. public $prefix_db;
  63. /** @var bool Status */
  64. public $ok;
  65. /** @var string */
  66. public $error;
  67. /**
  68. * Return the DB prefix
  69. *
  70. * @return string The DB prefix
  71. */
  72. public function prefix()
  73. {
  74. return (empty($this->prefix_db) ? MAIN_DB_PREFIX : $this->prefix_db);
  75. }
  76. /**
  77. * Format a SQL IF
  78. *
  79. * @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
  80. * @param string $resok resultat si test egal
  81. * @param string $resko resultat si test non egal
  82. * @return string SQL string
  83. */
  84. public function ifsql($test, $resok, $resko)
  85. {
  86. //return 'IF('.$test.','.$resok.','.$resko.')'; // Not sql standard
  87. return '(CASE WHEN '.$test.' THEN '.$resok.' ELSE '.$resko.' END)';
  88. }
  89. /**
  90. * Return SQL string to force an index
  91. *
  92. * @param string $nameofindex Name of index
  93. * @return string SQL string
  94. */
  95. public function hintindex($nameofindex)
  96. {
  97. return '';
  98. }
  99. /**
  100. * Format a SQL REGEXP
  101. *
  102. * @param string $subject string tested
  103. * @param string $pattern SQL pattern to match
  104. * @param string $sqlstring whether or not the string being tested is an SQL expression
  105. * @return string SQL string
  106. */
  107. public function regexpsql($subject, $pattern, $sqlstring = false)
  108. {
  109. if ($sqlstring) {
  110. return "(". $subject ." REGEXP '" . $pattern . "')";
  111. }
  112. return "('". $subject ."' REGEXP '" . $pattern . "')";
  113. }
  114. /**
  115. * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
  116. * Function to use to build INSERT, UPDATE or WHERE predica
  117. *
  118. * @param int $param Date TMS to convert
  119. * @param mixed $gm 'gmt'=Input informations are GMT values, 'tzserver'=Local to server TZ
  120. * @return string Date in a string YYYY-MM-DD HH:MM:SS
  121. */
  122. public function idate($param, $gm = 'tzserver')
  123. {
  124. // TODO $param should be gmt, so we should have default $gm to 'gmt' instead of default 'tzserver'
  125. return dol_print_date($param, "%Y-%m-%d %H:%M:%S", $gm);
  126. }
  127. /**
  128. * Return last error code
  129. *
  130. * @return string lasterrno
  131. */
  132. public function lasterrno()
  133. {
  134. return $this->lasterrno;
  135. }
  136. /**
  137. * Sanitize a string for SQL forging
  138. *
  139. * @param string $stringtosanitize String to escape
  140. * @param int $allowsimplequote 1=Allow simple quotes in string. When string is used as a list of SQL string ('aa', 'bb', ...)
  141. * @param string $allowsequals 1=Allow equals sign
  142. * @return string String escaped
  143. */
  144. public function sanitize($stringtosanitize, $allowsimplequote = 0, $allowsequals = 0)
  145. {
  146. return preg_replace('/[^a-z0-9_\-\.,'.($allowsequals ? '=' : '').($allowsimplequote ? "\'" : '').']/i', '', $stringtosanitize);
  147. }
  148. /**
  149. * Start transaction
  150. *
  151. * @param string $textinlog Add a small text into log. '' by default.
  152. * @return int 1 if transaction successfuly opened or already opened, 0 if error
  153. */
  154. public function begin($textinlog = '')
  155. {
  156. if (!$this->transaction_opened) {
  157. $ret = $this->query("BEGIN");
  158. if ($ret) {
  159. $this->transaction_opened++;
  160. dol_syslog("BEGIN Transaction".($textinlog ? ' '.$textinlog : ''), LOG_DEBUG);
  161. dol_syslog('', 0, 1);
  162. }
  163. return $ret;
  164. } else {
  165. $this->transaction_opened++;
  166. dol_syslog('', 0, 1);
  167. return 1;
  168. }
  169. }
  170. /**
  171. * Validate a database transaction
  172. *
  173. * @param string $log Add more log to default log line
  174. * @return int 1 if validation is OK or transaction level no started, 0 if ERROR
  175. */
  176. public function commit($log = '')
  177. {
  178. dol_syslog('', 0, -1);
  179. if ($this->transaction_opened <= 1) {
  180. $ret = $this->query("COMMIT");
  181. if ($ret) {
  182. $this->transaction_opened = 0;
  183. dol_syslog("COMMIT Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
  184. return 1;
  185. } else {
  186. return 0;
  187. }
  188. } else {
  189. $this->transaction_opened--;
  190. return 1;
  191. }
  192. }
  193. /**
  194. * Cancel a transaction and go back to initial data values
  195. *
  196. * @param string $log Add more log to default log line
  197. * @return resource|int 1 if cancelation is ok or transaction not open, 0 if error
  198. */
  199. public function rollback($log = '')
  200. {
  201. dol_syslog('', 0, -1);
  202. if ($this->transaction_opened <= 1) {
  203. $ret = $this->query("ROLLBACK");
  204. $this->transaction_opened = 0;
  205. dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
  206. return $ret;
  207. } else {
  208. $this->transaction_opened--;
  209. return 1;
  210. }
  211. }
  212. /**
  213. * Define limits and offset of request
  214. *
  215. * @param int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
  216. * @param int $offset Numero of line from where starting fetch
  217. * @return string String with SQL syntax to add a limit and offset
  218. */
  219. public function plimit($limit = 0, $offset = 0)
  220. {
  221. global $conf;
  222. if (empty($limit)) {
  223. return "";
  224. }
  225. if ($limit < 0) {
  226. $limit = $conf->liste_limit;
  227. }
  228. if ($offset > 0) {
  229. return " LIMIT ".((int) $offset).",".((int) $limit)." ";
  230. } else {
  231. return " LIMIT ".((int) $limit)." ";
  232. }
  233. }
  234. /**
  235. * Return version of database server into an array
  236. *
  237. * @return array Version array
  238. */
  239. public function getVersionArray()
  240. {
  241. return preg_split("/[\.,-]/", $this->getVersion());
  242. }
  243. /**
  244. * Return last request executed with query()
  245. *
  246. * @return string Last query
  247. */
  248. public function lastquery()
  249. {
  250. return $this->lastquery;
  251. }
  252. /**
  253. * Define sort criteria of request
  254. *
  255. * @param string $sortfield List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
  256. * @param string $sortorder Sort order, separated by comma. Example: 'ASC,DESC'. Note: If the quantity fo sortorder values is lower than sortfield, we used the last value for missing values.
  257. * @return string String to provide syntax of a sort sql string
  258. */
  259. public function order($sortfield = null, $sortorder = null)
  260. {
  261. if (!empty($sortfield)) {
  262. $oldsortorder = '';
  263. $return = '';
  264. $fields = explode(',', $sortfield);
  265. $orders = explode(',', $sortorder);
  266. $i = 0;
  267. foreach ($fields as $val) {
  268. if (!$return) {
  269. $return .= ' ORDER BY ';
  270. } else {
  271. $return .= ', ';
  272. }
  273. $return .= preg_replace('/[^0-9a-z_\.]/i', '', $val); // Add field
  274. $tmpsortorder = (empty($orders[$i]) ? '' : trim($orders[$i]));
  275. // Only ASC and DESC values are valid SQL
  276. if (strtoupper($tmpsortorder) === 'ASC') {
  277. $oldsortorder = 'ASC';
  278. $return .= ' ASC';
  279. } elseif (strtoupper($tmpsortorder) === 'DESC') {
  280. $oldsortorder = 'DESC';
  281. $return .= ' DESC';
  282. } else {
  283. $return .= ' '.($oldsortorder ? $oldsortorder : 'ASC');
  284. }
  285. $i++;
  286. }
  287. return $return;
  288. } else {
  289. return '';
  290. }
  291. }
  292. /**
  293. * Return last error label
  294. *
  295. * @return string Last error
  296. */
  297. public function lasterror()
  298. {
  299. return $this->lasterror;
  300. }
  301. /**
  302. * Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
  303. * 19700101020000 -> 3600 with server TZ = +1 and $gm='tzserver'
  304. * 19700101020000 -> 7200 whaterver is server TZ if $gm='gmt'
  305. *
  306. * @param string $string Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
  307. * @param mixed $gm 'gmt'=Input informations are GMT values, 'tzserver'=Local to server TZ
  308. * @return int|string Date TMS or ''
  309. */
  310. public function jdate($string, $gm = 'tzserver')
  311. {
  312. // TODO $string should be converted into a GMT timestamp, so param gm should be set to true by default instead of false
  313. if ($string == 0 || $string == "0000-00-00 00:00:00") {
  314. return '';
  315. }
  316. $string = preg_replace('/([^0-9])/i', '', $string);
  317. $tmp = $string.'000000';
  318. $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);
  319. return $date;
  320. }
  321. /**
  322. * Return last query in error
  323. *
  324. * @return string lastqueryerror
  325. */
  326. public function lastqueryerror()
  327. {
  328. return $this->lastqueryerror;
  329. }
  330. /**
  331. * Return first result from query as object
  332. * Note : This method executes a given SQL query and retrieves the first row of results as an object. It should only be used with SELECT queries
  333. * Dont add LIMIT to your query, it will be added by this method
  334. *
  335. * @param string $sql The sql query string
  336. * @return bool|int|object False on failure, 0 on empty, object on success
  337. */
  338. public function getRow($sql)
  339. {
  340. $sql .= ' LIMIT 1';
  341. $res = $this->query($sql);
  342. if ($res) {
  343. $obj = $this->fetch_object($res);
  344. if ($obj) {
  345. return $obj;
  346. } else {
  347. return 0;
  348. }
  349. }
  350. return false;
  351. }
  352. /**
  353. * Return all results from query as an array of objects
  354. * Note : This method executes a given SQL query and retrieves all row of results as an array of objects. It should only be used with SELECT queries
  355. * be carefull with this method use it only with some limit of results to avoid performences loss.
  356. *
  357. * @param string $sql The sql query string
  358. * @return bool|array Result
  359. * @deprecated
  360. */
  361. public function getRows($sql)
  362. {
  363. $res = $this->query($sql);
  364. if ($res) {
  365. $results = array();
  366. if ($this->num_rows($res) > 0) {
  367. while ($obj = $this->fetch_object($res)) {
  368. $results[] = $obj;
  369. }
  370. }
  371. return $results;
  372. }
  373. return false;
  374. }
  375. }