mysqli.class.php 38 KB

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