mysqli.class.php 37 KB

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