Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1732 lines
44 KiB

1 year ago
1 year ago
  1. <?php
  2. /**
  3. * @copyright Copyright (C) 2020, Friendica
  4. *
  5. * @license GNU AGPL version 3 or any later version
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as
  9. * published by the Free Software Foundation, either version 3 of the
  10. * License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. *
  20. */
  21. namespace Friendica\Database;
  22. use Friendica\Core\Config\Cache;
  23. use Friendica\Core\System;
  24. use Friendica\Network\HTTPException\InternalServerErrorException;
  25. use Friendica\Util\DateTimeFormat;
  26. use Friendica\Util\Profiler;
  27. use mysqli;
  28. use mysqli_result;
  29. use mysqli_stmt;
  30. use PDO;
  31. use PDOException;
  32. use PDOStatement;
  33. use Psr\Log\LoggerInterface;
  34. /**
  35. * This class is for the low level database stuff that does driver specific things.
  36. */
  37. class Database
  38. {
  39. const PDO = 'pdo';
  40. const MYSQLI = 'mysqli';
  41. const INSERT_DEFAULT = 0;
  42. const INSERT_UPDATE = 1;
  43. const INSERT_IGNORE = 2;
  44. protected $connected = false;
  45. /**
  46. * @var Cache
  47. */
  48. protected $configCache;
  49. /**
  50. * @var Profiler
  51. */
  52. protected $profiler;
  53. /**
  54. * @var LoggerInterface
  55. */
  56. protected $logger;
  57. protected $server_info = '';
  58. /** @var PDO|mysqli */
  59. protected $connection;
  60. protected $driver;
  61. protected $pdo_emulate_prepares = false;
  62. private $error = false;
  63. private $errorno = 0;
  64. private $affected_rows = 0;
  65. protected $in_transaction = false;
  66. protected $in_retrial = false;
  67. protected $testmode = false;
  68. private $relation = [];
  69. public function __construct(Cache $configCache, Profiler $profiler, LoggerInterface $logger)
  70. {
  71. // We are storing these values for being able to perform a reconnect
  72. $this->configCache = $configCache;
  73. $this->profiler = $profiler;
  74. $this->logger = $logger;
  75. $this->connect();
  76. if ($this->isConnected()) {
  77. // Loads DB_UPDATE_VERSION constant
  78. DBStructure::definition($configCache->get('system', 'basepath'), false);
  79. }
  80. }
  81. public function connect()
  82. {
  83. if (!is_null($this->connection) && $this->connected()) {
  84. return $this->connected;
  85. }
  86. // Reset connected state
  87. $this->connected = false;
  88. $port = 0;
  89. $serveraddr = trim($this->configCache->get('database', 'hostname'));
  90. $serverdata = explode(':', $serveraddr);
  91. $server = $serverdata[0];
  92. if (count($serverdata) > 1) {
  93. $port = trim($serverdata[1]);
  94. }
  95. if (!empty(trim($this->configCache->get('database', 'port')))) {
  96. $port = trim($this->configCache->get('database', 'port'));
  97. }
  98. $server = trim($server);
  99. $user = trim($this->configCache->get('database', 'username'));
  100. $pass = trim($this->configCache->get('database', 'password'));
  101. $db = trim($this->configCache->get('database', 'database'));
  102. $charset = trim($this->configCache->get('database', 'charset'));
  103. if (!(strlen($server) && strlen($user))) {
  104. return false;
  105. }
  106. $persistent = (bool)$this->configCache->get('database', 'persistent');
  107. $this->pdo_emulate_prepares = (bool)$this->configCache->get('database', 'pdo_emulate_prepares');
  108. if (!$this->configCache->get('database', 'disable_pdo') && class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
  109. $this->driver = self::PDO;
  110. $connect = "mysql:host=" . $server . ";dbname=" . $db;
  111. if ($port > 0) {
  112. $connect .= ";port=" . $port;
  113. }
  114. if ($charset) {
  115. $connect .= ";charset=" . $charset;
  116. }
  117. try {
  118. $this->connection = @new PDO($connect, $user, $pass, [PDO::ATTR_PERSISTENT => $persistent]);
  119. $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
  120. $this->connected = true;
  121. } catch (PDOException $e) {
  122. $this->connected = false;
  123. }
  124. }
  125. if (!$this->connected && class_exists('\mysqli')) {
  126. $this->driver = self::MYSQLI;
  127. if ($port > 0) {
  128. $this->connection = @new mysqli($server, $user, $pass, $db, $port);
  129. } else {
  130. $this->connection = @new mysqli($server, $user, $pass, $db);
  131. }
  132. if (!mysqli_connect_errno()) {
  133. $this->connected = true;
  134. if ($charset) {
  135. $this->connection->set_charset($charset);
  136. }
  137. }
  138. }
  139. // No suitable SQL driver was found.
  140. if (!$this->connected) {
  141. $this->driver = null;
  142. $this->connection = null;
  143. }
  144. return $this->connected;
  145. }
  146. public function setTestmode(bool $test)
  147. {
  148. $this->testmode = $test;
  149. }
  150. /**
  151. * Sets the logger for DBA
  152. *
  153. * @note this is necessary because if we want to load the logger configuration
  154. * from the DB, but there's an error, we would print out an exception.
  155. * So the logger gets updated after the logger configuration can be retrieved
  156. * from the database
  157. *
  158. * @param LoggerInterface $logger
  159. */
  160. public function setLogger(LoggerInterface $logger)
  161. {
  162. $this->logger = $logger;
  163. }
  164. /**
  165. * Sets the profiler for DBA
  166. *
  167. * @param Profiler $profiler
  168. */
  169. public function setProfiler(Profiler $profiler)
  170. {
  171. $this->profiler = $profiler;
  172. }
  173. /**
  174. * Disconnects the current database connection
  175. */
  176. public function disconnect()
  177. {
  178. if (!is_null($this->connection)) {
  179. switch ($this->driver) {
  180. case self::PDO:
  181. $this->connection = null;
  182. break;
  183. case self::MYSQLI:
  184. $this->connection->close();
  185. $this->connection = null;
  186. break;
  187. }
  188. }
  189. $this->driver = null;
  190. $this->connected = false;
  191. }
  192. /**
  193. * Perform a reconnect of an existing database connection
  194. */
  195. public function reconnect()
  196. {
  197. $this->disconnect();
  198. return $this->connect();
  199. }
  200. /**
  201. * Return the database object.
  202. *
  203. * @return PDO|mysqli
  204. */
  205. public function getConnection()
  206. {
  207. return $this->connection;
  208. }
  209. /**
  210. * Return the database driver string
  211. *
  212. * @return string with either "pdo" or "mysqli"
  213. */
  214. public function getDriver()
  215. {
  216. return $this->driver;
  217. }
  218. /**
  219. * Returns the MySQL server version string
  220. *
  221. * This function discriminate between the deprecated mysql API and the current
  222. * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
  223. *
  224. * @return string
  225. */
  226. public function serverInfo()
  227. {
  228. if ($this->server_info == '') {
  229. switch ($this->driver) {
  230. case self::PDO:
  231. $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  232. break;
  233. case self::MYSQLI:
  234. $this->server_info = $this->connection->server_info;
  235. break;
  236. }
  237. }
  238. return $this->server_info;
  239. }
  240. /**
  241. * Returns the selected database name
  242. *
  243. * @return string
  244. * @throws \Exception
  245. */
  246. public function databaseName()
  247. {
  248. $ret = $this->p("SELECT DATABASE() AS `db`");
  249. $data = $this->toArray($ret);
  250. return $data[0]['db'];
  251. }
  252. /**
  253. * Analyze a database query and log this if some conditions are met.
  254. *
  255. * @param string $query The database query that will be analyzed
  256. *
  257. * @throws \Exception
  258. */
  259. private function logIndex($query)
  260. {
  261. if (!$this->configCache->get('system', 'db_log_index')) {
  262. return;
  263. }
  264. // Don't explain an explain statement
  265. if (strtolower(substr($query, 0, 7)) == "explain") {
  266. return;
  267. }
  268. // Only do the explain on "select", "update" and "delete"
  269. if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
  270. return;
  271. }
  272. $r = $this->p("EXPLAIN " . $query);
  273. if (!$this->isResult($r)) {
  274. return;
  275. }
  276. $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
  277. $denylist = explode(',', $this->configCache->get('system', 'db_log_index_denylist'));
  278. while ($row = $this->fetch($r)) {
  279. if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
  280. $log = (in_array($row['key'], $watchlist) &&
  281. ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
  282. } else {
  283. $log = false;
  284. }
  285. if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
  286. $log = true;
  287. }
  288. if (in_array($row['key'], $denylist) || ($row['key'] == "")) {
  289. $log = false;
  290. }
  291. if ($log) {
  292. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  293. @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
  294. $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
  295. basename($backtrace[1]["file"]) . "\t" .
  296. $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
  297. substr($query, 0, 4000) . "\n", FILE_APPEND);
  298. }
  299. }
  300. }
  301. /**
  302. * Removes every not allowlisted character from the identifier string
  303. *
  304. * @param string $identifier
  305. *
  306. * @return string sanitized identifier
  307. * @throws \Exception
  308. */
  309. private function sanitizeIdentifier($identifier)
  310. {
  311. return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
  312. }
  313. public function escape($str)
  314. {
  315. if ($this->connected) {
  316. switch ($this->driver) {
  317. case self::PDO:
  318. return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
  319. case self::MYSQLI:
  320. return @$this->connection->real_escape_string($str);
  321. }
  322. } else {
  323. return str_replace("'", "\\'", $str);
  324. }
  325. }
  326. public function isConnected()
  327. {
  328. return $this->connected;
  329. }
  330. public function connected()
  331. {
  332. $connected = false;
  333. if (is_null($this->connection)) {
  334. return false;
  335. }
  336. switch ($this->driver) {
  337. case self::PDO:
  338. $r = $this->p("SELECT 1");
  339. if ($this->isResult($r)) {
  340. $row = $this->toArray($r);
  341. $connected = ($row[0]['1'] == '1');
  342. }
  343. break;
  344. case self::MYSQLI:
  345. $connected = $this->connection->ping();
  346. break;
  347. }
  348. return $connected;
  349. }
  350. /**
  351. * Replaces ANY_VALUE() function by MIN() function,
  352. * if the database server does not support ANY_VALUE().
  353. *
  354. * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
  355. * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
  356. * A standard fall-back is to use MIN().
  357. *
  358. * @param string $sql An SQL string without the values
  359. *
  360. * @return string The input SQL string modified if necessary.
  361. */
  362. public function anyValueFallback($sql)
  363. {
  364. $server_info = $this->serverInfo();
  365. if (version_compare($server_info, '5.7.5', '<') ||
  366. (stripos($server_info, 'MariaDB') !== false)) {
  367. $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
  368. }
  369. return $sql;
  370. }
  371. /**
  372. * Replaces the ? placeholders with the parameters in the $args array
  373. *
  374. * @param string $sql SQL query
  375. * @param array $args The parameters that are to replace the ? placeholders
  376. *
  377. * @return string The replaced SQL query
  378. */
  379. private function replaceParameters($sql, $args)
  380. {
  381. $offset = 0;
  382. foreach ($args AS $param => $value) {
  383. if (is_int($args[$param]) || is_float($args[$param]) || is_bool($args[$param])) {
  384. $replace = intval($args[$param]);
  385. } elseif (is_null($args[$param])) {
  386. $replace = 'NULL';
  387. } else {
  388. $replace = "'" . $this->escape($args[$param]) . "'";
  389. }
  390. $pos = strpos($sql, '?', $offset);
  391. if ($pos !== false) {
  392. $sql = substr_replace($sql, $replace, $pos, 1);
  393. }
  394. $offset = $pos + strlen($replace);
  395. }
  396. return $sql;
  397. }
  398. /**
  399. * Executes a prepared statement that returns data
  400. *
  401. * @usage Example: $r = p("SELECT * FROM `post` WHERE `guid` = ?", $guid);
  402. *
  403. * Please only use it with complicated queries.
  404. * For all regular queries please use DBA::select or DBA::exists
  405. *
  406. * @param string $sql SQL statement
  407. *
  408. * @return bool|object statement object or result object
  409. * @throws \Exception
  410. */
  411. public function p($sql)
  412. {
  413. $stamp1 = microtime(true);
  414. $params = DBA::getParam(func_get_args());
  415. // Renumber the array keys to be sure that they fit
  416. $i = 0;
  417. $args = [];
  418. foreach ($params AS $param) {
  419. // Avoid problems with some MySQL servers and boolean values. See issue #3645
  420. if (is_bool($param)) {
  421. $param = (int)$param;
  422. }
  423. $args[++$i] = $param;
  424. }
  425. if (!$this->connected) {
  426. return false;
  427. }
  428. if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
  429. // Question: Should we continue or stop the query here?
  430. $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
  431. }
  432. $sql = DBA::cleanQuery($sql);
  433. $sql = $this->anyValueFallback($sql);
  434. $orig_sql = $sql;
  435. if ($this->configCache->get('system', 'db_callstack') !== null) {
  436. $sql = "/*" . System::callstack() . " */ " . $sql;
  437. }
  438. $is_error = false;
  439. $this->error = '';
  440. $this->errorno = 0;
  441. $this->affected_rows = 0;
  442. // We have to make some things different if this function is called from "e"
  443. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  444. if (isset($trace[1])) {
  445. $called_from = $trace[1];
  446. } else {
  447. // We use just something that is defined to avoid warnings
  448. $called_from = $trace[0];
  449. }
  450. // We are having an own error logging in the function "e"
  451. $called_from_e = ($called_from['function'] == 'e');
  452. if (!isset($this->connection)) {
  453. throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
  454. }
  455. switch ($this->driver) {
  456. case self::PDO:
  457. // If there are no arguments we use "query"
  458. if (count($args) == 0) {
  459. if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
  460. $errorInfo = $this->connection->errorInfo();
  461. $this->error = $errorInfo[2];
  462. $this->errorno = $errorInfo[1];
  463. $retval = false;
  464. $is_error = true;
  465. break;
  466. }
  467. $this->affected_rows = $retval->rowCount();
  468. break;
  469. }
  470. /** @var $stmt mysqli_stmt|PDOStatement */
  471. if (!$stmt = $this->connection->prepare($sql)) {
  472. $errorInfo = $this->connection->errorInfo();
  473. $this->error = $errorInfo[2];
  474. $this->errorno = $errorInfo[1];
  475. $retval = false;
  476. $is_error = true;
  477. break;
  478. }
  479. foreach ($args AS $param => $value) {
  480. if (is_int($args[$param])) {
  481. $data_type = PDO::PARAM_INT;
  482. } else {
  483. $data_type = PDO::PARAM_STR;
  484. }
  485. $stmt->bindParam($param, $args[$param], $data_type);
  486. }
  487. if (!$stmt->execute()) {
  488. $errorInfo = $stmt->errorInfo();
  489. $this->error = $errorInfo[2];
  490. $this->errorno = $errorInfo[1];
  491. $retval = false;
  492. $is_error = true;
  493. } else {
  494. $retval = $stmt;
  495. $this->affected_rows = $retval->rowCount();
  496. }
  497. break;
  498. case self::MYSQLI:
  499. // There are SQL statements that cannot be executed with a prepared statement
  500. $parts = explode(' ', $orig_sql);
  501. $command = strtolower($parts[0]);
  502. $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
  503. // The fallback routine is called as well when there are no arguments
  504. if (!$can_be_prepared || (count($args) == 0)) {
  505. $retval = $this->connection->query($this->replaceParameters($sql, $args));
  506. if ($this->connection->errno) {
  507. $this->error = $this->connection->error;
  508. $this->errorno = $this->connection->errno;
  509. $retval = false;
  510. $is_error = true;
  511. } else {
  512. if (isset($retval->num_rows)) {
  513. $this->affected_rows = $retval->num_rows;
  514. } else {
  515. $this->affected_rows = $this->connection->affected_rows;
  516. }
  517. }
  518. break;
  519. }
  520. $stmt = $this->connection->stmt_init();
  521. if (!$stmt->prepare($sql)) {
  522. $this->error = $stmt->error;
  523. $this->errorno = $stmt->errno;
  524. $retval = false;
  525. $is_error = true;
  526. break;
  527. }
  528. $param_types = '';
  529. $values = [];
  530. foreach ($args AS $param => $value) {
  531. if (is_int($args[$param])) {
  532. $param_types .= 'i';
  533. } elseif (is_float($args[$param])) {
  534. $param_types .= 'd';
  535. } elseif (is_string($args[$param])) {
  536. $param_types .= 's';
  537. } else {
  538. $param_types .= 'b';
  539. }
  540. $values[] = &$args[$param];
  541. }
  542. if (count($values) > 0) {
  543. array_unshift($values, $param_types);
  544. call_user_func_array([$stmt, 'bind_param'], $values);
  545. }
  546. if (!$stmt->execute()) {
  547. $this->error = $this->connection->error;
  548. $this->errorno = $this->connection->errno;
  549. $retval = false;
  550. $is_error = true;
  551. } else {
  552. $stmt->store_result();
  553. $retval = $stmt;
  554. $this->affected_rows = $retval->affected_rows;
  555. }
  556. break;
  557. }
  558. // See issue https://github.com/friendica/friendica/issues/8572
  559. // Ensure that we always get an error message on an error.
  560. if ($is_error && empty($this->errorno)) {
  561. $this->errorno = -1;
  562. }
  563. if ($is_error && empty($this->error)) {
  564. $this->error = 'Unknown database error';
  565. }
  566. // We are having an own error logging in the function "e"
  567. if (($this->errorno != 0) && !$called_from_e) {
  568. // We have to preserve the error code, somewhere in the logging it get lost
  569. $error = $this->error;
  570. $errorno = $this->errorno;
  571. if ($this->testmode) {
  572. throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
  573. }
  574. $this->logger->error('DB Error', [
  575. 'code' => $errorno,
  576. 'error' => $error,
  577. 'callstack' => System::callstack(8),
  578. 'params' => $this->replaceParameters($sql, $args),
  579. ]);
  580. // On a lost connection we try to reconnect - but only once.
  581. if ($errorno == 2006) {
  582. if ($this->in_retrial || !$this->reconnect()) {
  583. // It doesn't make sense to continue when the database connection was lost
  584. if ($this->in_retrial) {
  585. $this->logger->notice('Giving up retrial because of database error', [
  586. 'code' => $errorno,
  587. 'error' => $error,
  588. ]);
  589. } else {
  590. $this->logger->notice('Couldn\'t reconnect after database error', [
  591. 'code' => $errorno,
  592. 'error' => $error,
  593. ]);
  594. }
  595. exit(1);
  596. } else {
  597. // We try it again
  598. $this->logger->notice('Reconnected after database error', [
  599. 'code' => $errorno,
  600. 'error' => $error,
  601. ]);
  602. $this->in_retrial = true;
  603. $ret = $this->p($sql, $args);
  604. $this->in_retrial = false;
  605. return $ret;
  606. }
  607. }
  608. $this->error = $error;
  609. $this->errorno = $errorno;
  610. }
  611. $this->profiler->saveTimestamp($stamp1, 'database');
  612. if ($this->configCache->get('system', 'db_log')) {
  613. $stamp2 = microtime(true);
  614. $duration = (float)($stamp2 - $stamp1);
  615. if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
  616. $duration = round($duration, 3);
  617. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  618. @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
  619. basename($backtrace[1]["file"]) . "\t" .
  620. $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
  621. substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
  622. }
  623. }
  624. return $retval;
  625. }
  626. /**
  627. * Executes a prepared statement like UPDATE or INSERT that doesn't return data
  628. *
  629. * Please use DBA::delete, DBA::insert, DBA::update, ... instead
  630. *
  631. * @param string $sql SQL statement
  632. *
  633. * @return boolean Was the query successfull? False is returned only if an error occurred
  634. * @throws \Exception
  635. */
  636. public function e($sql)
  637. {
  638. $stamp = microtime(true);
  639. $params = DBA::getParam(func_get_args());
  640. // In a case of a deadlock we are repeating the query 20 times
  641. $timeout = 20;
  642. do {
  643. $stmt = $this->p($sql, $params);
  644. if (is_bool($stmt)) {
  645. $retval = $stmt;
  646. } elseif (is_object($stmt)) {
  647. $retval = true;
  648. } else {
  649. $retval = false;
  650. }
  651. $this->close($stmt);
  652. } while (($this->errorno == 1213) && (--$timeout > 0));
  653. if ($this->errorno != 0) {
  654. // We have to preserve the error code, somewhere in the logging it get lost
  655. $error = $this->error;
  656. $errorno = $this->errorno;
  657. if ($this->testmode) {
  658. throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
  659. }
  660. $this->logger->error('DB Error', [
  661. 'code' => $errorno,
  662. 'error' => $error,
  663. 'callstack' => System::callstack(8),
  664. 'params' => $this->replaceParameters($sql, $params),
  665. ]);
  666. // On a lost connection we simply quit.
  667. // A reconnect like in $this->p could be dangerous with modifications
  668. if ($errorno == 2006) {
  669. $this->logger->notice('Giving up because of database error', [
  670. 'code' => $errorno,
  671. 'error' => $error,
  672. ]);
  673. exit(1);
  674. }
  675. $this->error = $error;
  676. $this->errorno = $errorno;
  677. }
  678. $this->profiler->saveTimestamp($stamp, "database_write");
  679. return $retval;
  680. }
  681. /**
  682. * Check if data exists
  683. *
  684. * @param string|array $table Table name or array [schema => table]
  685. * @param array $condition array of fields for condition
  686. *
  687. * @return boolean Are there rows for that condition?
  688. * @throws \Exception
  689. */
  690. public function exists($table, $condition)
  691. {
  692. if (empty($table)) {
  693. return false;
  694. }
  695. $fields = [];
  696. if (empty($condition)) {
  697. return DBStructure::existsTable($table);
  698. }
  699. reset($condition);
  700. $first_key = key($condition);
  701. if (!is_int($first_key)) {
  702. $fields = [$first_key];
  703. }
  704. $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
  705. if (is_bool($stmt)) {
  706. $retval = $stmt;
  707. } else {
  708. $retval = ($this->numRows($stmt) > 0);
  709. }
  710. $this->close($stmt);
  711. return $retval;
  712. }
  713. /**
  714. * Fetches the first row
  715. *
  716. * Please use DBA::selectFirst or DBA::exists whenever this is possible.
  717. *
  718. * Fetches the first row
  719. *
  720. * @param string $sql SQL statement
  721. *
  722. * @return array first row of query
  723. * @throws \Exception
  724. */
  725. public function fetchFirst($sql)
  726. {
  727. $params = DBA::getParam(func_get_args());
  728. $stmt = $this->p($sql, $params);
  729. if (is_bool($stmt)) {
  730. $retval = $stmt;
  731. } else {
  732. $retval = $this->fetch($stmt);
  733. }
  734. $this->close($stmt);
  735. return $retval;
  736. }
  737. /**
  738. * Returns the number of affected rows of the last statement
  739. *
  740. * @return int Number of rows
  741. */
  742. public function affectedRows()
  743. {
  744. return $this->affected_rows;
  745. }
  746. /**
  747. * Returns the number of columns of a statement
  748. *
  749. * @param object Statement object
  750. *
  751. * @return int Number of columns
  752. */
  753. public function columnCount($stmt)
  754. {
  755. if (!is_object($stmt)) {
  756. return 0;
  757. }
  758. switch ($this->driver) {
  759. case self::PDO:
  760. return $stmt->columnCount();
  761. case self::MYSQLI:
  762. return $stmt->field_count;
  763. }
  764. return 0;
  765. }
  766. /**
  767. * Returns the number of rows of a statement
  768. *
  769. * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
  770. *
  771. * @return int Number of rows
  772. */
  773. public function numRows($stmt)
  774. {
  775. if (!is_object($stmt)) {
  776. return 0;
  777. }
  778. switch ($this->driver) {
  779. case self::PDO:
  780. return $stmt->rowCount();
  781. case self::MYSQLI:
  782. return $stmt->num_rows;
  783. }
  784. return 0;
  785. }
  786. /**
  787. * Fetch a single row
  788. *
  789. * @param PDOStatement|mysqli_stmt $stmt statement object
  790. *
  791. * @return array|false current row
  792. */
  793. public function fetch($stmt)
  794. {
  795. $stamp1 = microtime(true);
  796. $columns = [];
  797. if (!is_object($stmt)) {
  798. return false;
  799. }
  800. switch ($this->driver) {
  801. case self::PDO:
  802. $columns = $stmt->fetch(PDO::FETCH_ASSOC);
  803. if (!empty($stmt->table) && is_array($columns)) {
  804. $columns = $this->castFields($stmt->table, $columns);
  805. }
  806. break;
  807. case self::MYSQLI:
  808. if (get_class($stmt) == 'mysqli_result') {
  809. $columns = $stmt->fetch_assoc() ?? false;
  810. break;
  811. }
  812. // This code works, but is slow
  813. // Bind the result to a result array
  814. $cols = [];
  815. $cols_num = [];
  816. for ($x = 0; $x < $stmt->field_count; $x++) {
  817. $cols[] = &$cols_num[$x];
  818. }
  819. call_user_func_array([$stmt, 'bind_result'], $cols);
  820. if (!$stmt->fetch()) {
  821. return false;
  822. }
  823. // The slow part:
  824. // We need to get the field names for the array keys
  825. // It seems that there is no better way to do this.
  826. $result = $stmt->result_metadata();
  827. $fields = $result->fetch_fields();
  828. foreach ($cols_num AS $param => $col) {
  829. $columns[$fields[$param]->name] = $col;
  830. }
  831. }
  832. $this->profiler->saveTimestamp($stamp1, 'database');
  833. return $columns;
  834. }
  835. /**
  836. * Insert a row into a table
  837. *
  838. * @param string|array $table Table name or array [schema => table]
  839. * @param array $param parameter array
  840. * @param int $duplicate_mode What to do on a duplicated entry
  841. *
  842. * @return boolean was the insert successful?
  843. * @throws \Exception
  844. */
  845. public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
  846. {
  847. if (empty($table) || empty($param)) {
  848. $this->logger->info('Table and fields have to be set');
  849. return false;
  850. }
  851. $param = $this->castFields($table, $param);
  852. $table_string = DBA::buildTableString($table);
  853. $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
  854. $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
  855. $sql = "INSERT ";
  856. if ($duplicate_mode == self::INSERT_IGNORE) {
  857. $sql .= "IGNORE ";
  858. }
  859. $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
  860. if ($duplicate_mode == self::INSERT_UPDATE) {
  861. $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
  862. $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
  863. $values = array_values($param);
  864. $param = array_merge_recursive($values, $values);
  865. }
  866. $result = $this->e($sql, $param);
  867. if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
  868. return $result;
  869. }
  870. return $this->affectedRows() != 0;
  871. }
  872. /**
  873. * Inserts a row with the provided data in the provided table.
  874. * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
  875. *
  876. * @param string|array $table Table name or array [schema => table]
  877. * @param array $param parameter array
  878. *
  879. * @return boolean was the insert successful?
  880. * @throws \Exception
  881. */
  882. public function replace($table, array $param)
  883. {
  884. if (empty($table) || empty($param)) {
  885. $this->logger->info('Table and fields have to be set');
  886. return false;
  887. }
  888. $param = $this->castFields($table, $param);
  889. $table_string = DBA::buildTableString($table);
  890. $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
  891. $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
  892. $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
  893. return $this->e($sql, $param);
  894. }
  895. /**
  896. * Fetch the id of the last insert command
  897. *
  898. * @return integer Last inserted id
  899. */
  900. public function lastInsertId()
  901. {
  902. switch ($this->driver) {
  903. case self::PDO:
  904. $id = $this->connection->lastInsertId();
  905. break;
  906. case self::MYSQLI:
  907. $id = $this->connection->insert_id;
  908. break;
  909. }
  910. return (int)$id;
  911. }
  912. /**
  913. * Locks a table for exclusive write access
  914. *
  915. * This function can be extended in the future to accept a table array as well.
  916. *
  917. * @param string|array $table Table name or array [schema => table]
  918. *
  919. * @return boolean was the lock successful?
  920. * @throws \Exception
  921. */
  922. public function lock($table)
  923. {
  924. // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
  925. if ($this->driver == self::PDO) {
  926. $this->e("SET autocommit=0");
  927. $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
  928. } else {
  929. $this->connection->autocommit(false);
  930. }
  931. $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
  932. if ($this->driver == self::PDO) {
  933. $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
  934. }
  935. if (!$success) {
  936. if ($this->driver == self::PDO) {
  937. $this->e("SET autocommit=1");
  938. } else {
  939. $this->connection->autocommit(true);
  940. }
  941. } else {
  942. $this->in_transaction = true;
  943. }
  944. return $success;
  945. }
  946. /**
  947. * Unlocks all locked tables
  948. *
  949. * @return boolean was the unlock successful?
  950. * @throws \Exception
  951. */
  952. public function unlock()
  953. {
  954. // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
  955. $this->performCommit();
  956. if ($this->driver == self::PDO) {
  957. $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
  958. }
  959. $success = $this->e("UNLOCK TABLES");
  960. if ($this->driver == self::PDO) {
  961. $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
  962. $this->e("SET autocommit=1");
  963. } else {
  964. $this->connection->autocommit(true);
  965. }
  966. $this->in_transaction = false;
  967. return $success;
  968. }
  969. /**
  970. * Starts a transaction
  971. *
  972. * @return boolean Was the command executed successfully?
  973. */
  974. public function transaction()
  975. {
  976. if (!$this->performCommit()) {
  977. return false;
  978. }
  979. switch ($this->driver) {
  980. case self::PDO:
  981. if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
  982. return false;
  983. }
  984. break;
  985. case self::MYSQLI:
  986. if (!$this->connection->begin_transaction()) {
  987. return false;
  988. }
  989. break;
  990. }
  991. $this->in_transaction = true;
  992. return true;
  993. }
  994. protected function performCommit()
  995. {
  996. switch ($this->driver) {
  997. case self::PDO:
  998. if (!$this->connection->inTransaction()) {
  999. return true;
  1000. }
  1001. return $this->connection->commit();
  1002. case self::MYSQLI:
  1003. return $this->connection->commit();
  1004. }
  1005. return true;
  1006. }
  1007. /**
  1008. * Does a commit
  1009. *
  1010. * @return boolean Was the command executed successfully?
  1011. */
  1012. public function commit()
  1013. {
  1014. if (!$this->performCommit()) {
  1015. return false;
  1016. }
  1017. $this->in_transaction = false;
  1018. return true;
  1019. }
  1020. /**
  1021. * Does a rollback
  1022. *
  1023. * @return boolean Was the command executed successfully?
  1024. */
  1025. public function rollback()
  1026. {
  1027. $ret = false;
  1028. switch ($this->driver) {
  1029. case self::PDO:
  1030. if (!$this->connection->inTransaction()) {
  1031. $ret = true;
  1032. break;
  1033. }
  1034. $ret = $this->connection->rollBack();
  1035. break;
  1036. case self::MYSQLI:
  1037. $ret = $this->connection->rollback();
  1038. break;
  1039. }
  1040. $this->in_transaction = false;
  1041. return $ret;
  1042. }
  1043. /**
  1044. * Delete a row from a table
  1045. *
  1046. * @param string $table Table name
  1047. * @param array $conditions Field condition(s)
  1048. *
  1049. * @return boolean was the delete successful?
  1050. * @throws \Exception
  1051. */
  1052. public function delete($table, array $conditions)
  1053. {
  1054. if (empty($table) || empty($conditions)) {
  1055. $this->logger->info('Table and conditions have to be set');
  1056. return false;
  1057. }
  1058. $table_string = DBA::buildTableString($table);
  1059. $condition_string = DBA::buildCondition($conditions);
  1060. $sql = "DELETE FROM " . $table_string . " " . $condition_string;
  1061. $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
  1062. return $this->e($sql, $conditions);
  1063. }
  1064. /**
  1065. * Updates rows
  1066. *
  1067. * Updates rows in the database. When $old_fields is set to an array,
  1068. * the system will only do an update if the fields in that array changed.
  1069. *
  1070. * Attention:
  1071. * Only the values in $old_fields are compared.
  1072. * This is an intentional behaviour.
  1073. *
  1074. * Example:
  1075. * We include the timestamp field in $fields but not in $old_fields.
  1076. * Then the row will only get the new timestamp when the other fields had changed.
  1077. *
  1078. * When $old_fields is set to a boolean value the system will do this compare itself.
  1079. * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
  1080. *
  1081. * Attention:
  1082. * Only set $old_fields to a boolean value when you are sure that you will update a single row.
  1083. * When you set $old_fields to "true" then $fields must contain all relevant fields!
  1084. *
  1085. * @param string|array $table Table name or array [schema => table]
  1086. * @param array $fields contains the fields that are updated
  1087. * @param array $condition condition array with the key values
  1088. * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
  1089. *
  1090. * @return boolean was the update successfull?
  1091. * @throws \Exception
  1092. */
  1093. public function update($table, $fields, $condition, $old_fields = [])
  1094. {
  1095. if (empty($table) || empty($fields) || empty($condition)) {
  1096. $this->logger->info('Table, fields and condition have to be set');
  1097. return false;
  1098. }
  1099. if (is_bool($old_fields)) {
  1100. $do_insert = $old_fields;
  1101. $old_fields = $this->selectFirst($table, [], $condition);
  1102. if (is_bool($old_fields)) {
  1103. if ($do_insert) {
  1104. $values = array_merge($condition, $fields);
  1105. return $this->replace($table, $values);
  1106. }
  1107. $old_fields = [];
  1108. }
  1109. }
  1110. foreach ($old_fields AS $fieldname => $content) {
  1111. if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
  1112. unset($fields[$fieldname]);
  1113. }
  1114. }
  1115. if (count($fields) == 0) {
  1116. return true;
  1117. }
  1118. $fields = $this->castFields($table, $fields);
  1119. $table_string = DBA::buildTableString($table);
  1120. $condition_string = DBA::buildCondition($condition);
  1121. $sql = "UPDATE " . $table_string . " SET "
  1122. . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
  1123. . $condition_string;
  1124. // Combines the updated fields parameter values with the condition parameter values
  1125. $params = array_merge(array_values($fields), $condition);
  1126. return $this->e($sql, $params);
  1127. }
  1128. /**
  1129. * Retrieve a single record from a table and returns it in an associative array
  1130. *
  1131. * @param string|array $table
  1132. * @param array $fields
  1133. * @param array $condition
  1134. * @param array $params
  1135. *
  1136. * @return bool|array
  1137. * @throws \Exception
  1138. * @see $this->select
  1139. */
  1140. public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
  1141. {
  1142. $params['limit'] = 1;
  1143. $result = $this->select($table, $fields, $condition, $params);
  1144. if (is_bool($result)) {
  1145. return $result;
  1146. } else {
  1147. $row = $this->fetch($result);
  1148. $this->close($result);
  1149. return $row;
  1150. }
  1151. }
  1152. /**
  1153. * Select rows from a table and fills an array with the data
  1154. *
  1155. * @param string|array $table Table name or array [schema => table]
  1156. * @param array $fields Array of selected fields, empty for all
  1157. * @param array $condition Array of fields for condition
  1158. * @param array $params Array of several parameters
  1159. *
  1160. * @return array Data array
  1161. * @throws \Exception
  1162. * @see self::select
  1163. */
  1164. public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
  1165. {
  1166. return $this->toArray($this->select($table, $fields, $condition, $params));
  1167. }
  1168. /**
  1169. * Select rows from a table
  1170. *
  1171. *
  1172. * Example:
  1173. * $table = 'post';
  1174. * or:
  1175. * $table = ['schema' => 'table'];
  1176. * @see DBA::buildTableString()
  1177. *
  1178. * $fields = ['id', 'uri', 'uid', 'network'];
  1179. *
  1180. * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
  1181. * or:
  1182. * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
  1183. * @see DBA::buildCondition()
  1184. *
  1185. * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
  1186. * @see DBA::buildParameter()
  1187. *
  1188. * $data = DBA::select($table, $fields, $condition, $params);
  1189. *
  1190. * @param string|array $table Table name or array [schema => table]
  1191. * @param array $fields Array of selected fields, empty for all
  1192. * @param array $condition Array of fields for condition
  1193. * @param array $params Array of several parameters
  1194. * @return boolean|object
  1195. * @throws \Exception
  1196. */
  1197. public function select($table, array $fields = [], array $condition = [], array $params = [])
  1198. {
  1199. if (empty($table)) {
  1200. return false;
  1201. }
  1202. if (count($fields) > 0) {
  1203. $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
  1204. } else {
  1205. $select_string = '*';
  1206. }
  1207. $table_string = DBA::buildTableString($table);
  1208. $condition_string = DBA::buildCondition($condition);
  1209. $param_string = DBA::buildParameter($params);
  1210. $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
  1211. $result = $this->p($sql, $condition);
  1212. if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
  1213. $result->table = $table;
  1214. }
  1215. return $result;
  1216. }
  1217. /**
  1218. * Counts the rows from a table satisfying the provided condition
  1219. *
  1220. * @param string|array $table Table name or array [schema => table]
  1221. * @param array $condition Array of fields for condition
  1222. * @param array $params Array of several parameters
  1223. *
  1224. * @return int
  1225. *
  1226. * Example:
  1227. * $table = "post";
  1228. *
  1229. * $condition = ["uid" => 1, "network" => 'dspr'];
  1230. * or:
  1231. * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
  1232. *
  1233. * $count = DBA::count($table, $condition);
  1234. * @throws \Exception
  1235. */
  1236. public function count($table, array $condition = [], array $params = [])
  1237. {
  1238. if (empty($table)) {
  1239. return false;
  1240. }
  1241. $table_string = DBA::buildTableString($table);
  1242. $condition_string = DBA::buildCondition($condition);
  1243. if (empty($params['expression'])) {
  1244. $expression = '*';
  1245. } elseif (!empty($params['distinct'])) {
  1246. $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
  1247. } else {
  1248. $expression = DBA::quoteIdentifier($params['expression']);
  1249. }
  1250. $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
  1251. $row = $this->fetchFirst($sql, $condition);
  1252. // Ensure to always return either a "null" or a numeric value
  1253. return is_numeric($row['count']) ? (int)$row['count'] : $row['count'];
  1254. }
  1255. /**
  1256. * Fills an array with data from a query
  1257. *
  1258. * @param object $stmt statement object
  1259. * @param bool $do_close Close database connection after last row
  1260. * @param int $count maximum number of rows to be fetched
  1261. *
  1262. * @return array Data array
  1263. */
  1264. public function toArray($stmt, $do_close = true, int $count = 0)
  1265. {
  1266. if (is_bool($stmt)) {
  1267. return [];
  1268. }
  1269. $data = [];
  1270. while ($row = $this->fetch($stmt)) {
  1271. $data[] = $row;
  1272. if (($count != 0) && (count($data) == $count)) {
  1273. return $data;
  1274. }
  1275. }
  1276. if ($do_close) {
  1277. $this->close($stmt);
  1278. }
  1279. return $data;
  1280. }
  1281. /**
  1282. * Cast field types according to the table definition
  1283. *
  1284. * @param string $table
  1285. * @param array $fields
  1286. * @return array casted fields
  1287. */
  1288. public function castFields(string $table, array $fields) {
  1289. // When there is no data, we don't need to do something
  1290. if (empty($fields)) {
  1291. return $fields;
  1292. }
  1293. // We only need to cast fields with PDO
  1294. if ($this->driver != self::PDO) {
  1295. return $fields;
  1296. }
  1297. // We only need to cast when emulating the prepares
  1298. if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
  1299. return $fields;
  1300. }
  1301. $types = [];
  1302. $tables = DBStructure::definition('', false);
  1303. if (empty($tables[$table])) {
  1304. // When a matching table wasn't found we check if it is a view
  1305. $views = View::definition('', false);
  1306. if (empty($views[$table])) {
  1307. return $fields;
  1308. }
  1309. foreach(array_keys($fields) as $field) {
  1310. if (!empty($views[$table]['fields'][$field])) {
  1311. $viewdef = $views[$table]['fields'][$field];
  1312. if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
  1313. $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
  1314. }
  1315. }
  1316. }
  1317. } else {
  1318. foreach ($tables[$table]['fields'] as $field => $definition) {
  1319. $types[$field] = $definition['type'];
  1320. }
  1321. }
  1322. foreach ($fields as $field => $content) {
  1323. if (is_null($content) || empty($types[$field])) {
  1324. continue;
  1325. }
  1326. if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
  1327. (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
  1328. (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
  1329. $fields[$field] = (int)$content;
  1330. }
  1331. if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
  1332. $fields[$field] = (float)$content;
  1333. }
  1334. }
  1335. return $fields;
  1336. }
  1337. /**
  1338. * Returns the error number of the last query
  1339. *
  1340. * @return string Error number (0 if no error)
  1341. */
  1342. public function errorNo()
  1343. {
  1344. return $this->errorno;
  1345. }
  1346. /**
  1347. * Returns the error message of the last query
  1348. *
  1349. * @return string Error message ('' if no error)
  1350. */
  1351. public function errorMessage()
  1352. {
  1353. return $this->error;
  1354. }
  1355. /**
  1356. * Closes the current statement
  1357. *
  1358. * @param object $stmt statement object
  1359. *
  1360. * @return boolean was the close successful?
  1361. */
  1362. public function close($stmt)
  1363. {
  1364. $stamp1 = microtime(true);
  1365. if (!is_object($stmt)) {
  1366. return false;
  1367. }
  1368. switch ($this->driver) {
  1369. case self::PDO:
  1370. $ret = $stmt->closeCursor();
  1371. break;
  1372. case self::MYSQLI:
  1373. // MySQLi offers both a mysqli_stmt and a mysqli_result class.
  1374. // We should be careful not to assume the object type of $stmt
  1375. // because DBA::p() has been able to return both types.
  1376. if ($stmt instanceof mysqli_stmt) {
  1377. $stmt->free_result();
  1378. $ret = $stmt->close();
  1379. } elseif ($stmt instanceof mysqli_result) {
  1380. $stmt->free();
  1381. $ret = true;
  1382. } else {
  1383. $ret = false;
  1384. }
  1385. break;
  1386. }
  1387. $this->profiler->saveTimestamp($stamp1, 'database');
  1388. return $ret;
  1389. }
  1390. /**
  1391. * Return a list of database processes
  1392. *
  1393. * @return array
  1394. * 'list' => List of processes, separated in their different states
  1395. * 'amount' => Number of concurrent database processes
  1396. * @throws \Exception
  1397. */
  1398. public function processlist()
  1399. {
  1400. $ret = $this->p("SHOW PROCESSLIST");
  1401. $data = $this->toArray($ret);
  1402. $processes = 0;
  1403. $states = [];
  1404. foreach ($data as $process) {
  1405. $state = trim($process["State"]);
  1406. // Filter out all non blocking processes
  1407. if (!in_array($state, ["", "init", "statistics", "updating"])) {
  1408. ++$states[$state];
  1409. ++$processes;
  1410. }
  1411. }
  1412. $statelist = "";
  1413. foreach ($states as $state => $usage) {
  1414. if ($statelist != "") {
  1415. $statelist .= ", ";
  1416. }
  1417. $statelist .= $state . ": " . $usage;
  1418. }
  1419. return (["list" => $statelist, "amount" => $processes]);
  1420. }
  1421. /**
  1422. * Fetch a database variable
  1423. *
  1424. * @param string $name
  1425. * @return string content
  1426. */
  1427. public function getVariable(string $name)
  1428. {
  1429. $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
  1430. return $result['Value'] ?? null;
  1431. }
  1432. /**
  1433. * Checks if $array is a filled array with at least one entry.
  1434. *
  1435. * @param mixed $array A filled array with at least one entry
  1436. *
  1437. * @return boolean Whether $array is a filled array or an object with rows
  1438. */
  1439. public function isResult($array)
  1440. {
  1441. // It could be a return value from an update statement
  1442. if (is_bool($array)) {
  1443. return $array;
  1444. }
  1445. if (is_object($array)) {
  1446. return $this->numRows($array) > 0;
  1447. }
  1448. return (is_array($array) && (count($array) > 0));
  1449. }
  1450. /**
  1451. * Callback function for "esc_array"
  1452. *
  1453. * @param mixed $value Array value
  1454. * @param string $key Array key
  1455. * @param boolean $add_quotation add quotation marks for string values
  1456. *
  1457. * @return void
  1458. */
  1459. private function escapeArrayCallback(&$value, $key, $add_quotation)
  1460. {
  1461. if (!$add_quotation) {
  1462. if (is_bool($value)) {
  1463. $value = ($value ? '1' : '0');
  1464. } else {
  1465. $value = $this->escape($value);
  1466. }
  1467. return;
  1468. }
  1469. if (is_bool($value)) {
  1470. $value = ($value ? 'true' : 'false');
  1471. } elseif (is_float($value) || is_integer($value)) {
  1472. $value = (string)$value;
  1473. } else {
  1474. $value = "'" . $this->escape($value) . "'";
  1475. }
  1476. }
  1477. /**
  1478. * Escapes a whole array
  1479. *
  1480. * @param mixed $arr Array with values to be escaped
  1481. * @param boolean $add_quotation add quotation marks for string values
  1482. *
  1483. * @return void
  1484. */
  1485. public function escapeArray(&$arr, $add_quotation = false)
  1486. {
  1487. array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
  1488. }
  1489. }