PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/core/db/mysqli.class.php

https://bitbucket.org/speedealing/speedealing
PHP | 1245 lines | 704 code | 119 blank | 422 comment | 122 complexity | ec33a1d2928a69876c5ce162af4f22e8 MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-3.0, MIT
  1. <?php
  2. /* Copyright (C) 2001 Fabien Seisen <seisen@linuxfr.org>
  3. * Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  4. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
  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 <http://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/core/db/mysqli.class.php
  23. * \brief Class file to manage Dolibarr database access for a Mysql database
  24. */
  25. /**
  26. * \class DoliDBMysqli
  27. * \brief Class to manage Dolibarr database access for a Mysql database
  28. */
  29. class DoliDBMysqli
  30. {
  31. //! Database handler
  32. var $db;
  33. //! Database type
  34. public $type='mysqli';
  35. //! Database label
  36. static $label='MySQL';
  37. //! Charset used to force charset when creating database
  38. var $forcecharset='utf8'; // latin1, utf8. Can't be static as it may be forced with a dynamic value
  39. //! Collate used to force collate when creating database
  40. var $forcecollate='utf8_general_ci'; // latin1_swedish_ci, utf8_general_ci. Can't be static as it may be forced with a dynamic value
  41. //! Version min database
  42. static $versionmin=array(4,1,0);
  43. //! Resultset of last request
  44. private $_results;
  45. //! 1 if connected, 0 else
  46. var $connected;
  47. //! 1 if database selected, 0 else
  48. var $database_selected;
  49. //! Database name selected
  50. var $database_name;
  51. //! Nom user base
  52. var $database_user;
  53. //! >=1 if a transaction is opened, 0 otherwise
  54. var $transaction_opened;
  55. //! Last executed request
  56. var $lastquery;
  57. //! Last failed executed request
  58. var $lastqueryerror;
  59. //! Message erreur mysql
  60. var $lasterror;
  61. //! Message erreur mysql
  62. var $lasterrno;
  63. var $ok;
  64. var $error;
  65. /**
  66. * Constructor.
  67. * This create an opened connexion to a database server and eventually to a database
  68. *
  69. * @param string $type Type of database (mysql, pgsql...)
  70. * @param string $host Address of database server
  71. * @param string $user Nom de l'utilisateur autorise
  72. * @param string $pass Mot de passe
  73. * @param string $name Nom de la database
  74. * @param int $port Port of database server
  75. * @return int 1 if OK, 0 if not
  76. */
  77. function __construct($type, $host, $user, $pass, $name='', $port=0)
  78. {
  79. global $conf,$langs;
  80. // TODO error in strict mode (static property for "$forcecharset" and "$forcecollate")
  81. //if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
  82. //if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
  83. $this->database_user=$user;
  84. $this->transaction_opened=0;
  85. //print "Name DB: $host,$user,$pass,$name<br>";
  86. if (! function_exists("mysqli_connect"))
  87. {
  88. $this->connected = 0;
  89. $this->ok = 0;
  90. $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
  91. dol_syslog(get_class($this)."::DoliDBMysqli : Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.",LOG_ERR);
  92. return $this->ok;
  93. }
  94. if (! $host)
  95. {
  96. $this->connected = 0;
  97. $this->ok = 0;
  98. $this->error=$langs->trans("ErrorWrongHostParameter");
  99. dol_syslog(get_class($this)."::DoliDBMysqli : Erreur Connect, wrong host parameters",LOG_ERR);
  100. return $this->ok;
  101. }
  102. // Essai connexion serveur
  103. // We do not try to connect to database, only to server. Connect to database is done later in constrcutor
  104. $this->db = $this->connect($host, $user, $pass, '', $port);
  105. if ($this->db)
  106. {
  107. $this->connected = 1;
  108. $this->ok = 1;
  109. }
  110. else
  111. {
  112. // host, login ou password incorrect
  113. $this->connected = 0;
  114. $this->ok = 0;
  115. $this->error=mysqli_connect_error();
  116. dol_syslog(get_class($this)."::DoliDBMysqli : Erreur Connect mysqli_connect_error=".$this->error,LOG_ERR);
  117. }
  118. // Si connexion serveur ok et si connexion base demandee, on essaie connexion base
  119. if ($this->connected && $name)
  120. {
  121. if ($this->select_db($name))
  122. {
  123. $this->database_selected = 1;
  124. $this->database_name = $name;
  125. $this->ok = 1;
  126. // If client connected with different charset than Dolibarr HTML output
  127. $clientmustbe='';
  128. if (preg_match('/UTF-8/i',$conf->file->character_set_client)) $clientmustbe='utf8';
  129. if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
  130. if (mysqli_character_set_name($this->db) != $clientmustbe)
  131. {
  132. $this->query("SET NAMES '".$clientmustbe."'", $this->db);
  133. //$this->query("SET CHARACTER SET ". $this->forcecharset);
  134. }
  135. }
  136. else
  137. {
  138. $this->database_selected = 0;
  139. $this->database_name = '';
  140. $this->ok = 0;
  141. $this->error=$this->error();
  142. dol_syslog(get_class($this)."::DoliDBMysqli : Erreur Select_db ".$this->error,LOG_ERR);
  143. }
  144. }
  145. else
  146. {
  147. // Pas de selection de base demandee, ok ou ko
  148. $this->database_selected = 0;
  149. if ($this->connected)
  150. {
  151. // If client connected with different charset than Dolibarr HTML output
  152. $clientmustbe='';
  153. if (preg_match('/UTF-8/i',$conf->file->character_set_client)) $clientmustbe='utf8';
  154. if (preg_match('/ISO-8859-1/i',$conf->file->character_set_client)) $clientmustbe='latin1';
  155. if (mysqli_character_set_name($this->db) != $clientmustbe)
  156. {
  157. $this->query("SET NAMES '".$clientmustbe."'", $this->db);
  158. //$this->query("SET CHARACTER SET ". $this->forcecharset);
  159. }
  160. }
  161. }
  162. return $this->ok;
  163. }
  164. /**
  165. * Convert a SQL request in Mysql syntax to native syntax
  166. *
  167. * @param string $line SQL request line to convert
  168. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  169. * @return string SQL request line converted
  170. */
  171. static function convertSQLFromMysql($line,$type='ddl')
  172. {
  173. return $line;
  174. }
  175. /**
  176. * Select a database
  177. *
  178. * @param string $database Name of database
  179. * @return boolean true if OK, false if KO
  180. */
  181. function select_db($database)
  182. {
  183. dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
  184. return mysqli_select_db($this->db,$database);
  185. }
  186. /**
  187. * Connexion to server
  188. *
  189. * @param string $host database server host
  190. * @param string $login login
  191. * @param string $passwd password
  192. * @param string $name name of database (not used for mysql, used for pgsql)
  193. * @param string $port Port of database server
  194. * @return resource Database access handler
  195. * @see close
  196. */
  197. function connect($host, $login, $passwd, $name, $port=0)
  198. {
  199. dol_syslog(get_class($this)."::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name",LOG_DEBUG);
  200. $newhost=$host;
  201. $newport=$port;
  202. // With mysqli, port must be in connect parameters
  203. if (! $newport) $newport=3306;
  204. $this->db = @mysqli_connect($newhost, $login, $passwd, $name, $newport);
  205. //print "Resultat fonction connect: ".$this->db;
  206. return $this->db;
  207. }
  208. /**
  209. * Return version of database server
  210. *
  211. * @return string Version string
  212. */
  213. function getVersion()
  214. {
  215. return mysqli_get_server_info($this->db);
  216. }
  217. /**
  218. * Return version of database server into an array
  219. *
  220. * @return array Version array
  221. */
  222. function getVersionArray()
  223. {
  224. return explode('.',$this->getVersion());
  225. }
  226. /**
  227. * Close database connexion
  228. *
  229. * @return boolean True if disconnect successfull, false otherwise
  230. * @see connect
  231. */
  232. function close()
  233. {
  234. if ($this->db)
  235. {
  236. if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
  237. $this->connected=0;
  238. return mysqli_close($this->db);
  239. }
  240. return false;
  241. }
  242. /**
  243. * Start transaction
  244. *
  245. * @return int 1 if transaction successfuly opened or already opened, 0 if error
  246. */
  247. function begin()
  248. {
  249. if (! $this->transaction_opened)
  250. {
  251. $ret=$this->query("BEGIN");
  252. if ($ret)
  253. {
  254. $this->transaction_opened++;
  255. dol_syslog("BEGIN Transaction",LOG_DEBUG);
  256. }
  257. return $ret;
  258. }
  259. else
  260. {
  261. $this->transaction_opened++;
  262. return 1;
  263. }
  264. }
  265. /**
  266. * Validate a database transaction
  267. *
  268. * @param string $log Add more log to default log line
  269. * @return int 1 if validation is OK or transaction level no started, 0 if ERROR
  270. */
  271. function commit($log='')
  272. {
  273. if ($this->transaction_opened<=1)
  274. {
  275. $ret=$this->query("COMMIT");
  276. if ($ret)
  277. {
  278. $this->transaction_opened=0;
  279. dol_syslog("COMMIT Transaction".($log?' '.$log:''),LOG_DEBUG);
  280. }
  281. return $ret;
  282. }
  283. else
  284. {
  285. $this->transaction_opened--;
  286. return 1;
  287. }
  288. }
  289. /**
  290. * Annulation d'une transaction et retour aux anciennes valeurs
  291. *
  292. * @param string $log Add more log to default log line
  293. * @return int 1 si annulation ok ou transaction non ouverte, 0 en cas d'erreur
  294. */
  295. function rollback($log='')
  296. {
  297. if ($this->transaction_opened<=1)
  298. {
  299. $ret=$this->query("ROLLBACK");
  300. $this->transaction_opened=0;
  301. dol_syslog("ROLLBACK Transaction".($log?' '.$log:''),LOG_DEBUG);
  302. return $ret;
  303. }
  304. else
  305. {
  306. $this->transaction_opened--;
  307. return 1;
  308. }
  309. }
  310. /**
  311. * Execute a SQL request and return the resultset
  312. *
  313. * @param string $query SQL query string
  314. * @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions).
  315. * Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints.
  316. * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
  317. * @return resource Resultset of answer
  318. */
  319. function query($query,$usesavepoint=0,$type='auto')
  320. {
  321. $query = trim($query);
  322. if (! $this->database_name)
  323. {
  324. // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
  325. $ret = mysqli_query($this->db,$query);
  326. }
  327. else
  328. {
  329. $ret = mysqli_query($this->db,$query);
  330. }
  331. if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
  332. {
  333. // Si requete utilisateur, on la sauvegarde ainsi que son resultset
  334. if (! $ret)
  335. {
  336. $this->lastqueryerror = $query;
  337. $this->lasterror = $this->error();
  338. $this->lasterrno = $this->errno();
  339. dol_syslog(get_class($this)."::query SQL error: ".$query." ".$this->lasterrno, LOG_WARNING);
  340. }
  341. $this->lastquery=$query;
  342. $this->_results = $ret;
  343. }
  344. return $ret;
  345. }
  346. /**
  347. * Renvoie la ligne courante (comme un objet) pour le curseur resultset
  348. *
  349. * @param Resultset $resultset Curseur de la requete voulue
  350. * @return Object Object result line or false if KO or end of cursor
  351. */
  352. function fetch_object($resultset)
  353. {
  354. // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
  355. if (! is_object($resultset)) { $resultset=$this->_results; }
  356. return mysqli_fetch_object($resultset);
  357. }
  358. /**
  359. * Return datas as an array
  360. *
  361. * @param Resultset $resultset Resultset of request
  362. * @return array Array
  363. */
  364. function fetch_array($resultset)
  365. {
  366. // If resultset not provided, we take the last used by connexion
  367. if (! is_object($resultset)) { $resultset=$this->_results; }
  368. return mysqli_fetch_array($resultset);
  369. }
  370. /**
  371. * Return datas as an array
  372. *
  373. * @param Resultset $resultset Resultset of request
  374. * @return array Array
  375. */
  376. function fetch_row($resultset)
  377. {
  378. // If resultset not provided, we take the last used by connexion
  379. if (! is_bool($resultset))
  380. {
  381. if (! is_object($resultset)) { $resultset=$this->_results; }
  382. return mysqli_fetch_row($resultset);
  383. }
  384. else
  385. {
  386. // si le curseur est un booleen on retourne la valeur 0
  387. return 0;
  388. }
  389. }
  390. /**
  391. * Return number of lines for result of a SELECT
  392. *
  393. * @param Resultset $resultset Resulset of requests
  394. * @return int Nb of lines
  395. * @see affected_rows
  396. */
  397. function num_rows($resultset)
  398. {
  399. // If resultset not provided, we take the last used by connexion
  400. if (! is_object($resultset)) { $resultset=$this->_results; }
  401. return mysqli_num_rows($resultset);
  402. }
  403. /**
  404. * Renvoie le nombre de lignes dans le resultat d'une requete INSERT, DELETE ou UPDATE
  405. *
  406. * @param resultset $resultset Curseur de la requete voulue
  407. * @return int Nombre de lignes
  408. * @see num_rows
  409. */
  410. function affected_rows($resultset)
  411. {
  412. // If resultset not provided, we take the last used by connexion
  413. if (! is_object($resultset)) { $resultset=$this->_results; }
  414. // mysql necessite un link de base pour cette fonction contrairement
  415. // a pqsql qui prend un resultset
  416. return mysqli_affected_rows($this->db);
  417. }
  418. /**
  419. * Libere le dernier resultset utilise sur cette connexion
  420. *
  421. * @param resultset $resultset Curseur de la requete voulue
  422. * @return void
  423. */
  424. function free($resultset=0)
  425. {
  426. // If resultset not provided, we take the last used by connexion
  427. if (! is_object($resultset)) { $resultset=$this->_results; }
  428. // Si resultset en est un, on libere la memoire
  429. if (is_object($resultset)) mysqli_free_result($resultset);
  430. }
  431. /**
  432. * Defini les limites de la requete
  433. *
  434. * @param int $limit nombre maximum de lignes retournees
  435. * @param int $offset numero de la ligne a partir de laquelle recuperer les ligne
  436. * @return string chaine exprimant la syntax sql de la limite
  437. */
  438. function plimit($limit=0,$offset=0)
  439. {
  440. global $conf;
  441. if (! $limit) $limit=$conf->liste_limit;
  442. if ($offset > 0) return " LIMIT $offset,$limit ";
  443. else return " LIMIT $limit ";
  444. }
  445. /**
  446. * Define sort criteria of request
  447. *
  448. * @param string $sortfield List of sort fields
  449. * @param string $sortorder Sort order
  450. * @return string String to provide syntax of a sort sql string
  451. * TODO Mutualized this into a mother class
  452. */
  453. function order($sortfield=0,$sortorder=0)
  454. {
  455. if ($sortfield)
  456. {
  457. $return='';
  458. $fields=explode(',',$sortfield);
  459. foreach($fields as $val)
  460. {
  461. if (! $return) $return.=' ORDER BY ';
  462. else $return.=',';
  463. $return.=preg_replace('/[^0-9a-z_\.]/i','',$val);
  464. if ($sortorder) $return.=' '.preg_replace('/[^0-9a-z]/i','',$sortorder);
  465. }
  466. return $return;
  467. }
  468. else
  469. {
  470. return '';
  471. }
  472. }
  473. /**
  474. * Escape a string to insert data
  475. *
  476. * @param string $stringtoencode String to escape
  477. * @return string String escaped
  478. */
  479. function escape($stringtoencode)
  480. {
  481. return addslashes($stringtoencode);
  482. }
  483. /**
  484. * Convert (by PHP) a GM Timestamp date into a string date with PHP server TZ to insert into a date field.
  485. * Function to use to build INSERT, UPDATE or WHERE predica
  486. *
  487. * @param string $param Date TMS to convert
  488. * @return string Date in a string YYYYMMDDHHMMSS
  489. */
  490. function idate($param)
  491. {
  492. return dol_print_date($param,"%Y%m%d%H%M%S");
  493. }
  494. /**
  495. * Convert (by PHP) a PHP server TZ string date into a GM Timestamps date
  496. * 19700101020000 -> 3600 with TZ+1
  497. *
  498. * @param string $string Date in a string (YYYYMMDDHHMMSS, YYYYMMDD, YYYY-MM-DD HH:MM:SS)
  499. * @return date Date TMS
  500. */
  501. function jdate($string)
  502. {
  503. $string=preg_replace('/([^0-9])/i','',$string);
  504. $tmp=$string.'000000';
  505. $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4));
  506. return $date;
  507. }
  508. /**
  509. * Format a SQL IF
  510. *
  511. * @param string $test Test string (example: 'cd.statut=0', 'field IS NULL')
  512. * @param string $resok resultat si test egal
  513. * @param string $resko resultat si test non egal
  514. * @return string SQL string
  515. */
  516. function ifsql($test,$resok,$resko)
  517. {
  518. return 'IF('.$test.','.$resok.','.$resko.')';
  519. }
  520. /**
  521. * Return last request executed with query()
  522. *
  523. * @return string Last query
  524. */
  525. function lastquery()
  526. {
  527. return $this->lastquery;
  528. }
  529. /**
  530. * Renvoie la derniere requete en erreur
  531. *
  532. * @return string lastqueryerror
  533. */
  534. function lastqueryerror()
  535. {
  536. return $this->lastqueryerror;
  537. }
  538. /**
  539. * Renvoie le libelle derniere erreur
  540. *
  541. * @return string lasterror
  542. */
  543. function lasterror()
  544. {
  545. return $this->lasterror;
  546. }
  547. /**
  548. * Renvoie le code derniere erreur
  549. *
  550. * @return string lasterrno
  551. */
  552. function lasterrno()
  553. {
  554. return $this->lasterrno;
  555. }
  556. /**
  557. * Return generic error code of last operation.
  558. *
  559. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  560. */
  561. function errno()
  562. {
  563. if (! $this->connected) {
  564. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  565. return 'DB_ERROR_FAILED_TO_CONNECT';
  566. }
  567. else {
  568. // Constants to convert a MySql error code to a generic Dolibarr error code
  569. $errorcode_map = array(
  570. 1004 => 'DB_ERROR_CANNOT_CREATE',
  571. 1005 => 'DB_ERROR_CANNOT_CREATE',
  572. 1006 => 'DB_ERROR_CANNOT_CREATE',
  573. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  574. 1008 => 'DB_ERROR_CANNOT_DROP',
  575. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  576. 1044 => 'DB_ERROR_ACCESSDENIED',
  577. 1046 => 'DB_ERROR_NODBSELECTED',
  578. 1048 => 'DB_ERROR_CONSTRAINT',
  579. 1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  580. 1051 => 'DB_ERROR_NOSUCHTABLE',
  581. 1054 => 'DB_ERROR_NOSUCHFIELD',
  582. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  583. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  584. 1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  585. 1064 => 'DB_ERROR_SYNTAX',
  586. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  587. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  588. 1091 => 'DB_ERROR_NOSUCHFIELD',
  589. 1100 => 'DB_ERROR_NOT_LOCKED',
  590. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  591. 1146 => 'DB_ERROR_NOSUCHTABLE',
  592. 1216 => 'DB_ERROR_NO_PARENT',
  593. 1217 => 'DB_ERROR_CHILD_EXISTS',
  594. 1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
  595. 1451 => 'DB_ERROR_CHILD_EXISTS'
  596. );
  597. if (isset($errorcode_map[mysqli_errno($this->db)]))
  598. {
  599. return $errorcode_map[mysqli_errno($this->db)];
  600. }
  601. $errno=mysqli_errno($this->db);
  602. return ($errno?'DB_ERROR_'.$errno:'0');
  603. }
  604. }
  605. /**
  606. * Return description of last error
  607. *
  608. * @return string Error text
  609. */
  610. function error()
  611. {
  612. if (! $this->connected) {
  613. // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
  614. return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
  615. }
  616. else {
  617. return mysqli_error($this->db);
  618. }
  619. }
  620. /**
  621. * Get last ID after an insert INSERT
  622. *
  623. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  624. * @param string $fieldid Field name
  625. * @return int Id of row
  626. */
  627. function last_insert_id($tab,$fieldid='rowid')
  628. {
  629. return mysqli_insert_id($this->db);
  630. }
  631. /**
  632. * Encrypt sensitive data in database
  633. * Warning: This function includes the escape, so it must use direct value
  634. *
  635. * @param string $fieldorvalue Field name or value to encrypt
  636. * @param int $withQuotes Return string with quotes
  637. * @return string XXX(field) or XXX('value') or field or 'value'
  638. *
  639. */
  640. function encrypt($fieldorvalue, $withQuotes=0)
  641. {
  642. global $conf;
  643. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  644. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
  645. //Encryption key
  646. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  647. $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
  648. if ($cryptType && !empty($cryptKey))
  649. {
  650. if ($cryptType == 2)
  651. {
  652. $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
  653. }
  654. else if ($cryptType == 1)
  655. {
  656. $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
  657. }
  658. }
  659. return $return;
  660. }
  661. /**
  662. * Decrypt sensitive data in database
  663. *
  664. * @param string $value Value to decrypt
  665. * @return string Decrypted value if used
  666. */
  667. function decrypt($value)
  668. {
  669. global $conf;
  670. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  671. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
  672. //Encryption key
  673. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
  674. $return = $value;
  675. if ($cryptType && !empty($cryptKey))
  676. {
  677. if ($cryptType == 2)
  678. {
  679. $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  680. }
  681. else if ($cryptType == 1)
  682. {
  683. $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  684. }
  685. }
  686. return $return;
  687. }
  688. /**
  689. * Return connexion ID
  690. *
  691. * @return string Id connexion
  692. */
  693. function DDLGetConnectId()
  694. {
  695. $resql=$this->query('SELECT CONNECTION_ID()');
  696. $row=$this->fetch_row($resql);
  697. return $row[0];
  698. }
  699. /**
  700. * Create a new database
  701. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  702. * We force to create database with charset this->forcecharset and collate this->forcecollate
  703. *
  704. * @param string $database Database name to create
  705. * @param string $charset Charset used to store data
  706. * @param string $collation Charset used to sort data
  707. * @param string $owner Username of database owner
  708. * @return resource resource defined if OK, null if KO
  709. */
  710. function DDLCreateDb($database,$charset='',$collation='',$owner='')
  711. {
  712. if (empty($charset)) $charset=$this->forcecharset;
  713. if (empty($collation)) $collation=$this->forcecollate;
  714. // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
  715. $sql = "CREATE DATABASE `".$this->escape($database)."`";
  716. $sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
  717. dol_syslog($sql,LOG_DEBUG);
  718. $ret=$this->query($sql);
  719. if (! $ret)
  720. {
  721. // We try again for compatibility with Mysql < 4.1.1
  722. $sql = "CREATE DATABASE `".$this->escape($database)."`";
  723. dol_syslog($sql,LOG_DEBUG);
  724. $ret=$this->query($sql);
  725. }
  726. return $ret;
  727. }
  728. /**
  729. * List tables into a database
  730. *
  731. * @param string $database Name of database
  732. * @param string $table Nmae of table filter ('xxx%')
  733. * @return resource Resource
  734. */
  735. function DDLListTables($database, $table='')
  736. {
  737. $listtables=array();
  738. $like = '';
  739. if ($table) $like = "LIKE '".$table."'";
  740. $sql="SHOW TABLES FROM ".$database." ".$like.";";
  741. //print $sql;
  742. $result = $this->query($sql);
  743. while($row = $this->fetch_row($result))
  744. {
  745. $listtables[] = $row[0];
  746. }
  747. return $listtables;
  748. }
  749. /**
  750. * List information of columns into a table.
  751. *
  752. * @param string $table Name of table
  753. * @return array Tableau des informations des champs de la table
  754. */
  755. function DDLInfoTable($table)
  756. {
  757. $infotables=array();
  758. $sql="SHOW FULL COLUMNS FROM ".$table.";";
  759. dol_syslog($sql,LOG_DEBUG);
  760. $result = $this->query($sql);
  761. while($row = $this->fetch_row($result))
  762. {
  763. $infotables[] = $row;
  764. }
  765. return $infotables;
  766. }
  767. /**
  768. * Create a table into database
  769. *
  770. * @param string $table Nom de la table
  771. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  772. * @param string $primary_key Nom du champ qui sera la clef primaire
  773. * @param string $type Type de la table
  774. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  775. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  776. * @param string $keys Tableau des champs cles noms => valeur
  777. * @return int <0 if KO, >=0 if OK
  778. */
  779. function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys="",$fulltext_keys="",$keys="")
  780. {
  781. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  782. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  783. $sql = "create table ".$table."(";
  784. $i=0;
  785. foreach($fields as $field_name => $field_desc)
  786. {
  787. $sqlfields[$i] = $field_name." ";
  788. $sqlfields[$i] .= $field_desc['type'];
  789. if( preg_match("/^[^\s]/i",$field_desc['value']))
  790. $sqlfields[$i] .= "(".$field_desc['value'].")";
  791. else if( preg_match("/^[^\s]/i",$field_desc['attribute']))
  792. $sqlfields[$i] .= " ".$field_desc['attribute'];
  793. else if( preg_match("/^[^\s]/i",$field_desc['default']))
  794. {
  795. if(preg_match("/null/i",$field_desc['default']))
  796. $sqlfields[$i] .= " default ".$field_desc['default'];
  797. else
  798. $sqlfields[$i] .= " default '".$field_desc['default']."'";
  799. }
  800. else if( preg_match("/^[^\s]/i",$field_desc['null']))
  801. $sqlfields[$i] .= " ".$field_desc['null'];
  802. else if( preg_match("/^[^\s]/i",$field_desc['extra']))
  803. $sqlfields[$i] .= " ".$field_desc['extra'];
  804. $i++;
  805. }
  806. if($primary_key != "")
  807. $pk = "primary key(".$primary_key.")";
  808. if($unique_keys != "")
  809. {
  810. $i = 0;
  811. foreach($unique_keys as $key => $value)
  812. {
  813. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
  814. $i++;
  815. }
  816. }
  817. if($keys != "")
  818. {
  819. $i = 0;
  820. foreach($keys as $key => $value)
  821. {
  822. $sqlk[$i] = "KEY ".$key." (".$value.")";
  823. $i++;
  824. }
  825. }
  826. $sql .= implode(',',$sqlfields);
  827. if($primary_key != "")
  828. $sql .= ",".$pk;
  829. if($unique_keys != "")
  830. $sql .= ",".implode(',',$sqluq);
  831. if($keys != "")
  832. $sql .= ",".implode(',',$sqlk);
  833. $sql .=") type=".$type;
  834. dol_syslog($sql,LOG_DEBUG);
  835. if(! $this -> query($sql))
  836. return -1;
  837. else
  838. return 1;
  839. }
  840. /**
  841. * Return a pointer of line with description of a table or field
  842. *
  843. * @param string $table Name of table
  844. * @param string $field Optionnel : Name of field if we want description of field
  845. * @return resource Resource
  846. */
  847. function DDLDescTable($table,$field="")
  848. {
  849. $sql="DESC ".$table." ".$field;
  850. dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
  851. $this->_results = $this->query($sql);
  852. return $this->_results;
  853. }
  854. /**
  855. * Create a new field into table
  856. *
  857. * @param string $table Name of table
  858. * @param string $field_name Name of field to add
  859. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  860. * @param string $field_position Optionnel ex.: "after champtruc"
  861. * @return int <0 if KO, >0 if OK
  862. */
  863. function DDLAddField($table,$field_name,$field_desc,$field_position="")
  864. {
  865. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  866. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  867. $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
  868. $sql.= $field_desc['type'];
  869. if(preg_match("/^[^\s]/i",$field_desc['value']))
  870. if (! in_array($field_desc['type'],array('date','datetime')))
  871. {
  872. $sql.= "(".$field_desc['value'].")";
  873. }
  874. if(preg_match("/^[^\s]/i",$field_desc['attribute']))
  875. $sql.= " ".$field_desc['attribute'];
  876. if(preg_match("/^[^\s]/i",$field_desc['null']))
  877. $sql.= " ".$field_desc['null'];
  878. if(preg_match("/^[^\s]/i",$field_desc['default']))
  879. {
  880. if(preg_match("/null/i",$field_desc['default']))
  881. $sql.= " default ".$field_desc['default'];
  882. else
  883. $sql.= " default '".$field_desc['default']."'";
  884. }
  885. if(preg_match("/^[^\s]/i",$field_desc['extra']))
  886. $sql.= " ".$field_desc['extra'];
  887. $sql.= " ".$field_position;
  888. dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
  889. if(! $this->query($sql))
  890. {
  891. return -1;
  892. }
  893. else
  894. {
  895. return 1;
  896. }
  897. }
  898. /**
  899. * Update format of a field into a table
  900. *
  901. * @param string $table Name of table
  902. * @param string $field_name Name of field to modify
  903. * @param string $field_desc Array with description of field format
  904. * @return int <0 if KO, >0 if OK
  905. */
  906. function DDLUpdateField($table,$field_name,$field_desc)
  907. {
  908. $sql = "ALTER TABLE ".$table;
  909. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  910. if ($field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') $sql.="(".$field_desc['value'].")";
  911. dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
  912. if (! $this->query($sql))
  913. return -1;
  914. else
  915. return 1;
  916. }
  917. /**
  918. * Drop a field from table
  919. *
  920. * @param string $table Name of table
  921. * @param string $field_name Name of field to drop
  922. * @return int <0 if KO, >0 if OK
  923. */
  924. function DDLDropField($table,$field_name)
  925. {
  926. $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
  927. dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
  928. if (! $this->query($sql))
  929. {
  930. $this->error=$this->lasterror();
  931. return -1;
  932. }
  933. else return 1;
  934. }
  935. /**
  936. * Create a user and privileges to connect to database (even if database does not exists yet)
  937. *
  938. * @param string $dolibarr_main_db_host Ip serveur
  939. * @param string $dolibarr_main_db_user Nom user a creer
  940. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  941. * @param string $dolibarr_main_db_name Database name where user must be granted
  942. * @return int <0 if KO, >=0 if OK
  943. */
  944. function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
  945. {
  946. $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
  947. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  948. $resql=$this->query($sql);
  949. if (! $resql)
  950. {
  951. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_ERR);
  952. return -1;
  953. }
  954. $sql = "GRANT ALL PRIVILEGES ON ".$this->escape($dolibarr_main_db_name).".* TO '".$this->escape($dolibarr_main_db_user)."'@'".$this->escape($dolibarr_main_db_host)."' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
  955. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  956. $resql=$this->query($sql);
  957. if (! $resql)
  958. {
  959. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_ERR);
  960. return -1;
  961. }
  962. $sql="FLUSH Privileges";
  963. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql);
  964. $resql=$this->query($sql);
  965. if (! $resql)
  966. {
  967. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_ERR);
  968. return -1;
  969. }
  970. return 1;
  971. }
  972. /**
  973. * Return charset used to store data in database
  974. *
  975. * @return string Charset
  976. */
  977. function getDefaultCharacterSetDatabase()
  978. {
  979. $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
  980. if (!$resql)
  981. {
  982. // version Mysql < 4.1.1
  983. return $this->forcecharset;
  984. }
  985. $liste=$this->fetch_array($resql);
  986. return $liste['Value'];
  987. }
  988. /**
  989. * Return list of available charset that can be used to store data in database
  990. *
  991. * @return array List of Charset
  992. */
  993. function getListOfCharacterSet()
  994. {
  995. $resql=$this->query('SHOW CHARSET');
  996. $liste = array();
  997. if ($resql)
  998. {
  999. $i = 0;
  1000. while ($obj = $this->fetch_object($resql) )
  1001. {
  1002. $liste[$i]['charset'] = $obj->Charset;
  1003. $liste[$i]['description'] = $obj->Description;
  1004. $i++;
  1005. }
  1006. $this->free($resql);
  1007. } else {
  1008. // version Mysql < 4.1.1
  1009. return null;
  1010. }
  1011. return $liste;
  1012. }
  1013. /**
  1014. * Return collation used in database
  1015. *
  1016. * @return string Collation value
  1017. */
  1018. function getDefaultCollationDatabase()
  1019. {
  1020. $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
  1021. if (!$resql)
  1022. {
  1023. // version Mysql < 4.1.1
  1024. return $this->forcecollate;
  1025. }
  1026. $liste=$this->fetch_array($resql);
  1027. return $liste['Value'];
  1028. }
  1029. /**
  1030. * Return list of available collation that can be used for database
  1031. *
  1032. * @return array Liste of Collation
  1033. */
  1034. function getListOfCollation()
  1035. {
  1036. $resql=$this->query('SHOW COLLATION');
  1037. $liste = array();
  1038. if ($resql)
  1039. {
  1040. $i = 0;
  1041. while ($obj = $this->fetch_object($resql) )
  1042. {
  1043. $liste[$i]['collation'] = $obj->Collation;
  1044. $i++;
  1045. }
  1046. $this->free($resql);
  1047. } else {
  1048. // version Mysql < 4.1.1
  1049. return null;
  1050. }
  1051. return $liste;
  1052. }
  1053. /**
  1054. * Return full path of dump program
  1055. *
  1056. * @return string Full path of dump program
  1057. */
  1058. function getPathOfDump()
  1059. {
  1060. $fullpathofdump='/pathtomysqldump/mysqldump';
  1061. $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
  1062. if ($resql)
  1063. {
  1064. $liste=$this->fetch_array($resql);
  1065. $basedir=$liste['Value'];
  1066. $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
  1067. }
  1068. return $fullpathofdump;
  1069. }
  1070. /**
  1071. * Return full path of restore program
  1072. *
  1073. * @return string Full path of restore program
  1074. */
  1075. function getPathOfRestore()
  1076. {
  1077. $fullpathofimport='/pathtomysql/mysql';
  1078. $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
  1079. if ($resql)
  1080. {
  1081. $liste=$this->fetch_array($resql);
  1082. $basedir=$liste['Value'];
  1083. $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
  1084. }
  1085. return $fullpathofimport;
  1086. }
  1087. /**
  1088. * Return value of server parameters
  1089. *
  1090. * @param string $filter Filter list on a particular value
  1091. * @return string Value for parameter
  1092. */
  1093. function getServerParametersValues($filter='')
  1094. {
  1095. $result=array();
  1096. $sql='SHOW VARIABLES';
  1097. if ($filter) $sql.=" LIKE '".addslashes($filter)."'";
  1098. $resql=$this->query($sql);
  1099. if ($resql)
  1100. {
  1101. $obj=$this->fetch_object($resql);
  1102. $result[$obj->Variable_name]=$obj->Value;
  1103. }
  1104. return $result;
  1105. }
  1106. /**
  1107. * Return value of server status
  1108. *
  1109. * @param string $filter Filter list on a particular value
  1110. * @return string Value for parameter
  1111. */
  1112. function getServerStatusValues($filter='')
  1113. {
  1114. $result=array();
  1115. $sql='SHOW STATUS';
  1116. if ($filter) $sql.=" LIKE '".addslashes($filter)."'";
  1117. $resql=$this->query($sql);
  1118. if ($resql)
  1119. {
  1120. $obj=$this->fetch_object($resql);
  1121. $result[$obj->Variable_name]=$obj->Value;
  1122. }
  1123. return $result;
  1124. }
  1125. }
  1126. ?>