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.

1307 lines
34KB

  1. <?php
  2. use \Friendica\Core\System;
  3. require_once("dbm.php");
  4. require_once('include/datetime.php');
  5. /**
  6. * @class MySQL database class
  7. *
  8. * This class is for the low level database stuff that does driver specific things.
  9. */
  10. class dba {
  11. public static $connected = true;
  12. private static $_server_info = '';
  13. private static $db;
  14. private static $driver;
  15. private static $error = false;
  16. private static $errorno = 0;
  17. private static $affected_rows = 0;
  18. private static $in_transaction = false;
  19. private static $relation = array();
  20. public static function connect($serveraddr, $user, $pass, $db, $install = false) {
  21. if (!is_null(self::$db)) {
  22. return true;
  23. }
  24. $a = get_app();
  25. $stamp1 = microtime(true);
  26. $serveraddr = trim($serveraddr);
  27. $serverdata = explode(':', $serveraddr);
  28. $server = $serverdata[0];
  29. if (count($serverdata) > 1) {
  30. $port = trim($serverdata[1]);
  31. }
  32. $server = trim($server);
  33. $user = trim($user);
  34. $pass = trim($pass);
  35. $db = trim($db);
  36. if (!(strlen($server) && strlen($user))) {
  37. self::$connected = false;
  38. self::$db = null;
  39. return false;
  40. }
  41. if ($install) {
  42. if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
  43. if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
  44. self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
  45. self::$connected = false;
  46. self::$db = null;
  47. return false;
  48. }
  49. }
  50. }
  51. if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
  52. self::$driver = 'pdo';
  53. $connect = "mysql:host=".$server.";dbname=".$db;
  54. if (isset($port)) {
  55. $connect .= ";port=".$port;
  56. }
  57. if (isset($a->config["system"]["db_charset"])) {
  58. $connect .= ";charset=".$a->config["system"]["db_charset"];
  59. }
  60. try {
  61. self::$db = @new PDO($connect, $user, $pass);
  62. self::$connected = true;
  63. } catch (PDOException $e) {
  64. self::$connected = false;
  65. }
  66. }
  67. if (!self::$connected && class_exists('mysqli')) {
  68. self::$driver = 'mysqli';
  69. self::$db = @new mysqli($server, $user, $pass, $db, $port);
  70. if (!mysqli_connect_errno()) {
  71. self::$connected = true;
  72. if (isset($a->config["system"]["db_charset"])) {
  73. self::$db->set_charset($a->config["system"]["db_charset"]);
  74. }
  75. }
  76. }
  77. if (!self::$connected && function_exists('mysql_connect')) {
  78. self::$driver = 'mysql';
  79. self::$db = mysql_connect($serveraddr, $user, $pass);
  80. if (self::$db && mysql_select_db($db, self::$db)) {
  81. self::$connected = true;
  82. if (isset($a->config["system"]["db_charset"])) {
  83. mysql_set_charset($a->config["system"]["db_charset"], self::$db);
  84. }
  85. }
  86. }
  87. // No suitable SQL driver was found.
  88. if (!self::$connected) {
  89. self::$db = null;
  90. if (!$install) {
  91. system_unavailable();
  92. }
  93. }
  94. $a->save_timestamp($stamp1, "network");
  95. return true;
  96. }
  97. /**
  98. * @brief Returns the MySQL server version string
  99. *
  100. * This function discriminate between the deprecated mysql API and the current
  101. * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
  102. *
  103. * @return string
  104. */
  105. public static function server_info() {
  106. if (self::$_server_info == '') {
  107. switch (self::$driver) {
  108. case 'pdo':
  109. self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
  110. break;
  111. case 'mysqli':
  112. self::$_server_info = self::$db->server_info;
  113. break;
  114. case 'mysql':
  115. self::$_server_info = mysql_get_server_info(self::$db);
  116. break;
  117. }
  118. }
  119. return self::$_server_info;
  120. }
  121. /**
  122. * @brief Returns the selected database name
  123. *
  124. * @return string
  125. */
  126. public static function database_name() {
  127. $ret = self::p("SELECT DATABASE() AS `db`");
  128. $data = self::inArray($ret);
  129. return $data[0]['db'];
  130. }
  131. /**
  132. * @brief Analyze a database query and log this if some conditions are met.
  133. *
  134. * @param string $query The database query that will be analyzed
  135. */
  136. private static function log_index($query) {
  137. $a = get_app();
  138. if (empty($a->config["system"]["db_log_index"])) {
  139. return;
  140. }
  141. // Don't explain an explain statement
  142. if (strtolower(substr($query, 0, 7)) == "explain") {
  143. return;
  144. }
  145. // Only do the explain on "select", "update" and "delete"
  146. if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
  147. return;
  148. }
  149. $r = self::p("EXPLAIN ".$query);
  150. if (!dbm::is_result($r)) {
  151. return;
  152. }
  153. $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
  154. $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
  155. while ($row = dba::fetch($r)) {
  156. if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
  157. $log = (in_array($row['key'], $watchlist) &&
  158. ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
  159. } else {
  160. $log = false;
  161. }
  162. if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
  163. $log = true;
  164. }
  165. if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
  166. $log = false;
  167. }
  168. if ($log) {
  169. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  170. @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
  171. $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
  172. basename($backtrace[1]["file"])."\t".
  173. $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
  174. substr($query, 0, 2000)."\n", FILE_APPEND);
  175. }
  176. }
  177. }
  178. public static function escape($str) {
  179. switch (self::$driver) {
  180. case 'pdo':
  181. return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
  182. case 'mysqli':
  183. return @self::$db->real_escape_string($str);
  184. case 'mysql':
  185. return @mysql_real_escape_string($str,self::$db);
  186. }
  187. }
  188. public static function connected() {
  189. switch (self::$driver) {
  190. case 'pdo':
  191. // Not sure if this really is working like expected
  192. $connected = (self::$db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
  193. break;
  194. case 'mysqli':
  195. $connected = self::$db->ping();
  196. break;
  197. case 'mysql':
  198. $connected = mysql_ping(self::$db);
  199. break;
  200. }
  201. return $connected;
  202. }
  203. /**
  204. * @brief Replaces ANY_VALUE() function by MIN() function,
  205. * if the database server does not support ANY_VALUE().
  206. *
  207. * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
  208. * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
  209. * A standard fall-back is to use MIN().
  210. *
  211. * @param string $sql An SQL string without the values
  212. * @return string The input SQL string modified if necessary.
  213. */
  214. public static function any_value_fallback($sql) {
  215. $server_info = self::server_info();
  216. if (version_compare($server_info, '5.7.5', '<') ||
  217. (stripos($server_info, 'MariaDB') !== false)) {
  218. $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
  219. }
  220. return $sql;
  221. }
  222. /**
  223. * @brief beautifies the query - useful for "SHOW PROCESSLIST"
  224. *
  225. * This is safe when we bind the parameters later.
  226. * The parameter values aren't part of the SQL.
  227. *
  228. * @param string $sql An SQL string without the values
  229. * @return string The input SQL string modified if necessary.
  230. */
  231. public static function clean_query($sql) {
  232. $search = array("\t", "\n", "\r", " ");
  233. $replace = array(' ', ' ', ' ', ' ');
  234. do {
  235. $oldsql = $sql;
  236. $sql = str_replace($search, $replace, $sql);
  237. } while ($oldsql != $sql);
  238. return $sql;
  239. }
  240. /**
  241. * @brief Replaces the ? placeholders with the parameters in the $args array
  242. *
  243. * @param string $sql SQL query
  244. * @param array $args The parameters that are to replace the ? placeholders
  245. * @return string The replaced SQL query
  246. */
  247. private static function replace_parameters($sql, $args) {
  248. $offset = 0;
  249. foreach ($args AS $param => $value) {
  250. if (is_int($args[$param]) || is_float($args[$param])) {
  251. $replace = intval($args[$param]);
  252. } else {
  253. $replace = "'".self::escape($args[$param])."'";
  254. }
  255. $pos = strpos($sql, '?', $offset);
  256. if ($pos !== false) {
  257. $sql = substr_replace($sql, $replace, $pos, 1);
  258. }
  259. $offset = $pos + strlen($replace);
  260. }
  261. return $sql;
  262. }
  263. /**
  264. * @brief Convert parameter array to an universal form
  265. * @param array $args Parameter array
  266. * @return array universalized parameter array
  267. */
  268. private static function getParam($args) {
  269. unset($args[0]);
  270. // When the second function parameter is an array then use this as the parameter array
  271. if ((count($args) > 0) && (is_array($args[1]))) {
  272. return $args[1];
  273. } else {
  274. return $args;
  275. }
  276. }
  277. /**
  278. * @brief Executes a prepared statement that returns data
  279. * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
  280. *
  281. * Please only use it with complicated queries.
  282. * For all regular queries please use dba::select or dba::exists
  283. *
  284. * @param string $sql SQL statement
  285. * @return object statement object
  286. */
  287. public static function p($sql) {
  288. $a = get_app();
  289. $stamp1 = microtime(true);
  290. $params = self::getParam(func_get_args());
  291. // Renumber the array keys to be sure that they fit
  292. $i = 0;
  293. $args = array();
  294. foreach ($params AS $param) {
  295. // Avoid problems with some MySQL servers and boolean values. See issue #3645
  296. if (is_bool($param)) {
  297. $param = (int)$param;
  298. }
  299. $args[++$i] = $param;
  300. }
  301. if (!self::$connected) {
  302. return false;
  303. }
  304. if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
  305. // Question: Should we continue or stop the query here?
  306. logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
  307. }
  308. $sql = self::clean_query($sql);
  309. $sql = self::any_value_fallback($sql);
  310. $orig_sql = $sql;
  311. if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
  312. $sql = "/*".System::callstack()." */ ".$sql;
  313. }
  314. self::$error = '';
  315. self::$errorno = 0;
  316. self::$affected_rows = 0;
  317. // We have to make some things different if this function is called from "e"
  318. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  319. if (isset($trace[1])) {
  320. $called_from = $trace[1];
  321. } else {
  322. // We use just something that is defined to avoid warnings
  323. $called_from = $trace[0];
  324. }
  325. // We are having an own error logging in the function "e"
  326. $called_from_e = ($called_from['function'] == 'e');
  327. switch (self::$driver) {
  328. case 'pdo':
  329. // If there are no arguments we use "query"
  330. if (count($args) == 0) {
  331. if (!$retval = self::$db->query($sql)) {
  332. $errorInfo = self::$db->errorInfo();
  333. self::$error = $errorInfo[2];
  334. self::$errorno = $errorInfo[1];
  335. $retval = false;
  336. break;
  337. }
  338. self::$affected_rows = $retval->rowCount();
  339. break;
  340. }
  341. if (!$stmt = self::$db->prepare($sql)) {
  342. $errorInfo = self::$db->errorInfo();
  343. self::$error = $errorInfo[2];
  344. self::$errorno = $errorInfo[1];
  345. $retval = false;
  346. break;
  347. }
  348. foreach ($args AS $param => $value) {
  349. $stmt->bindParam($param, $args[$param]);
  350. }
  351. if (!$stmt->execute()) {
  352. $errorInfo = $stmt->errorInfo();
  353. self::$error = $errorInfo[2];
  354. self::$errorno = $errorInfo[1];
  355. $retval = false;
  356. } else {
  357. $retval = $stmt;
  358. self::$affected_rows = $retval->rowCount();
  359. }
  360. break;
  361. case 'mysqli':
  362. // There are SQL statements that cannot be executed with a prepared statement
  363. $parts = explode(' ', $orig_sql);
  364. $command = strtolower($parts[0]);
  365. $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
  366. // The fallback routine is called as well when there are no arguments
  367. if (!$can_be_prepared || (count($args) == 0)) {
  368. $retval = self::$db->query(self::replace_parameters($sql, $args));
  369. if (self::$db->errno) {
  370. self::$error = self::$db->error;
  371. self::$errorno = self::$db->errno;
  372. $retval = false;
  373. } else {
  374. if (isset($retval->num_rows)) {
  375. self::$affected_rows = $retval->num_rows;
  376. } else {
  377. self::$affected_rows = self::$db->affected_rows;
  378. }
  379. }
  380. break;
  381. }
  382. $stmt = self::$db->stmt_init();
  383. if (!$stmt->prepare($sql)) {
  384. self::$error = $stmt->error;
  385. self::$errorno = $stmt->errno;
  386. $retval = false;
  387. break;
  388. }
  389. $params = '';
  390. $values = array();
  391. foreach ($args AS $param => $value) {
  392. if (is_int($args[$param])) {
  393. $params .= 'i';
  394. } elseif (is_float($args[$param])) {
  395. $params .= 'd';
  396. } elseif (is_string($args[$param])) {
  397. $params .= 's';
  398. } else {
  399. $params .= 'b';
  400. }
  401. $values[] = &$args[$param];
  402. }
  403. if (count($values) > 0) {
  404. array_unshift($values, $params);
  405. call_user_func_array(array($stmt, 'bind_param'), $values);
  406. }
  407. if (!$stmt->execute()) {
  408. self::$error = self::$db->error;
  409. self::$errorno = self::$db->errno;
  410. $retval = false;
  411. } else {
  412. $stmt->store_result();
  413. $retval = $stmt;
  414. self::$affected_rows = $retval->affected_rows;
  415. }
  416. break;
  417. case 'mysql':
  418. // For the old "mysql" functions we cannot use prepared statements
  419. $retval = mysql_query(self::replace_parameters($sql, $args), self::$db);
  420. if (mysql_errno(self::$db)) {
  421. self::$error = mysql_error(self::$db);
  422. self::$errorno = mysql_errno(self::$db);
  423. } else {
  424. self::$affected_rows = mysql_affected_rows($retval);
  425. // Due to missing mysql_* support this here wasn't tested at all
  426. // See here: http://php.net/manual/en/function.mysql-num-rows.php
  427. if (self::$affected_rows <= 0) {
  428. self::$affected_rows = mysql_num_rows($retval);
  429. }
  430. }
  431. break;
  432. }
  433. // We are having an own error logging in the function "e"
  434. if ((self::$errorno != 0) && !$called_from_e) {
  435. // We have to preserve the error code, somewhere in the logging it get lost
  436. $error = self::$error;
  437. $errorno = self::$errorno;
  438. logger('DB Error '.self::$errorno.': '.self::$error."\n".
  439. System::callstack(8)."\n".self::replace_parameters($sql, $params));
  440. self::$error = $error;
  441. self::$errorno = $errorno;
  442. }
  443. $a->save_timestamp($stamp1, 'database');
  444. if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
  445. $stamp2 = microtime(true);
  446. $duration = (float)($stamp2 - $stamp1);
  447. if (($duration > $a->config["system"]["db_loglimit"])) {
  448. $duration = round($duration, 3);
  449. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  450. @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
  451. basename($backtrace[1]["file"])."\t".
  452. $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
  453. substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
  454. }
  455. }
  456. return $retval;
  457. }
  458. /**
  459. * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
  460. *
  461. * Please use dba::delete, dba::insert, dba::update, ... instead
  462. *
  463. * @param string $sql SQL statement
  464. * @return boolean Was the query successfull? False is returned only if an error occurred
  465. */
  466. public static function e($sql) {
  467. $a = get_app();
  468. $stamp = microtime(true);
  469. $params = self::getParam(func_get_args());
  470. // In a case of a deadlock we are repeating the query 20 times
  471. $timeout = 20;
  472. do {
  473. $stmt = self::p($sql, $params);
  474. if (is_bool($stmt)) {
  475. $retval = $stmt;
  476. } elseif (is_object($stmt)) {
  477. $retval = true;
  478. } else {
  479. $retval = false;
  480. }
  481. self::close($stmt);
  482. } while ((self::$errorno == 1213) && (--$timeout > 0));
  483. if (self::$errorno != 0) {
  484. // We have to preserve the error code, somewhere in the logging it get lost
  485. $error = self::$error;
  486. $errorno = self::$errorno;
  487. logger('DB Error '.self::$errorno.': '.self::$error."\n".
  488. System::callstack(8)."\n".self::replace_parameters($sql, $params));
  489. self::$error = $error;
  490. self::$errorno = $errorno;
  491. }
  492. $a->save_timestamp($stamp, "database_write");
  493. return $retval;
  494. }
  495. /**
  496. * @brief Check if data exists
  497. *
  498. * @param string $table Table name
  499. * @param array $condition array of fields for condition
  500. *
  501. * @return boolean Are there rows for that condition?
  502. */
  503. public static function exists($table, $condition) {
  504. if (empty($table)) {
  505. return false;
  506. }
  507. $fields = array();
  508. $array_element = each($condition);
  509. $array_key = $array_element['key'];
  510. if (!is_int($array_key)) {
  511. $fields = array($array_key);
  512. }
  513. $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
  514. if (is_bool($stmt)) {
  515. $retval = $stmt;
  516. } else {
  517. $retval = (self::num_rows($stmt) > 0);
  518. }
  519. self::close($stmt);
  520. return $retval;
  521. }
  522. /**
  523. * @brief Fetches the first row
  524. *
  525. * Please use dba::select or dba::exists whenever this is possible.
  526. *
  527. * @param string $sql SQL statement
  528. * @return array first row of query
  529. */
  530. public static function fetch_first($sql) {
  531. $params = self::getParam(func_get_args());
  532. $stmt = self::p($sql, $params);
  533. if (is_bool($stmt)) {
  534. $retval = $stmt;
  535. } else {
  536. $retval = self::fetch($stmt);
  537. }
  538. self::close($stmt);
  539. return $retval;
  540. }
  541. /**
  542. * @brief Returns the number of affected rows of the last statement
  543. *
  544. * @return int Number of rows
  545. */
  546. public static function affected_rows() {
  547. return self::$affected_rows;
  548. }
  549. /**
  550. * @brief Returns the number of columns of a statement
  551. *
  552. * @param object Statement object
  553. * @return int Number of columns
  554. */
  555. public static function columnCount($stmt) {
  556. if (!is_object($stmt)) {
  557. return 0;
  558. }
  559. switch (self::$driver) {
  560. case 'pdo':
  561. return $stmt->columnCount();
  562. case 'mysqli':
  563. return $stmt->field_count;
  564. case 'mysql':
  565. return mysql_affected_rows($stmt);
  566. }
  567. return 0;
  568. }
  569. /**
  570. * @brief Returns the number of rows of a statement
  571. *
  572. * @param object Statement object
  573. * @return int Number of rows
  574. */
  575. public static function num_rows($stmt) {
  576. if (!is_object($stmt)) {
  577. return 0;
  578. }
  579. switch (self::$driver) {
  580. case 'pdo':
  581. return $stmt->rowCount();
  582. case 'mysqli':
  583. return $stmt->num_rows;
  584. case 'mysql':
  585. return mysql_num_rows($stmt);
  586. }
  587. return 0;
  588. }
  589. /**
  590. * @brief Fetch a single row
  591. *
  592. * @param object $stmt statement object
  593. * @return array current row
  594. */
  595. public static function fetch($stmt) {
  596. if (!is_object($stmt)) {
  597. return false;
  598. }
  599. switch (self::$driver) {
  600. case 'pdo':
  601. return $stmt->fetch(PDO::FETCH_ASSOC);
  602. case 'mysqli':
  603. if (get_class($stmt) == 'mysqli_result') {
  604. return $stmt->fetch_assoc();
  605. }
  606. // This code works, but is slow
  607. // Bind the result to a result array
  608. $cols = array();
  609. $cols_num = array();
  610. for ($x = 0; $x < $stmt->field_count; $x++) {
  611. $cols[] = &$cols_num[$x];
  612. }
  613. call_user_func_array(array($stmt, 'bind_result'), $cols);
  614. if (!$stmt->fetch()) {
  615. return false;
  616. }
  617. // The slow part:
  618. // We need to get the field names for the array keys
  619. // It seems that there is no better way to do this.
  620. $result = $stmt->result_metadata();
  621. $fields = $result->fetch_fields();
  622. $columns = array();
  623. foreach ($cols_num AS $param => $col) {
  624. $columns[$fields[$param]->name] = $col;
  625. }
  626. return $columns;
  627. case 'mysql':
  628. return mysql_fetch_array($stmt, MYSQL_ASSOC);
  629. }
  630. }
  631. /**
  632. * @brief Insert a row into a table
  633. *
  634. * @param string $table Table name
  635. * @param array $param parameter array
  636. * @param bool $on_duplicate_update Do an update on a duplicate entry
  637. *
  638. * @return boolean was the insert successfull?
  639. */
  640. public static function insert($table, $param, $on_duplicate_update = false) {
  641. $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
  642. substr(str_repeat("?, ", count($param)), 0, -2).")";
  643. if ($on_duplicate_update) {
  644. $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
  645. $values = array_values($param);
  646. $param = array_merge_recursive($values, $values);
  647. }
  648. return self::e($sql, $param);
  649. }
  650. /**
  651. * @brief Fetch the id of the last insert command
  652. *
  653. * @return integer Last inserted id
  654. */
  655. public static function lastInsertId() {
  656. switch (self::$driver) {
  657. case 'pdo':
  658. $id = self::$db->lastInsertId();
  659. break;
  660. case 'mysqli':
  661. $id = self::$db->insert_id;
  662. break;
  663. case 'mysql':
  664. $id = mysql_insert_id(self::$db);
  665. break;
  666. }
  667. return $id;
  668. }
  669. /**
  670. * @brief Locks a table for exclusive write access
  671. *
  672. * This function can be extended in the future to accept a table array as well.
  673. *
  674. * @param string $table Table name
  675. *
  676. * @return boolean was the lock successful?
  677. */
  678. public static function lock($table) {
  679. // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
  680. self::e("SET autocommit=0");
  681. $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
  682. if (!$success) {
  683. self::e("SET autocommit=1");
  684. } else {
  685. self::$in_transaction = true;
  686. }
  687. return $success;
  688. }
  689. /**
  690. * @brief Unlocks all locked tables
  691. *
  692. * @return boolean was the unlock successful?
  693. */
  694. public static function unlock() {
  695. // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
  696. self::e("COMMIT");
  697. $success = self::e("UNLOCK TABLES");
  698. self::e("SET autocommit=1");
  699. self::$in_transaction = false;
  700. return $success;
  701. }
  702. /**
  703. * @brief Starts a transaction
  704. *
  705. * @return boolean Was the command executed successfully?
  706. */
  707. public static function transaction() {
  708. if (!self::e('COMMIT')) {
  709. return false;
  710. }
  711. if (!self::e('START TRANSACTION')) {
  712. return false;
  713. }
  714. self::$in_transaction = true;
  715. return true;
  716. }
  717. /**
  718. * @brief Does a commit
  719. *
  720. * @return boolean Was the command executed successfully?
  721. */
  722. public static function commit() {
  723. if (!self::e('COMMIT')) {
  724. return false;
  725. }
  726. self::$in_transaction = false;
  727. return true;
  728. }
  729. /**
  730. * @brief Does a rollback
  731. *
  732. * @return boolean Was the command executed successfully?
  733. */
  734. public static function rollback() {
  735. if (!self::e('ROLLBACK')) {
  736. return false;
  737. }
  738. self::$in_transaction = false;
  739. return true;
  740. }
  741. /**
  742. * @brief Build the array with the table relations
  743. *
  744. * The array is build from the database definitions in dbstructure.php
  745. *
  746. * This process must only be started once, since the value is cached.
  747. */
  748. private static function build_relation_data() {
  749. $definition = db_definition();
  750. foreach ($definition AS $table => $structure) {
  751. foreach ($structure['fields'] AS $field => $field_struct) {
  752. if (isset($field_struct['relation'])) {
  753. foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
  754. self::$relation[$rel_table][$rel_field][$table][] = $field;
  755. }
  756. }
  757. }
  758. }
  759. }
  760. /**
  761. * @brief Delete a row from a table
  762. *
  763. * @param string $table Table name
  764. * @param array $param parameter array
  765. * @param boolean $in_process Internal use: Only do a commit after the last delete
  766. * @param array $callstack Internal use: prevent endless loops
  767. *
  768. * @return boolean|array was the delete successfull? When $in_process is set: deletion data
  769. */
  770. public static function delete($table, $param, $in_process = false, &$callstack = array()) {
  771. $commands = array();
  772. // Create a key for the loop prevention
  773. $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
  774. // We quit when this key already exists in the callstack.
  775. if (isset($callstack[$key])) {
  776. return $commands;
  777. }
  778. $callstack[$key] = true;
  779. $table = self::escape($table);
  780. $commands[$key] = array('table' => $table, 'param' => $param);
  781. // To speed up the whole process we cache the table relations
  782. if (count(self::$relation) == 0) {
  783. self::build_relation_data();
  784. }
  785. // Is there a relation entry for the table?
  786. if (isset(self::$relation[$table])) {
  787. // We only allow a simple "one field" relation.
  788. $field = array_keys(self::$relation[$table])[0];
  789. $rel_def = array_values(self::$relation[$table])[0];
  790. // Create a key for preventing double queries
  791. $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
  792. // When the search field is the relation field, we don't need to fetch the rows
  793. // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
  794. if ((count($param) == 1) && ($field == array_keys($param)[0])) {
  795. foreach ($rel_def AS $rel_table => $rel_fields) {
  796. foreach ($rel_fields AS $rel_field) {
  797. $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
  798. $commands = array_merge($commands, $retval);
  799. }
  800. }
  801. // We quit when this key already exists in the callstack.
  802. } elseif (!isset($callstack[$qkey])) {
  803. $callstack[$qkey] = true;
  804. // Fetch all rows that are to be deleted
  805. $data = self::select($table, array($field), $param);
  806. while ($row = self::fetch($data)) {
  807. // Now we accumulate the delete commands
  808. $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
  809. $commands = array_merge($commands, $retval);
  810. }
  811. self::close($data);
  812. // Since we had split the delete command we don't need the original command anymore
  813. unset($commands[$key]);
  814. }
  815. }
  816. if (!$in_process) {
  817. // Now we finalize the process
  818. $do_transaction = !self::$in_transaction;
  819. if ($do_transaction) {
  820. self::transaction();
  821. }
  822. $compacted = array();
  823. $counter = array();
  824. foreach ($commands AS $command) {
  825. $condition = $command['param'];
  826. $array_element = each($condition);
  827. $array_key = $array_element['key'];
  828. if (is_int($array_key)) {
  829. $condition_string = " WHERE ".array_shift($condition);
  830. } else {
  831. $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
  832. }
  833. if ((count($command['param']) > 1) || is_int($array_key)) {
  834. $sql = "DELETE FROM `".$command['table']."`".$condition_string;
  835. logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
  836. if (!self::e($sql, $condition)) {
  837. if ($do_transaction) {
  838. self::rollback();
  839. }
  840. return false;
  841. }
  842. } else {
  843. $key_table = $command['table'];
  844. $key_param = array_keys($command['param'])[0];
  845. $value = array_values($command['param'])[0];
  846. // Split the SQL queries in chunks of 100 values
  847. // We do the $i stuff here to make the code better readable
  848. $i = $counter[$key_table][$key_param];
  849. if (count($compacted[$key_table][$key_param][$i]) > 100) {
  850. ++$i;
  851. }
  852. $compacted[$key_table][$key_param][$i][$value] = $value;
  853. $counter[$key_table][$key_param] = $i;
  854. }
  855. }
  856. foreach ($compacted AS $table => $values) {
  857. foreach ($values AS $field => $field_value_list) {
  858. foreach ($field_value_list AS $field_values) {
  859. $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
  860. substr(str_repeat("?, ", count($field_values)), 0, -2).");";
  861. logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
  862. if (!self::e($sql, $field_values)) {
  863. if ($do_transaction) {
  864. self::rollback();
  865. }
  866. return false;
  867. }
  868. }
  869. }
  870. }
  871. if ($do_transaction) {
  872. self::commit();
  873. }
  874. return true;
  875. }
  876. return $commands;
  877. }
  878. /**
  879. * @brief Updates rows
  880. *
  881. * Updates rows in the database. When $old_fields is set to an array,
  882. * the system will only do an update if the fields in that array changed.
  883. *
  884. * Attention:
  885. * Only the values in $old_fields are compared.
  886. * This is an intentional behaviour.
  887. *
  888. * Example:
  889. * We include the timestamp field in $fields but not in $old_fields.
  890. * Then the row will only get the new timestamp when the other fields had changed.
  891. *
  892. * When $old_fields is set to a boolean value the system will do this compare itself.
  893. * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
  894. *
  895. * Attention:
  896. * Only set $old_fields to a boolean value when you are sure that you will update a single row.
  897. * When you set $old_fields to "true" then $fields must contain all relevant fields!
  898. *
  899. * @param string $table Table name
  900. * @param array $fields contains the fields that are updated
  901. * @param array $condition condition array with the key values
  902. * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
  903. *
  904. * @return boolean was the update successfull?
  905. */
  906. public static function update($table, $fields, $condition, $old_fields = array()) {
  907. $table = self::escape($table);
  908. if (count($condition) > 0) {
  909. $array_element = each($condition);
  910. $array_key = $array_element['key'];
  911. if (is_int($array_key)) {
  912. $condition_string = " WHERE ".array_shift($condition);
  913. } else {
  914. $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
  915. }
  916. } else {
  917. $condition_string = "";
  918. }
  919. if (is_bool($old_fields)) {
  920. $do_insert = $old_fields;
  921. $old_fields = self::select($table, array(), $condition, array('limit' => 1));
  922. if (is_bool($old_fields)) {
  923. if ($do_insert) {
  924. $values = array_merge($condition, $fields);
  925. return self::insert($table, $values, $do_insert);
  926. }
  927. $old_fields = array();
  928. }
  929. }
  930. $do_update = (count($old_fields) == 0);
  931. foreach ($old_fields AS $fieldname => $content) {
  932. if (isset($fields[$fieldname])) {
  933. if ($fields[$fieldname] == $content) {
  934. unset($fields[$fieldname]);
  935. } else {
  936. $do_update = true;
  937. }
  938. }
  939. }
  940. if (!$do_update || (count($fields) == 0)) {
  941. return true;
  942. }
  943. $sql = "UPDATE `".$table."` SET `".
  944. implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
  945. $params1 = array_values($fields);
  946. $params2 = array_values($condition);
  947. $params = array_merge_recursive($params1, $params2);
  948. return self::e($sql, $params);
  949. }
  950. /**
  951. * @brief Select rows from a table
  952. *
  953. * @param string $table Table name
  954. * @param array $fields array of selected fields
  955. * @param array $condition array of fields for condition
  956. * @param array $params array of several parameters
  957. *
  958. * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
  959. *
  960. * Example:
  961. * $table = "item";
  962. * $fields = array("id", "uri", "uid", "network");
  963. *
  964. * $condition = array("uid" => 1, "network" => 'dspr');
  965. * or:
  966. * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
  967. *
  968. * $params = array("order" => array("id", "received" => true), "limit" => 1);
  969. *
  970. * $data = dba::select($table, $fields, $condition, $params);
  971. */
  972. public static function select($table, $fields = array(), $condition = array(), $params = array()) {
  973. if ($table == '') {
  974. return false;
  975. }
  976. if (count($fields) > 0) {
  977. $select_fields = "`".implode("`, `", array_values($fields))."`";
  978. } else {
  979. $select_fields = "*";
  980. }
  981. if (count($condition) > 0) {
  982. $array_element = each($condition);
  983. $array_key = $array_element['key'];
  984. if (is_int($array_key)) {
  985. $condition_string = " WHERE ".array_shift($condition);
  986. } else {
  987. $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
  988. }
  989. } else {
  990. $condition_string = "";
  991. }
  992. $param_string = '';
  993. $single_row = false;
  994. if (isset($params['order'])) {
  995. $param_string .= " ORDER BY ";
  996. foreach ($params['order'] AS $fields => $order) {
  997. if (!is_int($fields)) {
  998. $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
  999. } else {
  1000. $param_string .= "`".$order."`, ";
  1001. }
  1002. }
  1003. $param_string = substr($param_string, 0, -2);
  1004. }
  1005. if (isset($params['limit']) && is_int($params['limit'])) {
  1006. $param_string .= " LIMIT ".$params['limit'];
  1007. $single_row = ($params['limit'] == 1);
  1008. }
  1009. if (isset($params['only_query']) && $params['only_query']) {
  1010. $single_row = !$params['only_query'];
  1011. }
  1012. $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
  1013. $result = self::p($sql, $condition);
  1014. if (is_bool($result) || !$single_row) {
  1015. return $result;
  1016. } else {
  1017. $row = self::fetch($result);
  1018. self::close($result);
  1019. return $row;
  1020. }
  1021. }
  1022. /**
  1023. * @brief Fills an array with data from a query
  1024. *
  1025. * @param object $stmt statement object
  1026. * @return array Data array
  1027. */
  1028. public static function inArray($stmt, $do_close = true) {
  1029. if (is_bool($stmt)) {
  1030. return $stmt;
  1031. }
  1032. $data = array();
  1033. while ($row = self::fetch($stmt)) {
  1034. $data[] = $row;
  1035. }
  1036. if ($do_close) {
  1037. self::close($stmt);
  1038. }
  1039. return $data;
  1040. }
  1041. /**
  1042. * @brief Returns the error number of the last query
  1043. *
  1044. * @return string Error number (0 if no error)
  1045. */
  1046. public static function errorNo() {
  1047. return self::$errorno;
  1048. }
  1049. /**
  1050. * @brief Returns the error message of the last query
  1051. *
  1052. * @return string Error message ('' if no error)
  1053. */
  1054. public static function errorMessage() {
  1055. return self::$error;
  1056. }
  1057. /**
  1058. * @brief Closes the current statement
  1059. *
  1060. * @param object $stmt statement object
  1061. * @return boolean was the close successfull?
  1062. */
  1063. public static function close($stmt) {
  1064. if (!is_object($stmt)) {
  1065. return false;
  1066. }
  1067. switch (self::$driver) {
  1068. case 'pdo':
  1069. return $stmt->closeCursor();
  1070. case 'mysqli':
  1071. return $stmt->free_result();
  1072. return $stmt->close();
  1073. case 'mysql':
  1074. return mysql_free_result($stmt);
  1075. }
  1076. }
  1077. }
  1078. function dbesc($str) {
  1079. if (dba::$connected) {
  1080. return(dba::escape($str));
  1081. } else {
  1082. return(str_replace("'","\\'",$str));
  1083. }
  1084. }
  1085. /**
  1086. * @brief execute SQL query with printf style args - deprecated
  1087. *
  1088. * Please use the dba:: functions instead:
  1089. * dba::select, dba::exists, dba::insert
  1090. * dba::delete, dba::update, dba::p, dba::e
  1091. *
  1092. * @param $args Query parameters (1 to N parameters of different types)
  1093. * @return array Query array
  1094. */
  1095. function q($sql) {
  1096. $args = func_get_args();
  1097. unset($args[0]);
  1098. if (!dba::$connected) {
  1099. return false;
  1100. }
  1101. $sql = dba::clean_query($sql);
  1102. $sql = dba::any_value_fallback($sql);
  1103. $stmt = @vsprintf($sql, $args);
  1104. $ret = dba::p($stmt);
  1105. if (is_bool($ret)) {
  1106. return $ret;
  1107. }
  1108. $columns = dba::columnCount($ret);
  1109. $data = dba::inArray($ret);
  1110. if ((count($data) == 0) && ($columns == 0)) {
  1111. return true;
  1112. }
  1113. return $data;
  1114. }
  1115. function dba_timer() {
  1116. return microtime(true);
  1117. }