dolibarr  9.0.0
mysqli.class.php
Go to the documentation of this file.
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@inodbox.com>
7  * Copyright (C) 2015 RaphaĆ«l Doursenaud <rdoursenaud@gpcsolutions.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <http://www.gnu.org/licenses/>.
21  */
22 
28 require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php';
29 
33 class DoliDBMysqli extends DoliDB
34 {
36  public $db;
38  public $type='mysqli';
40  const LABEL='MySQL or MariaDB';
42  const VERSIONMIN='5.0.3';
44  private $_results;
45 
57  function __construct($type, $host, $user, $pass, $name='', $port=0)
58  {
59  global $conf,$langs;
60 
61  // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static
62  if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set;
63  if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation;
64 
65  $this->database_user=$user;
66  $this->database_host=$host;
67  $this->database_port=$port;
68 
69  $this->transaction_opened=0;
70 
71  //print "Name DB: $host,$user,$pass,$name<br>";
72 
73  if (! class_exists('mysqli'))
74  {
75  $this->connected = false;
76  $this->ok = false;
77  $this->error="Mysqli PHP functions for using Mysqli driver are not available in this version of PHP. Try to use another driver.";
78  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);
79  }
80 
81  if (! $host)
82  {
83  $this->connected = false;
84  $this->ok = false;
85  $this->error=$langs->trans("ErrorWrongHostParameter");
86  dol_syslog(get_class($this)."::DoliDBMysqli : Connect error, wrong host parameters",LOG_ERR);
87  }
88 
89  // Try server connection
90  // We do not try to connect to database, only to server. Connect to database is done later in constrcutor
91  $this->db = $this->connect($host, $user, $pass, '', $port);
92 
93  if ($this->db->connect_errno) {
94  $this->connected = false;
95  $this->ok = false;
96  $this->error = $this->db->connect_error;
97  dol_syslog(get_class($this) . "::DoliDBMysqli Connect error: " . $this->error, LOG_ERR);
98  } else {
99  $this->connected = true;
100  $this->ok = true;
101  }
102 
103  // If server connection is ok, we try to connect to the database
104  if ($this->connected && $name)
105  {
106  if ($this->select_db($name))
107  {
108  $this->database_selected = true;
109  $this->database_name = $name;
110  $this->ok = true;
111 
112  // If client is old latin, we force utf8
113  $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
114  if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
115 
116  if ($this->db->character_set_name() != $clientmustbe) {
117  $this->db->set_charset($clientmustbe); // This set charset, but with a bad collation
118 
119  $collation = $conf->db->dolibarr_main_db_collation;
120  if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
121 
122  if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
123  }
124  }
125  else
126  {
127  $this->database_selected = false;
128  $this->database_name = '';
129  $this->ok = false;
130  $this->error=$this->error();
131  dol_syslog(get_class($this)."::DoliDBMysqli : Select_db error ".$this->error,LOG_ERR);
132  }
133  }
134  else
135  {
136  // Pas de selection de base demandee, ok ou ko
137  $this->database_selected = false;
138 
139  if ($this->connected)
140  {
141  // If client is old latin, we force utf8
142  $clientmustbe=empty($conf->db->dolibarr_main_db_character_set)?'utf8':$conf->db->dolibarr_main_db_character_set;
143  if (preg_match('/latin1/', $clientmustbe)) $clientmustbe='utf8';
144 
145  if ($this->db->character_set_name() != $clientmustbe) {
146  $this->db->set_charset($clientmustbe); // This set utf8_general_ci
147 
148  $collation = $conf->db->dolibarr_main_db_collation;
149  if (preg_match('/latin1/', $collation)) $collation='utf8_unicode_ci';
150 
151  if (! preg_match('/general/', $collation)) $this->db->query("SET collation_connection = ".$collation);
152  }
153  }
154  }
155  }
156 
157 
165  static function convertSQLFromMysql($line,$type='ddl')
166  {
167  return $line;
168  }
169 
170  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
177  function select_db($database)
178  {
179  // phpcs:enable
180  dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG);
181  return $this->db->select_db($database);
182  }
183 
184 
196  function connect($host, $login, $passwd, $name, $port = 0)
197  {
198  dol_syslog(get_class($this) . "::connect host=$host, port=$port, login=$login, passwd=--hidden--, name=$name", LOG_DEBUG);
199 
200  // Can also be
201  // mysqli::init(); mysql::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0'); mysqli::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
202  // return mysqli::real_connect($host, $user, $pass, $db, $port);
203  return new mysqli($host, $login, $passwd, $name, $port);
204  }
205 
211  function getVersion()
212  {
213  return $this->db->server_info;
214  }
215 
221  function getDriverInfo()
222  {
223  return $this->db->client_info;
224  }
225 
226 
233  function close()
234  {
235  if ($this->db)
236  {
237  if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR);
238  $this->connected=false;
239  return $this->db->close();
240  }
241  return false;
242  }
243 
253  function query($query,$usesavepoint=0,$type='auto')
254  {
255  global $conf;
256 
257  $query = trim($query);
258 
259  if (! in_array($query,array('BEGIN','COMMIT','ROLLBACK'))) dol_syslog('sql='.$query, LOG_DEBUG);
260 
261  if (! $this->database_name)
262  {
263  // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE)
264  $ret = $this->db->query($query);
265  }
266  else
267  {
268  $ret = $this->db->query($query);
269  }
270 
271  if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query))
272  {
273  // Si requete utilisateur, on la sauvegarde ainsi que son resultset
274  if (! $ret)
275  {
276  $this->lastqueryerror = $query;
277  $this->lasterror = $this->error();
278  $this->lasterrno = $this->errno();
279 
280  if ($conf->global->SYSLOG_LEVEL < LOG_DEBUG) dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); // Log of request was not yet done previously
281  dol_syslog(get_class($this)."::query SQL Error message: ".$this->lasterrno." ".$this->lasterror, LOG_ERR);
282  }
283  $this->lastquery=$query;
284  $this->_results = $ret;
285  }
286 
287  return $ret;
288  }
289 
290  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
297  function fetch_object($resultset)
298  {
299  // phpcs:enable
300  // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion
301  if (! is_object($resultset)) { $resultset=$this->_results; }
302  return $resultset->fetch_object();
303  }
304 
305 
306  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
313  function fetch_array($resultset)
314  {
315  // phpcs:enable
316  // If resultset not provided, we take the last used by connexion
317  if (! is_object($resultset)) { $resultset=$this->_results; }
318  return $resultset->fetch_array();
319  }
320 
321  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
328  function fetch_row($resultset)
329  {
330  // phpcs:enable
331  // If resultset not provided, we take the last used by connexion
332  if (! is_bool($resultset))
333  {
334  if (! is_object($resultset)) { $resultset=$this->_results; }
335  return $resultset->fetch_row();
336  }
337  else
338  {
339  // si le curseur est un booleen on retourne la valeur 0
340  return 0;
341  }
342  }
343 
344  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
352  function num_rows($resultset)
353  {
354  // phpcs:enable
355  // If resultset not provided, we take the last used by connexion
356  if (! is_object($resultset)) { $resultset=$this->_results; }
357  return $resultset->num_rows;
358  }
359 
360  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
368  function affected_rows($resultset)
369  {
370  // phpcs:enable
371  // If resultset not provided, we take the last used by connexion
372  if (! is_object($resultset)) { $resultset=$this->_results; }
373  // mysql necessite un link de base pour cette fonction contrairement
374  // a pqsql qui prend un resultset
375  return $this->db->affected_rows;
376  }
377 
378 
385  function free($resultset=null)
386  {
387  // If resultset not provided, we take the last used by connexion
388  if (! is_object($resultset)) { $resultset=$this->_results; }
389  // Si resultset en est un, on libere la memoire
390  if (is_object($resultset)) $resultset->free_result();
391  }
392 
399  function escape($stringtoencode)
400  {
401  return $this->db->real_escape_string($stringtoencode);
402  }
403 
409  function errno()
410  {
411  if (! $this->connected) {
412  // Si il y a eu echec de connexion, $this->db n'est pas valide.
413  return 'DB_ERROR_FAILED_TO_CONNECT';
414  } else {
415  // Constants to convert a MySql error code to a generic Dolibarr error code
416  $errorcode_map = array(
417  1004 => 'DB_ERROR_CANNOT_CREATE',
418  1005 => 'DB_ERROR_CANNOT_CREATE',
419  1006 => 'DB_ERROR_CANNOT_CREATE',
420  1007 => 'DB_ERROR_ALREADY_EXISTS',
421  1008 => 'DB_ERROR_CANNOT_DROP',
422  1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
423  1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
424  1044 => 'DB_ERROR_ACCESSDENIED',
425  1046 => 'DB_ERROR_NODBSELECTED',
426  1048 => 'DB_ERROR_CONSTRAINT',
427  1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
428  1051 => 'DB_ERROR_NOSUCHTABLE',
429  1054 => 'DB_ERROR_NOSUCHFIELD',
430  1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
431  1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
432  1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
433  1064 => 'DB_ERROR_SYNTAX',
434  1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
435  1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
436  1091 => 'DB_ERROR_NOSUCHFIELD',
437  1100 => 'DB_ERROR_NOT_LOCKED',
438  1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
439  1146 => 'DB_ERROR_NOSUCHTABLE',
440  1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
441  1216 => 'DB_ERROR_NO_PARENT',
442  1217 => 'DB_ERROR_CHILD_EXISTS',
443  1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating user already existing
444  1451 => 'DB_ERROR_CHILD_EXISTS'
445  );
446 
447  if (isset($errorcode_map[$this->db->errno])) {
448  return $errorcode_map[$this->db->errno];
449  }
450  $errno=$this->db->errno;
451  return ($errno?'DB_ERROR_'.$errno:'0');
452  }
453  }
454 
460  function error()
461  {
462  if (! $this->connected) {
463  // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
464  return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
465  }
466  else {
467  return $this->db->error;
468  }
469  }
470 
471  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
479  function last_insert_id($tab,$fieldid='rowid')
480  {
481  // phpcs:enable
482  return $this->db->insert_id;
483  }
484 
494  function encrypt($fieldorvalue, $withQuotes=0)
495  {
496  global $conf;
497 
498  // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
499  $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
500 
501  //Encryption key
502  $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
503 
504  $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":"");
505 
506  if ($cryptType && !empty($cryptKey))
507  {
508  if ($cryptType == 2)
509  {
510  $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
511  }
512  else if ($cryptType == 1)
513  {
514  $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')';
515  }
516  }
517 
518  return $return;
519  }
520 
527  function decrypt($value)
528  {
529  global $conf;
530 
531  // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
532  $cryptType = (!empty($conf->db->dolibarr_main_db_encryption)?$conf->db->dolibarr_main_db_encryption:0);
533 
534  //Encryption key
535  $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:'');
536 
537  $return = $value;
538 
539  if ($cryptType && !empty($cryptKey))
540  {
541  if ($cryptType == 2)
542  {
543  $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
544  }
545  else if ($cryptType == 1)
546  {
547  $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
548  }
549  }
550 
551  return $return;
552  }
553 
554 
555  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
561  function DDLGetConnectId()
562  {
563  // phpcs:enable
564  $resql=$this->query('SELECT CONNECTION_ID()');
565  if ($resql)
566  {
567  $row=$this->fetch_row($resql);
568  return $row[0];
569  }
570  else return '?';
571  }
572 
573  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
585  function DDLCreateDb($database,$charset='',$collation='',$owner='')
586  {
587  // phpcs:enable
588  if (empty($charset)) $charset=$this->forcecharset;
589  if (empty($collation)) $collation=$this->forcecollate;
590 
591  // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
592  $sql = "CREATE DATABASE `".$this->escape($database)."`";
593  $sql.= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
594 
595  dol_syslog($sql,LOG_DEBUG);
596  $ret=$this->query($sql);
597  if (! $ret)
598  {
599  // We try again for compatibility with Mysql < 4.1.1
600  $sql = "CREATE DATABASE `".$this->escape($database)."`";
601  dol_syslog($sql,LOG_DEBUG);
602  $ret=$this->query($sql);
603  }
604  return $ret;
605  }
606 
607  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
615  function DDLListTables($database, $table='')
616  {
617  // phpcs:enable
618  $listtables=array();
619 
620  $like = '';
621  if ($table) $like = "LIKE '".$table."'";
622  $sql="SHOW TABLES FROM ".$database." ".$like.";";
623  //print $sql;
624  $result = $this->query($sql);
625  if ($result)
626  {
627  while($row = $this->fetch_row($result))
628  {
629  $listtables[] = $row[0];
630  }
631  }
632  return $listtables;
633  }
634 
635  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
642  function DDLInfoTable($table)
643  {
644  // phpcs:enable
645  $infotables=array();
646 
647  $sql="SHOW FULL COLUMNS FROM ".$table.";";
648 
649  dol_syslog($sql,LOG_DEBUG);
650  $result = $this->query($sql);
651  if ($result)
652  {
653  while($row = $this->fetch_row($result))
654  {
655  $infotables[] = $row;
656  }
657  }
658  return $infotables;
659  }
660 
661  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
674  function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null)
675  {
676  // phpcs:enable
677  // FIXME: $fulltext_keys parameter is unused
678 
679  // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
680  // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
681  $sql = "CREATE TABLE ".$table."(";
682  $i=0;
683  foreach($fields as $field_name => $field_desc)
684  {
685  $sqlfields[$i] = $field_name." ";
686  $sqlfields[$i] .= $field_desc['type'];
687  if( preg_match("/^[^\s]/i",$field_desc['value'])) {
688  $sqlfields[$i] .= "(".$field_desc['value'].")";
689  }
690  if( preg_match("/^[^\s]/i",$field_desc['attribute'])) {
691  $sqlfields[$i] .= " ".$field_desc['attribute'];
692  }
693  if( preg_match("/^[^\s]/i",$field_desc['default']))
694  {
695  if ((preg_match("/null/i",$field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i",$field_desc['default']))) {
696  $sqlfields[$i] .= " default ".$field_desc['default'];
697  }
698  else {
699  $sqlfields[$i] .= " default '".$field_desc['default']."'";
700  }
701  }
702  if( preg_match("/^[^\s]/i",$field_desc['null'])) {
703  $sqlfields[$i] .= " ".$field_desc['null'];
704  }
705  if( preg_match("/^[^\s]/i",$field_desc['extra'])) {
706  $sqlfields[$i] .= " ".$field_desc['extra'];
707  }
708  $i++;
709  }
710  if($primary_key != "")
711  $pk = "primary key(".$primary_key.")";
712 
713  if(is_array($unique_keys)) {
714  $i = 0;
715  foreach($unique_keys as $key => $value)
716  {
717  $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')";
718  $i++;
719  }
720  }
721  if(is_array($keys))
722  {
723  $i = 0;
724  foreach($keys as $key => $value)
725  {
726  $sqlk[$i] = "KEY ".$key." (".$value.")";
727  $i++;
728  }
729  }
730  $sql .= implode(',',$sqlfields);
731  if($primary_key != "")
732  $sql .= ",".$pk;
733  if($unique_keys != "")
734  $sql .= ",".implode(',',$sqluq);
735  if(is_array($keys))
736  $sql .= ",".implode(',',$sqlk);
737  $sql .=") engine=".$type;
738 
739  if(! $this->query($sql))
740  return -1;
741  else
742  return 1;
743  }
744 
745  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
752  function DDLDropTable($table)
753  {
754  // phpcs:enable
755  $sql = "DROP TABLE ".$table;
756 
757  if (! $this->query($sql))
758  return -1;
759  else
760  return 1;
761  }
762 
763  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
771  function DDLDescTable($table,$field="")
772  {
773  // phpcs:enable
774  $sql="DESC ".$table." ".$field;
775 
776  dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG);
777  $this->_results = $this->query($sql);
778  return $this->_results;
779  }
780 
781  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
791  function DDLAddField($table,$field_name,$field_desc,$field_position="")
792  {
793  // phpcs:enable
794  // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
795  // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
796  $sql= "ALTER TABLE ".$table." ADD ".$field_name." ";
797  $sql.= $field_desc['type'];
798  if (preg_match("/^[^\s]/i",$field_desc['value']))
799  {
800  if (! in_array($field_desc['type'],array('date','datetime')))
801  {
802  $sql.= "(".$field_desc['value'].")";
803  }
804  }
805  if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i",$field_desc['attribute']))
806  {
807  $sql.= " ".$field_desc['attribute'];
808  }
809  if (isset($field_desc['null']) && preg_match("/^[^\s]/i",$field_desc['null']))
810  {
811  $sql.= " ".$field_desc['null'];
812  }
813  if (isset($field_desc['default']) && preg_match("/^[^\s]/i",$field_desc['default']))
814  {
815  if(preg_match("/null/i",$field_desc['default']))
816  $sql.= " default ".$field_desc['default'];
817  else
818  $sql.= " default '".$field_desc['default']."'";
819  }
820  if (isset($field_desc['extra']) && preg_match("/^[^\s]/i",$field_desc['extra']))
821  {
822  $sql.= " ".$field_desc['extra'];
823  }
824  $sql.= " ".$field_position;
825 
826  dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG);
827  if ($this->query($sql)) {
828  return 1;
829  }
830  return -1;
831  }
832 
833  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
842  function DDLUpdateField($table,$field_name,$field_desc)
843  {
844  // phpcs:enable
845  $sql = "ALTER TABLE ".$table;
846  $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
847  if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') {
848  $sql.="(".$field_desc['value'].")";
849  }
850  if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL')
851  {
852  // We will try to change format of column to NOT NULL. To be sure the ALTER works, we try to update fields that are NULL
853  if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text')
854  {
855  $sqlbis="UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
856  $this->query($sqlbis);
857  }
858  elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int')
859  {
860  $sqlbis="UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
861  $this->query($sqlbis);
862  }
863 
864  $sql.=" NOT NULL";
865  }
866 
867  if ($field_desc['default'] != '')
868  {
869  if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') $sql.=" DEFAULT ".$this->escape($field_desc['default']);
870  elseif ($field_desc['type'] == 'text') $sql.=" DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
871  }
872 
873  dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG);
874  if (! $this->query($sql))
875  return -1;
876  else
877  return 1;
878  }
879 
880  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
888  function DDLDropField($table,$field_name)
889  {
890  // phpcs:enable
891  $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`";
892  dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG);
893  if ($this->query($sql)) {
894  return 1;
895  }
896  $this->error=$this->lasterror();
897  return -1;
898  }
899 
900 
901  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
911  function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name)
912  {
913  // phpcs:enable
914  $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'";
915  dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
916  $resql=$this->query($sql);
917  if (! $resql)
918  {
919  if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS')
920  {
921  return -1;
922  }
923  else
924  {
925  // If user already exists, we continue to set permissions
926  dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
927  }
928  }
929  $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)."'";
930  dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
931  $resql=$this->query($sql);
932  if (! $resql)
933  {
934  return -1;
935  }
936 
937  $sql="FLUSH Privileges";
938 
939  dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
940  $resql=$this->query($sql);
941  if (! $resql)
942  {
943  return -1;
944  }
945 
946  return 1;
947  }
948 
956  function getDefaultCharacterSetDatabase()
957  {
958  $resql=$this->query('SHOW VARIABLES LIKE \'character_set_database\'');
959  if (!$resql)
960  {
961  // version Mysql < 4.1.1
962  return $this->forcecharset;
963  }
964  $liste=$this->fetch_array($resql);
965  $tmpval = $liste['Value'];
966 
967  return $tmpval;
968  }
969 
976  {
977  $resql=$this->query('SHOW CHARSET');
978  $liste = array();
979  if ($resql)
980  {
981  $i = 0;
982  while ($obj = $this->fetch_object($resql) )
983  {
984  $liste[$i]['charset'] = $obj->Charset;
985  $liste[$i]['description'] = $obj->Description;
986  $i++;
987  }
988  $this->free($resql);
989  } else {
990  // version Mysql < 4.1.1
991  return null;
992  }
993  return $liste;
994  }
995 
1003  {
1004  $resql=$this->query('SHOW VARIABLES LIKE \'collation_database\'');
1005  if (!$resql)
1006  {
1007  // version Mysql < 4.1.1
1008  return $this->forcecollate;
1009  }
1010  $liste=$this->fetch_array($resql);
1011  $tmpval = $liste['Value'];
1012 
1013  return $tmpval;
1014  }
1015 
1022  {
1023  $resql=$this->query('SHOW COLLATION');
1024  $liste = array();
1025  if ($resql)
1026  {
1027  $i = 0;
1028  while ($obj = $this->fetch_object($resql) )
1029  {
1030  $liste[$i]['collation'] = $obj->Collation;
1031  $i++;
1032  }
1033  $this->free($resql);
1034  } else {
1035  // version Mysql < 4.1.1
1036  return null;
1037  }
1038  return $liste;
1039  }
1040 
1046  function getPathOfDump()
1047  {
1048  $fullpathofdump='/pathtomysqldump/mysqldump';
1049 
1050  $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1051  if ($resql)
1052  {
1053  $liste=$this->fetch_array($resql);
1054  $basedir=$liste['Value'];
1055  $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump';
1056  }
1057  return $fullpathofdump;
1058  }
1059 
1065  function getPathOfRestore()
1066  {
1067  $fullpathofimport='/pathtomysql/mysql';
1068 
1069  $resql=$this->query('SHOW VARIABLES LIKE \'basedir\'');
1070  if ($resql)
1071  {
1072  $liste=$this->fetch_array($resql);
1073  $basedir=$liste['Value'];
1074  $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql';
1075  }
1076  return $fullpathofimport;
1077  }
1078 
1085  function getServerParametersValues($filter='')
1086  {
1087  $result=array();
1088 
1089  $sql='SHOW VARIABLES';
1090  if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1091  $resql=$this->query($sql);
1092  if ($resql)
1093  {
1094  while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1095  }
1096 
1097  return $result;
1098  }
1099 
1106  function getServerStatusValues($filter='')
1107  {
1108  $result=array();
1109 
1110  $sql='SHOW STATUS';
1111  if ($filter) $sql.=" LIKE '".$this->escape($filter)."'";
1112  $resql=$this->query($sql);
1113  if ($resql)
1114  {
1115  while($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value;
1116  }
1117 
1118  return $result;
1119  }
1120 }
getPathOfRestore()
Return full path of restore program.
lastqueryerror()
Return last query in error.
if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) if(! empty($conf->don->enabled) && $user->rights->societe->lire) if(! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) if(! empty($conf->facture->enabled) &&! empty($conf->commande->enabled) && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1053
getListOfCharacterSet()
Return list of available charset that can be used to store data in database.
$type
Database type.
getServerStatusValues($filter='')
Return value of server status (current indicators on memory, cache...)
escape($stringtoencode)
Escape a string to insert data.
lastquery()
Return last request executed with query()
fetch_row($resultset)
Return datas as an array.
getPathOfDump()
Return full path of dump program.
select_db($database)
Select a database.
Class to manage Dolibarr database access.
const LABEL
Database label.
last_insert_id($tab, $fieldid='rowid')
Get last ID after an insert INSERT.
lasterror()
Return last error label.
getServerParametersValues($filter='')
Return value of server parameters.
errno()
Return generic error code of last operation.
const VERSIONMIN
Version min database.
error()
Return description of last error.
fetch_object($resultset)
Renvoie la ligne courante (comme un objet) pour le curseur resultset.
connect($host, $login, $passwd, $name, $port=0)
Connect to server.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
type
Definition: viewcat.php:284
encrypt($fieldorvalue, $withQuotes=0)
Encrypt sensitive data in database Warning: This function includes the escape, so it must use direct ...
getDriverInfo()
Return version of database client driver.
query($query, $usesavepoint=0, $type='auto')
Execute a SQL request and return the resultset.
static convertSQLFromMysql($line, $type='ddl')
Convert a SQL request in Mysql syntax to native syntax.
close()
Close database connexion.
num_rows($resultset)
Return number of lines for result of a SELECT.
fetch_array($resultset)
Return datas as an array.
getDefaultCollationDatabase()
Return collation used in current database.
Class to manage Dolibarr database access for a MySQL database using the MySQLi extension.
lasterrno()
Return last error code.
__construct($type, $host, $user, $pass, $name='', $port=0)
Constructor.
affected_rows($resultset)
Renvoie le nombre de lignes dans le resultat d&#39;une requete INSERT, DELETE ou UPDATE.
getVersion()
Return version of database server.
free($resultset=null)
Libere le dernier resultset utilise sur cette connexion.
getListOfCollation()
Return list of available collation that can be used for database.