]> git.mxchange.org Git - friendica.git/blob - src/Database/DBA.php
Merge pull request #8963 from MrPetovan/task/8918-move-mod-common
[friendica.git] / src / Database / DBA.php
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
22 namespace Friendica\Database;
23
24 use Friendica\DI;
25 use mysqli;
26 use mysqli_result;
27 use mysqli_stmt;
28 use PDO;
29 use PDOStatement;
30
31 /**
32  * This class is for the low level database stuff that does driver specific things.
33  */
34 class DBA
35 {
36         /**
37          * Lowest possible date value
38          */
39         const NULL_DATE     = '0001-01-01';
40         /**
41          * Lowest possible datetime value
42          */
43         const NULL_DATETIME = '0001-01-01 00:00:00';
44
45         public static function connect()
46         {
47                 return DI::dba()->connect();
48         }
49
50         /**
51          * Disconnects the current database connection
52          */
53         public static function disconnect()
54         {
55                 DI::dba()->disconnect();
56         }
57
58         /**
59          * Perform a reconnect of an existing database connection
60          */
61         public static function reconnect()
62         {
63                 return DI::dba()->reconnect();
64         }
65
66         /**
67          * Return the database object.
68          * @return PDO|mysqli
69          */
70         public static function getConnection()
71         {
72                 return DI::dba()->getConnection();
73         }
74
75         /**
76          * Returns the MySQL server version string
77          *
78          * This function discriminate between the deprecated mysql API and the current
79          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
80          *
81          * @return string
82          */
83         public static function serverInfo()
84         {
85                 return DI::dba()->serverInfo();
86         }
87
88         /**
89          * Returns the selected database name
90          *
91          * @return string
92          * @throws \Exception
93          */
94         public static function databaseName()
95         {
96                 return DI::dba()->databaseName();
97         }
98
99         /**
100          * Escape all SQL unsafe data
101          *
102          * @param string $str
103          * @return string escaped string
104          */
105         public static function escape($str)
106         {
107                 return DI::dba()->escape($str);
108         }
109
110         /**
111          * Checks if the database is connected
112          *
113          * @return boolean is the database connected?
114          */
115         public static function connected()
116         {
117                 return DI::dba()->connected();
118         }
119
120         /**
121          * Replaces ANY_VALUE() function by MIN() function,
122          * if the database server does not support ANY_VALUE().
123          *
124          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
125          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
126          * A standard fall-back is to use MIN().
127          *
128          * @param string $sql An SQL string without the values
129          * @return string The input SQL string modified if necessary.
130          */
131         public static function anyValueFallback($sql)
132         {
133                 return DI::dba()->anyValueFallback($sql);
134         }
135
136         /**
137          * beautifies the query - useful for "SHOW PROCESSLIST"
138          *
139          * This is safe when we bind the parameters later.
140          * The parameter values aren't part of the SQL.
141          *
142          * @param string $sql An SQL string without the values
143          * @return string The input SQL string modified if necessary.
144          */
145         public static function cleanQuery($sql)
146         {
147                 $search = ["\t", "\n", "\r", "  "];
148                 $replace = [' ', ' ', ' ', ' '];
149                 do {
150                         $oldsql = $sql;
151                         $sql = str_replace($search, $replace, $sql);
152                 } while ($oldsql != $sql);
153
154                 return $sql;
155         }
156
157         /**
158          * Convert parameter array to an universal form
159          * @param array $args Parameter array
160          * @return array universalized parameter array
161          */
162         public static function getParam($args)
163         {
164                 unset($args[0]);
165
166                 // When the second function parameter is an array then use this as the parameter array
167                 if ((count($args) > 0) && (is_array($args[1]))) {
168                         return $args[1];
169                 } else {
170                         return $args;
171                 }
172         }
173
174         /**
175          * Executes a prepared statement that returns data
176          * Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
177          *
178          * Please only use it with complicated queries.
179          * For all regular queries please use DBA::select or DBA::exists
180          *
181          * @param string $sql SQL statement
182          * @return bool|object statement object or result object
183          * @throws \Exception
184          */
185         public static function p($sql)
186         {
187                 $params = self::getParam(func_get_args());
188
189                 return DI::dba()->p($sql, $params);
190         }
191
192         /**
193          * Executes a prepared statement like UPDATE or INSERT that doesn't return data
194          *
195          * Please use DBA::delete, DBA::insert, DBA::update, ... instead
196          *
197          * @param string $sql SQL statement
198          * @return boolean Was the query successfull? False is returned only if an error occurred
199          * @throws \Exception
200          */
201         public static function e($sql) {
202
203                 $params = self::getParam(func_get_args());
204
205                 return DI::dba()->e($sql, $params);
206         }
207
208         /**
209          * Check if data exists
210          *
211          * @param string|array $table     Table name or array [schema => table]
212          * @param array        $condition array of fields for condition
213          *
214          * @return boolean Are there rows for that condition?
215          * @throws \Exception
216          */
217         public static function exists($table, $condition)
218         {
219                 return DI::dba()->exists($table, $condition);
220         }
221
222         /**
223          * Fetches the first row
224          *
225          * Please use DBA::selectFirst or DBA::exists whenever this is possible.
226          *
227          * @param string $sql SQL statement
228          * @return array first row of query
229          * @throws \Exception
230          */
231         public static function fetchFirst($sql)
232         {
233                 $params = self::getParam(func_get_args());
234
235                 return DI::dba()->fetchFirst($sql, $params);
236         }
237
238         /**
239          * Returns the number of affected rows of the last statement
240          *
241          * @return int Number of rows
242          */
243         public static function affectedRows()
244         {
245                 return DI::dba()->affectedRows();
246         }
247
248         /**
249          * Returns the number of columns of a statement
250          *
251          * @param object Statement object
252          * @return int Number of columns
253          */
254         public static function columnCount($stmt)
255         {
256                 return DI::dba()->columnCount($stmt);
257         }
258         /**
259          * Returns the number of rows of a statement
260          *
261          * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
262          * @return int Number of rows
263          */
264         public static function numRows($stmt)
265         {
266                 return DI::dba()->numRows($stmt);
267         }
268
269         /**
270          * Fetch a single row
271          *
272          * @param mixed $stmt statement object
273          * @return array current row
274          */
275         public static function fetch($stmt)
276         {
277                 return DI::dba()->fetch($stmt);
278         }
279
280         /**
281          * Insert a row into a table
282          *
283          * @param string|array $table               Table name or array [schema => table]
284          * @param array        $param               parameter array
285          * @param bool         $on_duplicate_update Do an update on a duplicate entry
286          *
287          * @return boolean was the insert successful?
288          * @throws \Exception
289          */
290         public static function insert($table, $param, $on_duplicate_update = false)
291         {
292                 return DI::dba()->insert($table, $param, $on_duplicate_update);
293         }
294
295         /**
296          * Fetch the id of the last insert command
297          *
298          * @return integer Last inserted id
299          */
300         public static function lastInsertId()
301         {
302                 return DI::dba()->lastInsertId();
303         }
304
305         /**
306          * Locks a table for exclusive write access
307          *
308          * This function can be extended in the future to accept a table array as well.
309          *
310          * @param string|array $table Table name or array [schema => table]
311          *
312          * @return boolean was the lock successful?
313          * @throws \Exception
314          */
315         public static function lock($table)
316         {
317                 return DI::dba()->lock($table);
318         }
319
320         /**
321          * Unlocks all locked tables
322          *
323          * @return boolean was the unlock successful?
324          * @throws \Exception
325          */
326         public static function unlock()
327         {
328                 return DI::dba()->unlock();
329         }
330
331         /**
332          * Starts a transaction
333          *
334          * @return boolean Was the command executed successfully?
335          */
336         public static function transaction()
337         {
338                 return DI::dba()->transaction();
339         }
340
341         /**
342          * Does a commit
343          *
344          * @return boolean Was the command executed successfully?
345          */
346         public static function commit()
347         {
348                 return DI::dba()->commit();
349         }
350
351         /**
352          * Does a rollback
353          *
354          * @return boolean Was the command executed successfully?
355          */
356         public static function rollback()
357         {
358                 return DI::dba()->rollback();
359         }
360
361         /**
362          * Delete a row from a table
363          *
364          * @param string|array $table      Table name
365          * @param array        $conditions Field condition(s)
366          * @param array        $options
367          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
368          *                           relations (default: true)
369          *
370          * @return boolean was the delete successful?
371          * @throws \Exception
372          */
373         public static function delete($table, array $conditions, array $options = [])
374         {
375                 return DI::dba()->delete($table, $conditions, $options);
376         }
377
378         /**
379          * Updates rows in the database.
380          *
381          * When $old_fields is set to an array,
382          * the system will only do an update if the fields in that array changed.
383          *
384          * Attention:
385          * Only the values in $old_fields are compared.
386          * This is an intentional behaviour.
387          *
388          * Example:
389          * We include the timestamp field in $fields but not in $old_fields.
390          * Then the row will only get the new timestamp when the other fields had changed.
391          *
392          * When $old_fields is set to a boolean value the system will do this compare itself.
393          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
394          *
395          * Attention:
396          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
397          * When you set $old_fields to "true" then $fields must contain all relevant fields!
398          *
399          * @param string|array  $table      Table name or array [schema => table]
400          * @param array         $fields     contains the fields that are updated
401          * @param array         $condition  condition array with the key values
402          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
403          *
404          * @return boolean was the update successfull?
405          * @throws \Exception
406          */
407         public static function update($table, $fields, $condition, $old_fields = [])
408         {
409                 return DI::dba()->update($table, $fields, $condition, $old_fields);
410         }
411
412         /**
413          * Retrieve a single record from a table and returns it in an associative array
414          *
415          * @param string|array $table     Table name or array [schema => table]
416          * @param array        $fields
417          * @param array        $condition
418          * @param array        $params
419          * @return bool|array
420          * @throws \Exception
421          * @see   self::select
422          */
423         public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
424         {
425                 return DI::dba()->selectFirst($table, $fields, $condition, $params);
426         }
427
428         /**
429          * Select rows from a table and fills an array with the data
430          *
431          * @param string|array $table     Table name or array [schema => table]
432          * @param array        $fields    Array of selected fields, empty for all
433          * @param array        $condition Array of fields for condition
434          * @param array        $params    Array of several parameters
435          *
436          * @return array Data array
437          * @throws \Exception
438          * @see   self::select
439          */
440         public static function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
441         {
442                 return DI::dba()->selectToArray($table, $fields, $condition, $params);
443         }
444
445         /**
446          * Select rows from a table
447          *
448          * @param string|array $table     Table name or array [schema => table]
449          * @param array        $fields    Array of selected fields, empty for all
450          * @param array        $condition Array of fields for condition
451          * @param array        $params    Array of several parameters
452          *
453          * @return boolean|object
454          *
455          * Example:
456          * $table = "item";
457          * $fields = array("id", "uri", "uid", "network");
458          *
459          * $condition = array("uid" => 1, "network" => 'dspr');
460          * or:
461          * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
462          *
463          * $params = array("order" => array("id", "received" => true), "limit" => 10);
464          *
465          * $data = DBA::select($table, $fields, $condition, $params);
466          * @throws \Exception
467          */
468         public static function select($table, array $fields = [], array $condition = [], array $params = [])
469         {
470                 return DI::dba()->select($table, $fields, $condition, $params);
471         }
472
473         /**
474          * Counts the rows from a table satisfying the provided condition
475          *
476          * @param string|array $table     Table name or array [schema => table]
477          * @param array        $condition array of fields for condition
478          * @param array        $params    Array of several parameters
479          *
480          * @return int
481          *
482          * Example:
483          * $table = "item";
484          *
485          * $condition = ["uid" => 1, "network" => 'dspr'];
486          * or:
487          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
488          *
489          * $count = DBA::count($table, $condition);
490          * @throws \Exception
491          */
492         public static function count($table, array $condition = [], array $params = [])
493         {
494                 return DI::dba()->count($table, $condition, $params);
495         }
496
497         /**
498          * Build the table query substring from one or more tables, with or without a schema.
499          *
500          * Expected formats:
501          * - table
502          * - [table1, table2, ...]
503          * - [schema1 => table1, schema2 => table2, table3, ...]
504          *
505          * @param string|array $tables
506          * @return string
507          */
508         public static function buildTableString($tables)
509         {
510                 if (is_string($tables)) {
511                         $tables = [$tables];
512                 }
513
514                 $quotedTables = [];
515
516                 foreach ($tables as $schema => $table) {
517                         if (is_numeric($schema)) {
518                                 $quotedTables[] = self::quoteIdentifier($table);
519                         } else {
520                                 $quotedTables[] = self::quoteIdentifier($schema) . '.' . self::quoteIdentifier($table);
521                         }
522                 }
523
524                 return implode(', ', $quotedTables);
525         }
526
527         /**
528          * Escape an identifier (table or field name)
529          *
530          * @param $identifier
531          * @return string
532          */
533         public static function quoteIdentifier($identifier)
534         {
535                 return '`' . str_replace('`', '``', $identifier) . '`';
536         }
537
538         /**
539          * Returns the SQL condition string built from the provided condition array
540          *
541          * This function operates with two modes.
542          * - Supplied with a field/value associative array, it builds simple strict
543          *   equality conditions linked by AND.
544          * - Supplied with a flat list, the first element is the condition string and
545          *   the following arguments are the values to be interpolated
546          *
547          * $condition = ["uid" => 1, "network" => 'dspr'];
548          * or:
549          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
550          *
551          * In either case, the provided array is left with the parameters only
552          *
553          * @param array $condition
554          * @return string
555          */
556         public static function buildCondition(array &$condition = [])
557         {
558                 $condition = self::collapseCondition($condition);
559                 
560                 $condition_string = '';
561                 if (count($condition) > 0) {
562                         $condition_string = " WHERE (" . array_shift($condition) . ")";
563                 }
564
565                 return $condition_string;
566         }
567
568         /**
569          * Collapse an associative array condition into a SQL string + parameters condition array.
570          *
571          * ['uid' => 1, 'network' => ['dspr', 'apub']]
572          *
573          * gets transformed into
574          *
575          * ["`uid` = ? AND `network` IN (?, ?)", 1, 'dspr', 'apub']
576          *
577          * @param array $condition
578          * @return array
579          */
580         public static function collapseCondition(array $condition)
581         {
582                 // Ensures an always true condition is returned
583                 if (count($condition) < 1) {
584                         return ['1'];
585                 }
586
587                 reset($condition);
588                 $first_key = key($condition);
589
590                 if (is_int($first_key)) {
591                         // Already collapsed
592                         return $condition;
593                 }
594
595                 $values = [];
596                 $condition_string = "";
597                 foreach ($condition as $field => $value) {
598                         if ($condition_string != "") {
599                                 $condition_string .= " AND ";
600                         }
601
602                         if (is_array($value)) {
603                                 if (count($value)) {
604                                         /* Workaround for MySQL Bug #64791.
605                                          * Never mix data types inside any IN() condition.
606                                          * In case of mixed types, cast all as string.
607                                          * Logic needs to be consistent with DBA::p() data types.
608                                          */
609                                         $is_int = false;
610                                         $is_alpha = false;
611                                         foreach ($value as $single_value) {
612                                                 if (is_int($single_value)) {
613                                                         $is_int = true;
614                                                 } else {
615                                                         $is_alpha = true;
616                                                 }
617                                         }
618
619                                         if ($is_int && $is_alpha) {
620                                                 foreach ($value as &$ref) {
621                                                         if (is_int($ref)) {
622                                                                 $ref = (string)$ref;
623                                                         }
624                                                 }
625                                                 unset($ref); //Prevent accidental re-use.
626                                         }
627
628                                         $values = array_merge($values, array_values($value));
629                                         $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
630                                         $condition_string .= self::quoteIdentifier($field) . " IN (" . $placeholders . ")";
631                                 } else {
632                                         // Empty value array isn't supported by IN and is logically equivalent to no match
633                                         $condition_string .= "FALSE";
634                                 }
635                         } elseif (is_null($value)) {
636                                 $condition_string .= self::quoteIdentifier($field) . " IS NULL";
637                         } else {
638                                 $values[$field] = $value;
639                                 $condition_string .= self::quoteIdentifier($field) . " = ?";
640                         }
641                 }
642
643                 $condition = array_merge([$condition_string], array_values($values));
644
645                 return $condition;
646         }
647
648         /**
649          * Merges the provided conditions into a single collapsed one
650          *
651          * @param array ...$conditions One or more condition arrays
652          * @return array A collapsed condition
653          * @see DBA::collapseCondition() for the condition array formats
654          */
655         public static function mergeConditions(array ...$conditions)
656         {
657                 $conditionStrings = [];
658                 $result = [];
659
660                 foreach ($conditions as $key => $condition) {
661                         $condition = self::collapseCondition($condition);
662
663                         $conditionStrings[] = array_shift($condition);
664                         // The result array holds the eventual parameter values
665                         $result = array_merge($result, $condition);
666                 }
667
668                 if (count($conditionStrings)) {
669                         // We prepend the condition string at the end to form a collapsed condition array again
670                         array_unshift($result, implode(' AND ', $conditionStrings));
671                 }
672
673                 return $result;
674         }
675
676         /**
677          * Returns the SQL parameter string built from the provided parameter array
678          *
679          * Expected format for each key:
680          *
681          * group_by:
682          *  - list of column names
683          *
684          * order:
685          *  - numeric keyed column name => ASC
686          *  - associative element with boolean value => DESC (true), ASC (false)
687          *  - associative element with string value => 'ASC' or 'DESC' literally
688          *
689          * limit:
690          *  - single numeric value => count
691          *  - list with two numeric values => offset, count
692          *
693          * @param array $params
694          * @return string
695          */
696         public static function buildParameter(array $params = [])
697         {
698                 $groupby_string = '';
699                 if (!empty($params['group_by'])) {
700                         $groupby_string = " GROUP BY " . implode(', ', array_map(['self', 'quoteIdentifier'], $params['group_by']));
701                 }
702
703                 $order_string = '';
704                 if (isset($params['order'])) {
705                         $order_string = " ORDER BY ";
706                         foreach ($params['order'] AS $fields => $order) {
707                                 if ($order === 'RAND()') {
708                                         $order_string .= "RAND(), ";
709                                 } elseif (!is_int($fields)) {
710                                         if ($order !== 'DESC' && $order !== 'ASC') {
711                                                 $order = $order ? 'DESC' : 'ASC';
712                                         }
713
714                                         $order_string .= self::quoteIdentifier($fields) . " " . $order . ", ";
715                                 } else {
716                                         $order_string .= self::quoteIdentifier($order) . ", ";
717                                 }
718                         }
719                         $order_string = substr($order_string, 0, -2);
720                 }
721
722                 $limit_string = '';
723                 if (isset($params['limit']) && is_numeric($params['limit'])) {
724                         $limit_string = " LIMIT " . intval($params['limit']);
725                 }
726
727                 if (isset($params['limit']) && is_array($params['limit'])) {
728                         $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
729                 }
730
731                 return $groupby_string . $order_string . $limit_string;
732         }
733
734         /**
735          * Fills an array with data from a query
736          *
737          * @param object $stmt statement object
738          * @param bool   $do_close
739          * @return array Data array
740          */
741         public static function toArray($stmt, $do_close = true)
742         {
743                 return DI::dba()->toArray($stmt, $do_close);
744         }
745
746         /**
747          * Returns the error number of the last query
748          *
749          * @return string Error number (0 if no error)
750          */
751         public static function errorNo()
752         {
753                 return DI::dba()->errorNo();
754         }
755
756         /**
757          * Returns the error message of the last query
758          *
759          * @return string Error message ('' if no error)
760          */
761         public static function errorMessage()
762         {
763                 return DI::dba()->errorMessage();
764         }
765
766         /**
767          * Closes the current statement
768          *
769          * @param object $stmt statement object
770          * @return boolean was the close successful?
771          */
772         public static function close($stmt)
773         {
774                 return DI::dba()->close($stmt);
775         }
776
777         /**
778          * Return a list of database processes
779          *
780          * @return array
781          *      'list' => List of processes, separated in their different states
782          *      'amount' => Number of concurrent database processes
783          * @throws \Exception
784          */
785         public static function processlist()
786         {
787                 return DI::dba()->processlist();
788         }
789
790         /**
791          * Fetch a database variable
792          *
793          * @param string $name
794          * @return string content
795          */
796         public static function getVariable(string $name)
797         {
798                 return DI::dba()->getVariable($name);
799         }
800
801         /**
802          * Checks if $array is a filled array with at least one entry.
803          *
804          * @param mixed $array A filled array with at least one entry
805          *
806          * @return boolean Whether $array is a filled array or an object with rows
807          */
808         public static function isResult($array)
809         {
810                 return DI::dba()->isResult($array);
811         }
812
813         /**
814          * Escapes a whole array
815          *
816          * @param mixed   $arr           Array with values to be escaped
817          * @param boolean $add_quotation add quotation marks for string values
818          * @return void
819          */
820         public static function escapeArray(&$arr, $add_quotation = false)
821         {
822                 DI::dba()->escapeArray($arr, $add_quotation);
823         }
824 }