DoliDB.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 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 bool Status */
  62. public $ok;
  63. /** @var string */
  64. public $error;
  65. /**
  66. * Format a SQL IF
  67. *
  68. * @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
  69. * @param string $resok resultat si test egal
  70. * @param string $resko resultat si test non egal
  71. * @return string SQL string
  72. */
  73. public function ifsql($test, $resok, $resko)
  74. {
  75. return 'IF('.$test.','.$resok.','.$resko.')';
  76. }
  77. /**
  78. * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
  79. * Function to use to build INSERT, UPDATE or WHERE predica
  80. *
  81. * @param int $param Date TMS to convert
  82. * @param mixed $gm 'gmt'=Input informations are GMT values, 'tzserver'=Local to server TZ
  83. * @return string Date in a string YYYY-MM-DD HH:MM:SS
  84. */
  85. public function idate($param, $gm = 'tzserver')
  86. {
  87. // TODO $param should be gmt, so we should add $gm to 'gmt' instead of default 'tzserver'
  88. return dol_print_date($param, "%Y-%m-%d %H:%M:%S", $gm);
  89. }
  90. /**
  91. * Return last error code
  92. *
  93. * @return string lasterrno
  94. */
  95. public function lasterrno()
  96. {
  97. return $this->lasterrno;
  98. }
  99. /**
  100. * Sanitize a string for SQL forging
  101. *
  102. * @param string $stringtosanitize String to escape
  103. * @param int $allowsimplequote 1=Allow simple quotes in string. When string is used as a list of SQL string ('aa', 'bb', ...)
  104. * @return string String escaped
  105. */
  106. public function sanitize($stringtosanitize, $allowsimplequote = 0)
  107. {
  108. if ($allowsimplequote) {
  109. return preg_replace('/[^a-z0-9_\-\.,\']/i', '', $stringtosanitize);
  110. } else {
  111. return preg_replace('/[^a-z0-9_\-\.,]/i', '', $stringtosanitize);
  112. }
  113. }
  114. /**
  115. * Start transaction
  116. *
  117. * @return int 1 if transaction successfuly opened or already opened, 0 if error
  118. */
  119. public function begin()
  120. {
  121. if (!$this->transaction_opened) {
  122. $ret = $this->query("BEGIN");
  123. if ($ret) {
  124. $this->transaction_opened++;
  125. dol_syslog("BEGIN Transaction", LOG_DEBUG);
  126. dol_syslog('', 0, 1);
  127. }
  128. return $ret;
  129. } else {
  130. $this->transaction_opened++;
  131. dol_syslog('', 0, 1);
  132. return 1;
  133. }
  134. }
  135. /**
  136. * Validate a database transaction
  137. *
  138. * @param string $log Add more log to default log line
  139. * @return int 1 if validation is OK or transaction level no started, 0 if ERROR
  140. */
  141. public function commit($log = '')
  142. {
  143. dol_syslog('', 0, -1);
  144. if ($this->transaction_opened <= 1) {
  145. $ret = $this->query("COMMIT");
  146. if ($ret) {
  147. $this->transaction_opened = 0;
  148. dol_syslog("COMMIT Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
  149. return 1;
  150. } else {
  151. return 0;
  152. }
  153. } else {
  154. $this->transaction_opened--;
  155. return 1;
  156. }
  157. }
  158. /**
  159. * Cancel a transaction and go back to initial data values
  160. *
  161. * @param string $log Add more log to default log line
  162. * @return resource|int 1 if cancelation is ok or transaction not open, 0 if error
  163. */
  164. public function rollback($log = '')
  165. {
  166. dol_syslog('', 0, -1);
  167. if ($this->transaction_opened <= 1) {
  168. $ret = $this->query("ROLLBACK");
  169. $this->transaction_opened = 0;
  170. dol_syslog("ROLLBACK Transaction".($log ? ' '.$log : ''), LOG_DEBUG);
  171. return $ret;
  172. } else {
  173. $this->transaction_opened--;
  174. return 1;
  175. }
  176. }
  177. /**
  178. * Define limits and offset of request
  179. *
  180. * @param int $limit Maximum number of lines returned (-1=conf->liste_limit, 0=no limit)
  181. * @param int $offset Numero of line from where starting fetch
  182. * @return string String with SQL syntax to add a limit and offset
  183. */
  184. public function plimit($limit = 0, $offset = 0)
  185. {
  186. global $conf;
  187. if (empty($limit)) {
  188. return "";
  189. }
  190. if ($limit < 0) {
  191. $limit = $conf->liste_limit;
  192. }
  193. if ($offset > 0) {
  194. return " LIMIT ".((int) $offset).",".((int) $limit)." ";
  195. } else {
  196. return " LIMIT ".((int) $limit)." ";
  197. }
  198. }
  199. /**
  200. * Return version of database server into an array
  201. *
  202. * @return array Version array
  203. */
  204. public function getVersionArray()
  205. {
  206. return preg_split("/[\.,-]/", $this->getVersion());
  207. }
  208. /**
  209. * Return last request executed with query()
  210. *
  211. * @return string Last query
  212. */
  213. public function lastquery()
  214. {
  215. return $this->lastquery;
  216. }
  217. /**
  218. * Define sort criteria of request
  219. *
  220. * @param string $sortfield List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
  221. * @param string $sortorder Sort order, separated by comma. Example: 'ASC,DESC';
  222. * @return string String to provide syntax of a sort sql string
  223. */
  224. public function order($sortfield = null, $sortorder = null)
  225. {
  226. if (!empty($sortfield)) {
  227. $oldsortorder = '';
  228. $return = '';
  229. $fields = explode(',', $sortfield);
  230. $orders = explode(',', $sortorder);
  231. $i = 0;
  232. foreach ($fields as $val) {
  233. if (!$return) {
  234. $return .= ' ORDER BY ';
  235. } else {
  236. $return .= ', ';
  237. }
  238. $return .= preg_replace('/[^0-9a-z_\.]/i', '', $val); // Add field
  239. $tmpsortorder = (empty($orders[$i]) ? '' : trim($orders[$i]));
  240. // Only ASC and DESC values are valid SQL
  241. if (strtoupper($tmpsortorder) === 'ASC') {
  242. $oldsortorder = 'ASC';
  243. $return .= ' ASC';
  244. } elseif (strtoupper($tmpsortorder) === 'DESC') {
  245. $oldsortorder = 'DESC';
  246. $return .= ' DESC';
  247. } else {
  248. $return .= ' '.($oldsortorder ? $oldsortorder : 'ASC');
  249. }
  250. $i++;
  251. }
  252. return $return;
  253. } else {
  254. return '';
  255. }
  256. }
  257. /**
  258. * Return last error label
  259. *
  260. * @return string Last error
  261. */
  262. public function lasterror()
  263. {
  264. return $this->lasterror;
  265. }
  266. /**
  267. * Convert (by PHP) a PHP server TZ string date into a Timestamps date (GMT if gm=true)
  268. * 19700101020000 -> 3600 with TZ+1 and gmt=0
  269. * 19700101020000 -> 7200 whaterver is TZ if gmt=1
  270. *
  271. * @param string $string Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
  272. * @param mixed $gm 'gmt'=Input informations are GMT values, 'tzserver'=Local to server TZ
  273. * @return int|string Date TMS or ''
  274. */
  275. public function jdate($string, $gm = 'tzserver')
  276. {
  277. // TODO $string should be converted into a GMT timestamp, so param gm should be set to true by default instead of false
  278. if ($string == 0 || $string == "0000-00-00 00:00:00") {
  279. return '';
  280. }
  281. $string = preg_replace('/([^0-9])/i', '', $string);
  282. $tmp = $string.'000000';
  283. $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);
  284. return $date;
  285. }
  286. /**
  287. * Return last query in error
  288. *
  289. * @return string lastqueryerror
  290. */
  291. public function lastqueryerror()
  292. {
  293. return $this->lastqueryerror;
  294. }
  295. /**
  296. * Return first result from query as object
  297. * 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
  298. * Dont add LIMIT to your query, it will be added by this method
  299. *
  300. * @param string $sql The sql query string
  301. * @return bool|int|object False on failure, 0 on empty, object on success
  302. */
  303. public function getRow($sql)
  304. {
  305. $sql .= ' LIMIT 1';
  306. $res = $this->query($sql);
  307. if ($res) {
  308. $obj = $this->fetch_object($res);
  309. if ($obj) {
  310. return $obj;
  311. } else {
  312. return 0;
  313. }
  314. }
  315. return false;
  316. }
  317. /**
  318. * Return all results from query as an array of objects
  319. * 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
  320. * be carefull with this method use it only with some limit of results to avoid performences loss.
  321. *
  322. * @param string $sql The sql query string
  323. * @return bool|array Result
  324. * @deprecated
  325. */
  326. public function getRows($sql)
  327. {
  328. $res = $this->query($sql);
  329. if ($res) {
  330. $results = array();
  331. if ($this->num_rows($res) > 0) {
  332. while ($obj = $this->fetch_object($res)) {
  333. $results[] = $obj;
  334. }
  335. }
  336. return $results;
  337. }
  338. return false;
  339. }
  340. }