]> git.mxchange.org Git - friendica.git/blobdiff - src/Database/DBA.php
Merge pull request #6090 from zeroadam/TextToL10n
[friendica.git] / src / Database / DBA.php
index 8e5a621b3689819f93ec021506716debf7f6561e..bf3004ead4761eebdc2d46fc026c8240597a47cf 100644 (file)
@@ -6,6 +6,7 @@ namespace Friendica\Database;
 // Please use App->getConfigVariable() instead.
 //use Friendica\Core\Config;
 
+use Friendica\Core\Logger;
 use Friendica\Core\System;
 use Friendica\Util\DateTimeFormat;
 use mysqli;
@@ -24,6 +25,15 @@ require_once 'include/dba.php';
  */
 class DBA
 {
+       /**
+        * Lowest possible date value
+        */
+       const NULL_DATE     = '0001-01-01';
+       /**
+        * Lowest possible datetime value
+        */
+       const NULL_DATETIME = '0001-01-01 00:00:00';
+
        public static $connected = false;
 
        private static $server_info = '';
@@ -91,6 +101,7 @@ class DBA
                                self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                                self::$connected = true;
                        } catch (PDOException $e) {
+                               /// @TODO At least log exception, don't ignore it!
                        }
                }
 
@@ -251,11 +262,16 @@ class DBA
        }
 
        public static function escape($str) {
-               switch (self::$driver) {
-                       case 'pdo':
-                               return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
-                       case 'mysqli':
-                               return @self::$connection->real_escape_string($str);
+               if (self::$connected) {
+                       switch (self::$driver) {
+                               case 'pdo':
+                                       return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
+
+                               case 'mysqli':
+                                       return @self::$connection->real_escape_string($str);
+                       }
+               } else {
+                       return str_replace("'", "\\'", $str);
                }
        }
 
@@ -368,7 +384,7 @@ class DBA
         * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
         *
         * Please only use it with complicated queries.
-        * For all regular queries please use dba::select or dba::exists
+        * For all regular queries please use DBA::select or DBA::exists
         *
         * @param string $sql SQL statement
         * @return bool|object statement object or result object
@@ -397,7 +413,7 @@ class DBA
 
                if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
                        // Question: Should we continue or stop the query here?
-                       logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
+                       Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
                }
 
                $sql = self::cleanQuery($sql);
@@ -537,7 +553,7 @@ class DBA
                        $error = self::$error;
                        $errorno = self::$errorno;
 
-                       logger('DB Error '.self::$errorno.': '.self::$error."\n".
+                       Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
                                System::callstack(8)."\n".self::replaceParameters($sql, $args));
 
                        // On a lost connection we try to reconnect - but only once.
@@ -545,14 +561,14 @@ class DBA
                                if (self::$in_retrial || !self::reconnect()) {
                                        // It doesn't make sense to continue when the database connection was lost
                                        if (self::$in_retrial) {
-                                               logger('Giving up retrial because of database error '.$errorno.': '.$error);
+                                               Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
                                        } else {
-                                               logger("Couldn't reconnect after database error ".$errorno.': '.$error);
+                                               Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
                                        }
                                        exit(1);
                                } else {
                                        // We try it again
-                                       logger('Reconnected after database error '.$errorno.': '.$error);
+                                       Logger::log('Reconnected after database error '.$errorno.': '.$error);
                                        self::$in_retrial = true;
                                        $ret = self::p($sql, $args);
                                        self::$in_retrial = false;
@@ -564,7 +580,7 @@ class DBA
                        self::$errorno = $errorno;
                }
 
