mysqli.class.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. // Added by MMI Mathieu Moulin iProspective
  323. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  324. /**
  325. * Return datas as an array
  326. *
  327. * @param mysqli_result $resultset Resultset of request
  328. * @return array|null Array or null if KO or end of cursor
  329. */
  330. public function fetch_assoc($resultset)
  331. {
  332. // phpcs:enable
  333. // If resultset not provided, we take the last used by connexion
  334. if (!is_object($resultset)) {
  335. $resultset = $this->_results;
  336. }
  337. return $resultset->fetch_assoc();
  338. }
  339. // Added by MMI Mathieu Moulin iProspective
  340. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  341. /**
  342. * Return datas as an array
  343. *
  344. * @param mysqli_result $resultset Resultset of request
  345. * @return array Array or null if KO or end of cursor
  346. */
  347. public function fetch_assoc_all($resultset)
  348. {
  349. $l = [];
  350. while($row=$this->fetch_assoc($resultset))
  351. $l[] = $row;
  352. return $l;
  353. }
  354. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  355. /**
  356. * Return datas as an array
  357. *
  358. * @param mysqli_result $resultset Resultset of request
  359. * @return array|null Array or null if KO or end of cursor
  360. */
  361. public function fetch_array($resultset)
  362. {
  363. // phpcs:enable
  364. // If resultset not provided, we take the last used by connexion
  365. if (!is_object($resultset)) {
  366. $resultset = $this->_results;
  367. }
  368. return $resultset->fetch_array();
  369. }
  370. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  371. /**
  372. * Return datas as an array
  373. *
  374. * @param mysqli_result $resultset Resultset of request
  375. * @return array|null|int Array or null if KO or end of cursor or 0 if resultset is bool
  376. */
  377. public function fetch_row($resultset)
  378. {
  379. // phpcs:enable
  380. // If resultset not provided, we take the last used by connexion
  381. if (!is_bool($resultset)) {
  382. if (!is_object($resultset)) {
  383. $resultset = $this->_results;
  384. }
  385. return $resultset->fetch_row();
  386. } else {
  387. // si le curseur est un booleen on retourne la valeur 0
  388. return 0;
  389. }
  390. }
  391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  392. /**
  393. * Return number of lines for result of a SELECT
  394. *
  395. * @param mysqli_result $resultset Resulset of requests
  396. * @return int Nb of lines
  397. * @see affected_rows()
  398. */
  399. public function num_rows($resultset)
  400. {
  401. // phpcs:enable
  402. // If resultset not provided, we take the last used by connexion
  403. if (!is_object($resultset)) {
  404. $resultset = $this->_results;
  405. }
  406. return $resultset->num_rows;
  407. }
  408. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  409. /**
  410. * Return the number of lines in the result of a request INSERT, DELETE or UPDATE
  411. *
  412. * @param mysqli_result $resultset Curseur de la requete voulue
  413. * @return int Number of lines
  414. * @see num_rows()
  415. */
  416. public function affected_rows($resultset)
  417. {
  418. // phpcs:enable
  419. // If resultset not provided, we take the last used by connexion
  420. if (!is_object($resultset)) {
  421. $resultset = $this->_results;
  422. }
  423. // mysql necessite un link de base pour cette fonction contrairement
  424. // a pqsql qui prend un resultset
  425. return $this->db->affected_rows;
  426. }
  427. /**
  428. * Libere le dernier resultset utilise sur cette connexion
  429. *
  430. * @param mysqli_result $resultset Curseur de la requete voulue
  431. * @return void
  432. */
  433. public function free($resultset = null)
  434. {
  435. // If resultset not provided, we take the last used by connexion
  436. if (!is_object($resultset)) {
  437. $resultset = $this->_results;
  438. }
  439. // Si resultset en est un, on libere la memoire
  440. if (is_object($resultset)) {
  441. $resultset->free_result();
  442. }
  443. }
  444. /**
  445. * Escape a string to insert data
  446. *
  447. * @param string $stringtoencode String to escape
  448. * @return string String escaped
  449. */
  450. public function escape($stringtoencode)
  451. {
  452. return $this->db->real_escape_string((string) $stringtoencode);
  453. }
  454. /**
  455. * Escape a string to insert data
  456. *
  457. * @param string $stringtoencode String to escape
  458. * @return string String escaped
  459. * @deprecated
  460. */
  461. public function escapeunderscore($stringtoencode)
  462. {
  463. return str_replace('_', '\_', (string) $stringtoencode);
  464. }
  465. /**
  466. * Escape a string to insert data into a like
  467. *
  468. * @param string $stringtoencode String to escape
  469. * @return string String escaped
  470. */
  471. public function escapeforlike($stringtoencode)
  472. {
  473. return str_replace(array('_', '\\', '%'), array('\_', '\\\\', '\%'), (string) $stringtoencode);
  474. }
  475. /**
  476. * Return generic error code of last operation.
  477. *
  478. * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...)
  479. */
  480. public function errno()
  481. {
  482. if (!$this->connected) {
  483. // Si il y a eu echec de connexion, $this->db n'est pas valide.
  484. return 'DB_ERROR_FAILED_TO_CONNECT';
  485. } else {
  486. // Constants to convert a MySql error code to a generic Dolibarr error code
  487. $errorcode_map = array(
  488. 1004 => 'DB_ERROR_CANNOT_CREATE',
  489. 1005 => 'DB_ERROR_CANNOT_CREATE',
  490. 1006 => 'DB_ERROR_CANNOT_CREATE',
  491. 1007 => 'DB_ERROR_ALREADY_EXISTS',
  492. 1008 => 'DB_ERROR_CANNOT_DROP',
  493. 1022 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  494. 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP',
  495. 1044 => 'DB_ERROR_ACCESSDENIED',
  496. 1046 => 'DB_ERROR_NODBSELECTED',
  497. 1048 => 'DB_ERROR_CONSTRAINT',
  498. 1050 => 'DB_ERROR_TABLE_ALREADY_EXISTS',
  499. 1051 => 'DB_ERROR_NOSUCHTABLE',
  500. 1054 => 'DB_ERROR_NOSUCHFIELD',
  501. 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS',
  502. 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS',
  503. 1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS',
  504. 1064 => 'DB_ERROR_SYNTAX',
  505. 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS',
  506. 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY',
  507. 1091 => 'DB_ERROR_NOSUCHFIELD',
  508. 1100 => 'DB_ERROR_NOT_LOCKED',
  509. 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW',
  510. 1146 => 'DB_ERROR_NOSUCHTABLE',
  511. 1215 => 'DB_ERROR_CANNOT_ADD_FOREIGN_KEY_CONSTRAINT',
  512. 1216 => 'DB_ERROR_NO_PARENT',
  513. 1217 => 'DB_ERROR_CHILD_EXISTS',
  514. 1396 => 'DB_ERROR_USER_ALREADY_EXISTS', // When creating a user that already existing
  515. 1451 => 'DB_ERROR_CHILD_EXISTS',
  516. 1826 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'
  517. );
  518. if (isset($errorcode_map[$this->db->errno])) {
  519. return $errorcode_map[$this->db->errno];
  520. }
  521. $errno = $this->db->errno;
  522. return ($errno ? 'DB_ERROR_'.$errno : '0');
  523. }
  524. }
  525. /**
  526. * Return description of last error
  527. *
  528. * @return string Error text
  529. */
  530. public function error()
  531. {
  532. if (!$this->connected) {
  533. // Si il y a eu echec de connexion, $this->db n'est pas valide pour mysqli_error.
  534. return 'Not connected. Check setup parameters in conf/conf.php file and your mysql client and server versions';
  535. } else {
  536. return $this->db->error;
  537. }
  538. }
  539. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  540. /**
  541. * Get last ID after an insert INSERT
  542. *
  543. * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql
  544. * @param string $fieldid Field name
  545. * @return int|string Id of row
  546. */
  547. public function last_insert_id($tab, $fieldid = 'rowid')
  548. {
  549. // phpcs:enable
  550. return $this->db->insert_id;
  551. }
  552. /**
  553. * Encrypt sensitive data in database
  554. * Warning: This function includes the escape and add the SQL simple quotes on strings.
  555. *
  556. * @param string $fieldorvalue Field name or value to encrypt
  557. * @param int $withQuotes Return string including the SQL simple quotes. This param must always be 1 (Value 0 is bugged and deprecated).
  558. * @return string XXX(field) or XXX('value') or field or 'value'
  559. */
  560. public function encrypt($fieldorvalue, $withQuotes = 1)
  561. {
  562. global $conf;
  563. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  564. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
  565. //Encryption key
  566. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  567. $escapedstringwithquotes = ($withQuotes ? "'" : "").$this->escape($fieldorvalue).($withQuotes ? "'" : "");
  568. if ($cryptType && !empty($cryptKey)) {
  569. if ($cryptType == 2) {
  570. $escapedstringwithquotes = "AES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  571. } elseif ($cryptType == 1) {
  572. $escapedstringwithquotes = "DES_ENCRYPT(".$escapedstringwithquotes.", '".$this->escape($cryptKey)."')";
  573. }
  574. }
  575. return $escapedstringwithquotes;
  576. }
  577. /**
  578. * Decrypt sensitive data in database
  579. *
  580. * @param string $value Value to decrypt
  581. * @return string Decrypted value if used
  582. */
  583. public function decrypt($value)
  584. {
  585. global $conf;
  586. // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption)
  587. $cryptType = (!empty($conf->db->dolibarr_main_db_encryption) ? $conf->db->dolibarr_main_db_encryption : 0);
  588. //Encryption key
  589. $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey) ? $conf->db->dolibarr_main_db_cryptkey : '');
  590. $return = $value;
  591. if ($cryptType && !empty($cryptKey)) {
  592. if ($cryptType == 2) {
  593. $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  594. } elseif ($cryptType == 1) {
  595. $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')';
  596. }
  597. }
  598. return $return;
  599. }
  600. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  601. /**
  602. * Return connexion ID
  603. *
  604. * @return string Id connexion
  605. */
  606. public function DDLGetConnectId()
  607. {
  608. // phpcs:enable
  609. $resql = $this->query('SELECT CONNECTION_ID()');
  610. if ($resql) {
  611. $row = $this->fetch_row($resql);
  612. return $row[0];
  613. } else {
  614. return '?';
  615. }
  616. }
  617. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  618. /**
  619. * Create a new database
  620. * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated
  621. * We force to create database with charset this->forcecharset and collate this->forcecollate
  622. *
  623. * @param string $database Database name to create
  624. * @param string $charset Charset used to store data
  625. * @param string $collation Charset used to sort data
  626. * @param string $owner Username of database owner
  627. * @return bool|mysqli_result resource defined if OK, null if KO
  628. */
  629. public function DDLCreateDb($database, $charset = '', $collation = '', $owner = '')
  630. {
  631. // phpcs:enable
  632. if (empty($charset)) {
  633. $charset = $this->forcecharset;
  634. }
  635. if (empty($collation)) {
  636. $collation = $this->forcecollate;
  637. }
  638. // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci
  639. $sql = "CREATE DATABASE `".$this->escape($database)."`";
  640. $sql .= " DEFAULT CHARACTER SET `".$this->escape($charset)."` DEFAULT COLLATE `".$this->escape($collation)."`";
  641. dol_syslog($sql, LOG_DEBUG);
  642. $ret = $this->query($sql);
  643. if (!$ret) {
  644. // We try again for compatibility with Mysql < 4.1.1
  645. $sql = "CREATE DATABASE `".$this->escape($database)."`";
  646. dol_syslog($sql, LOG_DEBUG);
  647. $ret = $this->query($sql);
  648. }
  649. return $ret;
  650. }
  651. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  652. /**
  653. * List tables into a database
  654. *
  655. * @param string $database Name of database
  656. * @param string $table Nmae of table filter ('xxx%')
  657. * @return array List of tables in an array
  658. */
  659. public function DDLListTables($database, $table = '')
  660. {
  661. // phpcs:enable
  662. $listtables = array();
  663. $like = '';
  664. if ($table) {
  665. $tmptable = preg_replace('/[^a-z0-9\.\-\_%]/i', '', $table);
  666. $like = "LIKE '".$this->escape($tmptable)."'";
  667. }
  668. $tmpdatabase = preg_replace('/[^a-z0-9\.\-\_]/i', '', $database);
  669. $sql = "SHOW TABLES FROM `".$tmpdatabase."` ".$like.";";
  670. //print $sql;
  671. $result = $this->query($sql);
  672. if ($result) {
  673. while ($row = $this->fetch_row($result)) {
  674. $listtables[] = $row[0];
  675. }
  676. }
  677. return $listtables;
  678. }
  679. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  680. /**
  681. * List information of columns into a table.
  682. *
  683. * @param string $table Name of table
  684. * @return array Tableau des informations des champs de la table
  685. */
  686. public function DDLInfoTable($table)
  687. {
  688. // phpcs:enable
  689. $infotables = array();
  690. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  691. $sql = "SHOW FULL COLUMNS FROM ".$tmptable.";";
  692. dol_syslog($sql, LOG_DEBUG);
  693. $result = $this->query($sql);
  694. if ($result) {
  695. while ($row = $this->fetch_row($result)) {
  696. $infotables[] = $row;
  697. }
  698. }
  699. return $infotables;
  700. }
  701. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  702. /**
  703. * Create a table into database
  704. *
  705. * @param string $table Name of table
  706. * @param array $fields Tableau associatif [nom champ][tableau des descriptions]
  707. * @param string $primary_key Nom du champ qui sera la clef primaire
  708. * @param string $type Type de la table
  709. * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur
  710. * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext
  711. * @param array $keys Tableau des champs cles noms => valeur
  712. * @return int <0 if KO, >=0 if OK
  713. */
  714. public function DDLCreateTable($table, $fields, $primary_key, $type, $unique_keys = null, $fulltext_keys = null, $keys = null)
  715. {
  716. // phpcs:enable
  717. // FIXME: $fulltext_keys parameter is unused
  718. // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra
  719. // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  720. $sql = "CREATE TABLE ".$table."(";
  721. $i = 0;
  722. $sqlfields = array();
  723. foreach ($fields as $field_name => $field_desc) {
  724. $sqlfields[$i] = $field_name." ";
  725. $sqlfields[$i] .= $field_desc['type'];
  726. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  727. $sqlfields[$i] .= "(".$field_desc['value'].")";
  728. }
  729. if (preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  730. $sqlfields[$i] .= " ".$field_desc['attribute'];
  731. }
  732. if (preg_match("/^[^\s]/i", $field_desc['default'])) {
  733. if ((preg_match("/null/i", $field_desc['default'])) || (preg_match("/CURRENT_TIMESTAMP/i", $field_desc['default']))) {
  734. $sqlfields[$i] .= " default ".$field_desc['default'];
  735. } else {
  736. $sqlfields[$i] .= " default '".$this->escape($field_desc['default'])."'";
  737. }
  738. }
  739. if (preg_match("/^[^\s]/i", $field_desc['null'])) {
  740. $sqlfields[$i] .= " ".$field_desc['null'];
  741. }
  742. if (preg_match("/^[^\s]/i", $field_desc['extra'])) {
  743. $sqlfields[$i] .= " ".$field_desc['extra'];
  744. }
  745. $i++;
  746. }
  747. if ($primary_key != "") {
  748. $pk = "primary key(".$primary_key.")";
  749. }
  750. if (is_array($unique_keys)) {
  751. $i = 0;
  752. foreach ($unique_keys as $key => $value) {
  753. $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$this->escape($value)."')";
  754. $i++;
  755. }
  756. }
  757. if (is_array($keys)) {
  758. $i = 0;
  759. foreach ($keys as $key => $value) {
  760. $sqlk[$i] = "KEY ".$key." (".$value.")";
  761. $i++;
  762. }
  763. }
  764. $sql .= implode(',', $sqlfields);
  765. if ($primary_key != "") {
  766. $sql .= ",".$pk;
  767. }
  768. if ($unique_keys != "") {
  769. $sql .= ",".implode(',', $sqluq);
  770. }
  771. if (is_array($keys)) {
  772. $sql .= ",".implode(',', $sqlk);
  773. }
  774. $sql .= ") engine=".$type;
  775. if (!$this->query($sql)) {
  776. return -1;
  777. } else {
  778. return 1;
  779. }
  780. }
  781. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  782. /**
  783. * Drop a table into database
  784. *
  785. * @param string $table Name of table
  786. * @return int <0 if KO, >=0 if OK
  787. */
  788. public function DDLDropTable($table)
  789. {
  790. // phpcs:enable
  791. $tmptable = preg_replace('/[^a-z0-9\.\-\_]/i', '', $table);
  792. $sql = "DROP TABLE ".$tmptable;
  793. if (!$this->query($sql)) {
  794. return -1;
  795. } else {
  796. return 1;
  797. }
  798. }
  799. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  800. /**
  801. * Return a pointer of line with description of a table or field
  802. *
  803. * @param string $table Name of table
  804. * @param string $field Optionnel : Name of field if we want description of field
  805. * @return bool|mysqli_result Resultset x (x->Field, x->Type, ...)
  806. */
  807. public function DDLDescTable($table, $field = "")
  808. {
  809. // phpcs:enable
  810. $sql = "DESC ".$table." ".$field;
  811. dol_syslog(get_class($this)."::DDLDescTable ".$sql, LOG_DEBUG);
  812. $this->_results = $this->query($sql);
  813. return $this->_results;
  814. }
  815. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  816. /**
  817. * Create a new field into table
  818. *
  819. * @param string $table Name of table
  820. * @param string $field_name Name of field to add
  821. * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre]
  822. * @param string $field_position Optionnel ex.: "after champtruc"
  823. * @return int <0 if KO, >0 if OK
  824. */
  825. public function DDLAddField($table, $field_name, $field_desc, $field_position = "")
  826. {
  827. // phpcs:enable
  828. // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra
  829. // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment');
  830. $sql = "ALTER TABLE ".$table." ADD ".$field_name." ";
  831. $sql .= $field_desc['type'];
  832. if (preg_match("/^[^\s]/i", $field_desc['value'])) {
  833. if (!in_array($field_desc['type'], array('date', 'datetime')) && $field_desc['value']) {
  834. $sql .= "(".$field_desc['value'].")";
  835. }
  836. }
  837. if (isset($field_desc['attribute']) && preg_match("/^[^\s]/i", $field_desc['attribute'])) {
  838. $sql .= " ".$field_desc['attribute'];
  839. }
  840. if (isset($field_desc['null']) && preg_match("/^[^\s]/i", $field_desc['null'])) {
  841. $sql .= " ".$field_desc['null'];
  842. }
  843. if (isset($field_desc['default']) && preg_match("/^[^\s]/i", $field_desc['default'])) {
  844. if (preg_match("/null/i", $field_desc['default'])) {
  845. $sql .= " default ".$field_desc['default'];
  846. } else {
  847. $sql .= " default '".$this->escape($field_desc['default'])."'";
  848. }
  849. }
  850. if (isset($field_desc['extra']) && preg_match("/^[^\s]/i", $field_desc['extra'])) {
  851. $sql .= " ".$field_desc['extra'];
  852. }
  853. $sql .= " ".$field_position;
  854. dol_syslog(get_class($this)."::DDLAddField ".$sql, LOG_DEBUG);
  855. if ($this->query($sql)) {
  856. return 1;
  857. }
  858. return -1;
  859. }
  860. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  861. /**
  862. * Update format of a field into a table
  863. *
  864. * @param string $table Name of table
  865. * @param string $field_name Name of field to modify
  866. * @param string $field_desc Array with description of field format
  867. * @return int <0 if KO, >0 if OK
  868. */
  869. public function DDLUpdateField($table, $field_name, $field_desc)
  870. {
  871. // phpcs:enable
  872. $sql = "ALTER TABLE ".$table;
  873. $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type'];
  874. if (in_array($field_desc['type'], array('double', 'tinyint', 'int', 'varchar')) && $field_desc['value']) {
  875. $sql .= "(".$field_desc['value'].")";
  876. }
  877. if ($field_desc['null'] == 'not null' || $field_desc['null'] == 'NOT NULL') {
  878. // 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
  879. if ($field_desc['type'] == 'varchar' || $field_desc['type'] == 'text') {
  880. $sqlbis = "UPDATE ".$table." SET ".$field_name." = '".$this->escape($field_desc['default'] ? $field_desc['default'] : '')."' WHERE ".$field_name." IS NULL";
  881. $this->query($sqlbis);
  882. } elseif ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  883. $sqlbis = "UPDATE ".$table." SET ".$field_name." = ".((int) $this->escape($field_desc['default'] ? $field_desc['default'] : 0))." WHERE ".$field_name." IS NULL";
  884. $this->query($sqlbis);
  885. }
  886. $sql .= " NOT NULL";
  887. }
  888. if ($field_desc['default'] != '') {
  889. if ($field_desc['type'] == 'double' || $field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int') {
  890. $sql .= " DEFAULT ".$this->escape($field_desc['default']);
  891. } elseif ($field_desc['type'] != 'text') {
  892. $sql .= " DEFAULT '".$this->escape($field_desc['default'])."'"; // Default not supported on text fields
  893. }
  894. }
  895. dol_syslog(get_class($this)."::DDLUpdateField ".$sql, LOG_DEBUG);
  896. if (!$this->query($sql)) {
  897. return -1;
  898. } else {
  899. return 1;
  900. }
  901. }
  902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  903. /**
  904. * Drop a field from table
  905. *
  906. * @param string $table Name of table
  907. * @param string $field_name Name of field to drop
  908. * @return int <0 if KO, >0 if OK
  909. */
  910. public function DDLDropField($table, $field_name)
  911. {
  912. // phpcs:enable
  913. $tmp_field_name = preg_replace('/[^a-z0-9\.\-\_]/i', '', $field_name);
  914. $sql = "ALTER TABLE ".$table." DROP COLUMN `".$tmp_field_name."`";
  915. if ($this->query($sql)) {
  916. return 1;
  917. }
  918. $this->error = $this->lasterror();
  919. return -1;
  920. }
  921. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  922. /**
  923. * Create a user and privileges to connect to database (even if database does not exists yet)
  924. *
  925. * @param string $dolibarr_main_db_host Ip server or '%'
  926. * @param string $dolibarr_main_db_user Nom user a creer
  927. * @param string $dolibarr_main_db_pass Mot de passe user a creer
  928. * @param string $dolibarr_main_db_name Database name where user must be granted
  929. * @return int <0 if KO, >=0 if OK
  930. */
  931. public function DDLCreateUser($dolibarr_main_db_host, $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name)
  932. {
  933. // phpcs:enable
  934. $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
  935. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  936. $resql = $this->query($sql);
  937. if (!$resql) {
  938. if ($this->lasterrno != 'DB_ERROR_USER_ALREADY_EXISTS') {
  939. return -1;
  940. } else {
  941. // If user already exists, we continue to set permissions
  942. dol_syslog(get_class($this)."::DDLCreateUser sql=".$sql, LOG_WARNING);
  943. }
  944. }
  945. // Redo with localhost forced (sometimes user is created on %)
  946. $sql = "CREATE USER '".$this->escape($dolibarr_main_db_user)."'@'localhost' IDENTIFIED BY '".$this->escape($dolibarr_main_db_pass)."'";
  947. $resql = $this->query($sql);
  948. $sql = "GRANT ALL PRIVILEGES ON ".$this->escape($dolibarr_main_db_name).".* TO '".$this->escape($dolibarr_main_db_user)."'@'".$this->escape($dolibarr_main_db_host)."'";
  949. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log
  950. $resql = $this->query($sql);
  951. if (!$resql) {
  952. $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)."'";
  953. return -1;
  954. }
  955. $sql = "FLUSH Privileges";
  956. dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG);
  957. $resql = $this->query($sql);
  958. if (!$resql) {
  959. return -1;
  960. }
  961. return 1;
  962. }
  963. /**
  964. * Return charset used to store data in current database
  965. * 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";)
  966. *
  967. * @return string Charset
  968. * @see getDefaultCollationDatabase()
  969. */
  970. public function getDefaultCharacterSetDatabase()
  971. {
  972. $resql = $this->query('SHOW VARIABLES LIKE \'character_set_database\'');
  973. if (!$resql) {
  974. // version Mysql < 4.1.1
  975. return $this->forcecharset;
  976. }
  977. $liste = $this->fetch_array($resql);
  978. $tmpval = $liste['Value'];
  979. return $tmpval;
  980. }
  981. /**
  982. * Return list of available charset that can be used to store data in database
  983. *
  984. * @return array|null List of Charset
  985. */
  986. public function getListOfCharacterSet()
  987. {
  988. $resql = $this->query('SHOW CHARSET');
  989. $liste = array();
  990. if ($resql) {
  991. $i = 0;
  992. while ($obj = $this->fetch_object($resql)) {
  993. $liste[$i]['charset'] = $obj->Charset;
  994. $liste[$i]['description'] = $obj->Description;
  995. $i++;
  996. }
  997. $this->free($resql);
  998. } else {
  999. // version Mysql < 4.1.1
  1000. return null;
  1001. }
  1002. return $liste;
  1003. }
  1004. /**
  1005. * Return collation used in current database
  1006. *
  1007. * @return string Collation value
  1008. * @see getDefaultCharacterSetDatabase()
  1009. */
  1010. public function getDefaultCollationDatabase()
  1011. {
  1012. $resql = $this->query('SHOW VARIABLES LIKE \'collation_database\'');
  1013. if (!$resql) {
  1014. // version Mysql < 4.1.1
  1015. return $this->forcecollate;
  1016. }
  1017. $liste = $this->fetch_array($resql);
  1018. $tmpval = $liste['Value'];
  1019. return $tmpval;
  1020. }
  1021. /**
  1022. * Return list of available collation that can be used for database
  1023. *
  1024. * @return array|null Liste of Collation
  1025. */
  1026. public function getListOfCollation()
  1027. {
  1028. $resql = $this->query('SHOW COLLATION');
  1029. $liste = array();
  1030. if ($resql) {
  1031. $i = 0;
  1032. while ($obj = $this->fetch_object($resql)) {
  1033. $liste[$i]['collation'] = $obj->Collation;
  1034. $i++;
  1035. }
  1036. $this->free($resql);
  1037. } else {
  1038. // version Mysql < 4.1.1
  1039. return null;
  1040. }
  1041. return $liste;
  1042. }
  1043. /**
  1044. * Return full path of dump program
  1045. *
  1046. * @return string Full path of dump program
  1047. */
  1048. public function getPathOfDump()
  1049. {
  1050. $fullpathofdump = '/pathtomysqldump/mysqldump';
  1051. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1052. if ($resql) {
  1053. $liste = $this->fetch_array($resql);
  1054. $basedir = $liste['Value'];
  1055. $fullpathofdump = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysqldump';
  1056. }
  1057. return $fullpathofdump;
  1058. }
  1059. /**
  1060. * Return full path of restore program
  1061. *
  1062. * @return string Full path of restore program
  1063. */
  1064. public function getPathOfRestore()
  1065. {
  1066. $fullpathofimport = '/pathtomysql/mysql';
  1067. $resql = $this->query('SHOW VARIABLES LIKE \'basedir\'');
  1068. if ($resql) {
  1069. $liste = $this->fetch_array($resql);
  1070. $basedir = $liste['Value'];
  1071. $fullpathofimport = $basedir.(preg_match('/\/$/', $basedir) ? '' : '/').'bin/mysql';
  1072. }
  1073. return $fullpathofimport;
  1074. }
  1075. /**
  1076. * Return value of server parameters
  1077. *
  1078. * @param string $filter Filter list on a particular value
  1079. * @return array Array of key-values (key=>value)
  1080. */
  1081. public function getServerParametersValues($filter = '')
  1082. {
  1083. $result = array();
  1084. $sql = 'SHOW VARIABLES';
  1085. if ($filter) {
  1086. $sql .= " LIKE '".$this->escape($filter)."'";
  1087. }
  1088. $resql = $this->query($sql);
  1089. if ($resql) {
  1090. while ($obj = $this->fetch_object($resql)) {
  1091. $result[$obj->Variable_name] = $obj->Value;
  1092. }
  1093. }
  1094. return $result;
  1095. }
  1096. /**
  1097. * Return value of server status (current indicators on memory, cache...)
  1098. *
  1099. * @param string $filter Filter list on a particular value
  1100. * @return array Array of key-values (key=>value)
  1101. */
  1102. public function getServerStatusValues($filter = '')
  1103. {
  1104. $result = array();
  1105. $sql = 'SHOW STATUS';
  1106. if ($filter) {
  1107. $sql .= " LIKE '".$this->escape($filter)."'";
  1108. }
  1109. $resql = $this->query($sql);
  1110. if ($resql) {
  1111. while ($obj = $this->fetch_object($resql)) {
  1112. $result[$obj->Variable_name] = $obj->Value;
  1113. }
  1114. }
  1115. return $result;
  1116. }
  1117. }