mysqli.class.php 38 KB

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