-               $a->save_timestamp($stamp1, 'database');
+               $a->saveTimestamp($stamp1, 'database');
 
                if ($a->getConfigValue('system', 'db_log')) {
                        $stamp2 = microtime(true);
@@ -586,7 +602,7 @@ class DBA
        /**
         * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
         *
-        * Please use dba::delete, dba::insert, dba::update, ... instead
+        * Please use DBA::delete, DBA::insert, DBA::update, ... instead
         *
         * @param string $sql SQL statement
         * @return boolean Was the query successfull? False is returned only if an error occurred
@@ -621,13 +637,13 @@ class DBA
                        $error = self::$error;
                        $errorno = self::$errorno;
 
-                       logger('DB Error '.self::$errorno.': '.self::$error."\n".
+                       Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
                                System::callstack(8)."\n".self::replaceParameters($sql, $params));
 
                        // On a lost connection we simply quit.
                        // A reconnect like in self::p could be dangerous with modifications
                        if ($errorno == 2006) {
-                               logger('Giving up because of database error '.$errorno.': '.$error);
+                               Logger::log('Giving up because of database error '.$errorno.': '.$error);
                                exit(1);
                        }
 
@@ -635,7 +651,7 @@ class DBA
                        self::$errorno = $errorno;
                }
 
-               $a->save_timestamp($stamp, "database_write");
+               $a->saveTimestamp($stamp, "database_write");
 
                return $retval;
        }
@@ -681,7 +697,7 @@ class DBA
        /**
         * Fetches the first row
         *
-        * Please use dba::selectFirst or dba::exists whenever this is possible.
+        * Please use DBA::selectFirst or DBA::exists whenever this is possible.
         *
         * @brief Fetches the first row
         * @param string $sql SQL statement
@@ -803,7 +819,7 @@ class DBA
                                }
                }
 
-               $a->save_timestamp($stamp1, 'database');
+               $a->saveTimestamp($stamp1, 'database');
 
                return $columns;
        }
@@ -815,12 +831,12 @@ class DBA
         * @param array $param parameter array
         * @param bool $on_duplicate_update Do an update on a duplicate entry
         *
-        * @return boolean was the insert successfull?
+        * @return boolean was the insert successful?
         */
        public static function insert($table, $param, $on_duplicate_update = false) {
 
                if (empty($table) || empty($param)) {
-                       logger('Table and fields have to be set');
+                       Logger::log('Table and fields have to be set');
                        return false;
                }
 
@@ -928,13 +944,11 @@ class DBA
 
                switch (self::$driver) {
                        case 'pdo':
-                               if (self::$connection->inTransaction()) {
-                                       break;
-                               }
-                               if (!self::$connection->beginTransaction()) {
+                               if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
                                        return false;
                                }
                                break;
+
                        case 'mysqli':
                                if (!self::$connection->begin_transaction()) {
                                        return false;
@@ -953,10 +967,13 @@ class DBA
                                if (!self::$connection->inTransaction()) {
                                        return true;
                                }
+
                                return self::$connection->commit();
+
                        case 'mysqli':
                                return self::$connection->commit();
                }
+
                return true;
        }
 
@@ -989,6 +1006,7 @@ class DBA
                                }
                                $ret = self::$connection->rollBack();
                                break;
+
                        case 'mysqli':
                                $ret = self::$connection->rollback();
                                break;
@@ -1034,7 +1052,7 @@ class DBA
        public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
        {
                if (empty($table) || empty($conditions)) {
-                       logger('Table and conditions have to be set');
+                       Logger::log('Table and conditions have to be set');
                        return false;
                }
 
@@ -1054,7 +1072,12 @@ class DBA
 
                $commands[$key] = ['table' => $table, 'conditions' => $conditions];
 
-               $cascade = defaults($options, 'cascade', true);
+               // Don't use "defaults" here, since it would set "false" to "true"
+               if (isset($options['cascade'])) {
+                       $cascade = $options['cascade'];
+               } else {
+                       $cascade = true;
+               }
 
                // To speed up the whole process we cache the table relations
                if ($cascade && count(self::$relation) == 0) {
@@ -1120,7 +1143,7 @@ class DBA
 
                                if ((count($command['conditions']) > 1) || is_int($first_key)) {
                                        $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
-                                       logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
+                                       Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
 
                                        if (!self::e($sql, $conditions)) {
                                                if ($do_transaction) {
@@ -1150,7 +1173,7 @@ class DBA
                                                $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
                                                        substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
 
-                                               logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
+                                               Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
 
                                                if (!self::e($sql, $field_values)) {
                                                        if ($do_transaction) {
@@ -1201,7 +1224,7 @@ class DBA
        public static function update($table, $fields, $condition, $old_fields = []) {
 
                if (empty($table) || empty($fields) || empty($condition)) {
-                       logger('Table, fields and condition have to be set');
+                       Logger::log('Table, fields and condition have to be set');
                        return false;
                }
 
@@ -1294,7 +1317,7 @@ class DBA
         *
         * $params = array("order" => array("id", "received" => true), "limit" => 10);
         *
-        * $data = dba::select($table, $fields, $condition, $params);
+        * $data = DBA::select($table, $fields, $condition, $params);
         */
        public static function select($table, array $fields = [], array $condition = [], array $params = [])
        {
@@ -1336,7 +1359,7 @@ class DBA
         * or:
         * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
         *
-        * $count = dba::count($table, $condition);
+        * $count = DBA::count($table, $condition);
         */
        public static function count($table, array $condition = [])
        {
@@ -1390,7 +1413,7 @@ class DBA
                                                /* Workaround for MySQL Bug #64791.
                                                 * Never mix data types inside any IN() condition.
                                                 * In case of mixed types, cast all as string.
-                                                * Logic needs to be consistent with dba::p() data types.
+                                                * Logic needs to be consistent with DBA::p() data types.
                                                 */
                                                $is_int = false;
                                                $is_alpha = false;
@@ -1450,7 +1473,7 @@ class DBA
 
                $limit_string = '';
                if (isset($params['limit']) && is_int($params['limit'])) {
-                       $limit_string = " LIMIT " . $params['limit'];
+                       $limit_string = " LIMIT " . intval($params['limit']);
                }
 
                if (isset($params['limit']) && is_array($params['limit'])) {
@@ -1521,7 +1544,7 @@ class DBA
                        case 'mysqli':
                                // MySQLi offers both a mysqli_stmt and a mysqli_result class.
                                // We should be careful not to assume the object type of $stmt
-                               // because dba::p() has been able to return both types.
+                               // because DBA::p() has been able to return both types.
                                if ($stmt instanceof mysqli_stmt) {
                                        $stmt->free_result();
                                        $ret = $stmt->close();
@@ -1534,7 +1557,7 @@ class DBA
                                break;
                }
 
-               $a->save_timestamp($stamp1, 'database');
+               $a->saveTimestamp($stamp1, 'database');
 
                return $ret;
        }
@@ -1610,7 +1633,7 @@ class DBA
                        if (is_bool($value)) {
                                $value = ($value ? '1' : '0');
                        } else {
-                               $value = dbesc($value);
+                               $value = self::escape($value);
                        }
                        return;
                }
@@ -1620,7 +1643,7 @@ class DBA
                } elseif (is_float($value) || is_integer($value)) {
                        $value = (string) $value;
                } else {
-                       $value = "'" . dbesc($value) . "'";
+                       $value = "'" . self::escape($value) . "'";
                }
        }