mysqli.class.php 38 KB

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