Issue 9906 (again): Provide index hints
[friendica.git/.git] / src / Model / Post.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\Model;
23
24 use BadMethodCallException;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
30 use Friendica\Protocol\Activity;
31
32 class Post
33 {
34         /**
35          * Insert a new post entry
36          *
37          * @param integer $uri_id
38          * @param array   $fields
39          * @return int    ID of inserted post
40          * @throws \Exception
41          */
42         public static function insert(int $uri_id, array $data = [])
43         {
44                 if (empty($uri_id)) {
45                         throw new BadMethodCallException('Empty URI_id');
46                 }
47
48                 $fields = DBStructure::getFieldsForTable('post', $data);
49
50                 // Additionally assign the key fields
51                 $fields['uri-id'] = $uri_id;
52
53                 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
54                         return 0;
55                 }
56
57                 return DBA::lastInsertId();
58         }
59
60         /**
61          * Fetch a single post row
62          *
63          * @param mixed $stmt statement object
64          * @return array|false current row or false
65          * @throws \Exception
66          */
67         public static function fetch($stmt)
68         {
69                 $row = DBA::fetch($stmt);
70
71                 if (!is_array($row)) {
72                         return $row;
73                 }
74
75                 if (array_key_exists('verb', $row)) {
76                         if (in_array($row['verb'], Item::ACTIVITIES)) {
77                                 if (array_key_exists('title', $row)) {
78                                         $row['title'] = '';
79                                 }
80                                 if (array_key_exists('body', $row)) {
81                                         $row['body'] = $row['verb'];
82                                 }
83                                 if (array_key_exists('object', $row)) {
84                                         $row['object'] = '';
85                                 }
86                                 if (array_key_exists('object-type', $row)) {
87                                         $row['object-type'] = Activity\ObjectType::NOTE;
88                                 }
89                         } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
90                                 // Posts don't have a target - but having tags or files.
91                                 if (array_key_exists('target', $row)) {
92                                         $row['target'] = '';
93                                 }
94                         }
95                 }
96
97                 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
98                         $row['extid'] = '';
99                 }
100
101                 return $row;
102         }
103
104         /**
105          * Fills an array with data from an post query
106          *
107          * @param object $stmt statement object
108          * @param bool   $do_close
109          * @return array Data array
110          */
111         public static function toArray($stmt, $do_close = true) {
112                 if (is_bool($stmt)) {
113                         return $stmt;
114                 }
115
116                 $data = [];
117                 while ($row = self::fetch($stmt)) {
118                         $data[] = $row;
119                 }
120                 if ($do_close) {
121                         DBA::close($stmt);
122                 }
123                 return $data;
124         }
125
126         /**
127          * Check if post data exists
128          *
129          * @param array $condition array of fields for condition
130          *
131          * @return boolean Are there rows for that condition?
132          * @throws \Exception
133          */
134         public static function exists($condition) {
135                 return DBA::exists('post-user-view', $condition);
136         }
137
138         /**
139          * Counts the posts satisfying the provided condition
140          *
141          * @param array        $condition array of fields for condition
142          * @param array        $params    Array of several parameters
143          *
144          * @return int
145          *
146          * Example:
147          * $condition = ["uid" => 1, "network" => 'dspr'];
148          * or:
149          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
150          *
151          * $count = Post::count($condition);
152          * @throws \Exception
153          */
154         public static function count(array $condition = [], array $params = [])
155         {
156                 return DBA::count('post-user-view', $condition, $params);
157         }
158
159         /**
160          * Retrieve a single record from the post table and returns it in an associative array
161          *
162          * @param array $fields
163          * @param array $condition
164          * @param array $params
165          * @return bool|array
166          * @throws \Exception
167          * @see   DBA::select
168          */
169         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
170         {
171                 $params['limit'] = 1;
172
173                 $result = self::select($fields, $condition, $params);
174
175                 if (is_bool($result)) {
176                         return $result;
177                 } else {
178                         $row = self::fetch($result);
179                         DBA::close($result);
180                         return $row;
181                 }
182         }
183
184         /**
185          * Retrieve a single record from the post-thread table and returns it in an associative array
186          *
187          * @param array $fields
188          * @param array $condition
189          * @param array $params
190          * @return bool|array
191          * @throws \Exception
192          * @see   DBA::select
193          */
194         public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
195         {
196                 $params['limit'] = 1;
197
198                 $result = self::selectThread($fields, $condition, $params);
199
200                 if (is_bool($result)) {
201                         return $result;
202                 } else {
203                         $row = self::fetch($result);
204                         DBA::close($result);
205                         return $row;
206                 }
207         }
208
209         /**
210          * Select rows from the post table and returns them as an array
211          *
212          * @param array $selected  Array of selected fields, empty for all
213          * @param array $condition Array of fields for condition
214          * @param array $params    Array of several parameters
215          *
216          * @return array
217          * @throws \Exception
218          */
219         public static function selectToArray(array $fields = [], array $condition = [], $params = [])
220         {
221                 $result = self::select($fields, $condition, $params);
222
223                 if (is_bool($result)) {
224                         return [];
225                 }
226
227                 $data = [];
228                 while ($row = self::fetch($result)) {
229                         $data[] = $row;
230                 }
231                 DBA::close($result);
232
233                 return $data;
234         }
235
236         /**
237          * Select rows from the given view
238          *
239          * @param string $view      View (post-user-view or post-thread-user-view)
240          * @param array  $selected  Array of selected fields, empty for all
241          * @param array  $condition Array of fields for condition
242          * @param array  $params    Array of several parameters
243          *
244          * @return boolean|object
245          * @throws \Exception
246          */
247         private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
248         {
249                 if (empty($selected)) {
250                         $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
251
252                         if ($view == 'post-thread-user-view') {
253                                 $selected = array_merge($selected, ['ignored']);
254                         }
255                 }
256
257                 $selected = array_unique($selected);
258
259                 return DBA::select($view, $selected, $condition, $params);
260         }
261
262         /**
263          * Select rows from the post table
264          *
265          * @param array $selected  Array of selected fields, empty for all
266          * @param array $condition Array of fields for condition
267          * @param array $params    Array of several parameters
268          *
269          * @return boolean|object
270          * @throws \Exception
271          */
272         public static function select(array $selected = [], array $condition = [], $params = [])
273         {
274                 return self::selectView('post-user-view', $selected, $condition, $params);
275         }
276
277         /**
278          * Select rows from the post table
279          *
280          * @param array $selected  Array of selected fields, empty for all
281          * @param array $condition Array of fields for condition
282          * @param array $params    Array of several parameters
283          *
284          * @return boolean|object
285          * @throws \Exception
286          */
287         public static function selectThread(array $selected = [], array $condition = [], $params = [])
288         {
289                 return self::selectView('post-thread-user-view', $selected, $condition, $params);
290         }
291
292         /**
293          * Select rows from the given view for a given user
294          *
295          * @param string  $view      View (post-user-view or post-thread-user-view)
296          * @param integer $uid       User ID
297          * @param array   $selected  Array of selected fields, empty for all
298          * @param array   $condition Array of fields for condition
299          * @param array   $params    Array of several parameters
300          *
301          * @return boolean|object
302          * @throws \Exception
303          */
304         private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
305         {
306                 if (empty($selected)) {
307                         $selected = Item::DISPLAY_FIELDLIST;
308                 }
309
310                 $condition = DBA::mergeConditions($condition,
311                         ["`visible` AND NOT `deleted`
312                         AND NOT `author-blocked` AND NOT `owner-blocked`
313                         AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
314                         AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
315                                 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
316                         AND NOT EXISTS (SELECT `uri-id` FROM `post-user` USE INDEX (`uid_uri-id`) WHERE `uid` = ? AND `uri-id` = `" . $view . "`.`uri-id` AND `hidden`)
317                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
318                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
319                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
320                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
321                         0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
322
323                 $select_string = '';
324
325                 if (in_array('pinned', $selected)) {
326                         $selected = array_flip($selected);
327                         unset($selected['pinned']);
328                         $selected = array_flip($selected);      
329
330                         $select_string = "(SELECT `pinned` FROM `post-thread-user` WHERE `uri-id` = `" . $view . "`.`uri-id` AND uid=`" . $view . "`.`uid`) AS `pinned`, ";
331                 }
332
333                 $select_string .= implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
334
335                 $condition_string = DBA::buildCondition($condition);
336                 $param_string = DBA::buildParameter($params);
337
338                 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
339                 $sql = DBA::cleanQuery($sql);
340
341                 return DBA::p($sql, $condition);
342         }
343
344         /**
345          * Select rows from the post view for a given user
346          *
347          * @param integer $uid       User ID
348          * @param array   $selected  Array of selected fields, empty for all
349          * @param array   $condition Array of fields for condition
350          * @param array   $params    Array of several parameters
351          *
352          * @return boolean|object
353          * @throws \Exception
354          */
355         public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
356         {
357                 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
358         }
359
360                 /**
361          * Select rows from the post view for a given user
362          *
363          * @param integer $uid       User ID
364          * @param array   $selected  Array of selected fields, empty for all
365          * @param array   $condition Array of fields for condition
366          * @param array   $params    Array of several parameters
367          *
368          * @return boolean|object
369          * @throws \Exception
370          */
371         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
372         {
373                 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
374         }
375
376         /**
377          * Retrieve a single record from the post view for a given user and returns it in an associative array
378          *
379          * @param integer $uid User ID
380          * @param array   $selected
381          * @param array   $condition
382          * @param array   $params
383          * @return bool|array
384          * @throws \Exception
385          * @see   DBA::select
386          */
387         public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
388         {
389                 $params['limit'] = 1;
390
391                 $result = self::selectForUser($uid, $selected, $condition, $params);
392
393                 if (is_bool($result)) {
394                         return $result;
395                 } else {
396                         $row = self::fetch($result);
397                         DBA::close($result);
398                         return $row;
399                 }
400         }
401
402         /**
403          * Select pinned rows from the item table for a given user
404          *
405          * @param integer $uid       User ID
406          * @param array   $selected  Array of selected fields, empty for all
407          * @param array   $condition Array of fields for condition
408          * @param array   $params    Array of several parameters
409          *
410          * @return boolean|object
411          * @throws \Exception
412          */
413         public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
414         {
415                 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
416                 if (!DBA::isResult($postthreaduser)) {
417                         return $postthreaduser;
418                 }
419         
420                 $pinned = [];
421                 while ($useritem = DBA::fetch($postthreaduser)) {
422                         $pinned[] = $useritem['uri-id'];
423                 }
424                 DBA::close($postthreaduser);
425
426                 if (empty($pinned)) {
427                         return [];
428                 }
429
430                 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
431
432                 return self::selectForUser($uid, $selected, $condition, $params);
433         }
434
435         /**
436          * Update existing post entries
437          *
438          * @param array $fields    The fields that are to be changed
439          * @param array $condition The condition for finding the item entries
440          *
441          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
442          *
443          * @return integer|boolean number of affected rows - or "false" if there was an error
444          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
445          */
446         public static function update(array $fields, array $condition)
447         {
448                 $affected = 0;
449
450                 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => local_user(),'callstack' => System::callstack(10)]);
451
452                 // Don't allow changes to fields that are responsible for the relation between the records
453                 unset($fields['id']);
454                 unset($fields['parent']);
455                 unset($fields['uid']);
456                 unset($fields['uri']);
457                 unset($fields['uri-id']);
458                 unset($fields['thr-parent']);
459                 unset($fields['thr-parent-id']);
460                 unset($fields['parent-uri']);
461                 unset($fields['parent-uri-id']);
462
463                 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
464
465                 // To ensure the data integrity we do it in an transaction
466                 DBA::transaction();
467
468                 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
469                 if (!empty($update_fields)) {
470                         $affected_count = 0;
471                         $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
472                         while ($rows = DBA::toArray($posts, false, 100)) {
473                                 $puids = array_column($rows, 'post-user-id');
474                                 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
475                                         DBA::rollback();
476                                         Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
477                                         return false;
478                                 }
479                                 $affected_count += DBA::affectedRows();
480                         }
481                         DBA::close($posts);
482                         $affected = $affected_count;
483                 }
484
485                 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
486                 if (!empty($update_fields)) {
487                         $affected_count = 0;
488                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
489                         while ($rows = DBA::toArray($posts, false, 100)) {
490                                 $uriids = array_column($rows, 'uri-id');
491                                 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
492                                         DBA::rollback();
493                                         Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
494                                         return false;
495                                 }
496                                 $affected_count += DBA::affectedRows();
497                         }
498                         DBA::close($posts);
499                         $affected = max($affected, $affected_count);
500                 }
501
502                 $update_fields = DBStructure::getFieldsForTable('post', $fields);
503                 if (!empty($update_fields)) {
504                         $affected_count = 0;
505                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
506                         while ($rows = DBA::toArray($posts, false, 100)) {
507                                 $uriids = array_column($rows, 'uri-id');
508                                 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
509                                         DBA::rollback();
510                                         Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
511                                         return false;
512                                 }
513                                 $affected_count += DBA::affectedRows();
514                         }
515                         DBA::close($posts);
516                         $affected = max($affected, $affected_count);
517                 }
518
519                 $update_fields = Post\DeliveryData::extractFields($fields);
520                 if (!empty($update_fields)) {
521                         $affected_count = 0;
522                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
523                         while ($rows = DBA::toArray($posts, false, 100)) {
524                                 $uriids = array_column($rows, 'uri-id');
525                                 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
526                                         DBA::rollback();
527                                         Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
528                                         return false;
529                                 }
530                                 $affected_count += DBA::affectedRows();
531                         }
532                         DBA::close($posts);
533                         $affected = max($affected, $affected_count);
534                 }
535
536                 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
537                 if (!empty($update_fields)) {
538                         $affected_count = 0;
539                         $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
540                         while ($rows = DBA::toArray($posts, false, 100)) {
541                                 $uriids = array_column($rows, 'uri-id');
542                                 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
543                                         DBA::rollback();
544                                         Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
545                                         return false;
546                                 }
547                                 $affected_count += DBA::affectedRows();
548                         }
549                         DBA::close($posts);
550                         $affected = max($affected, $affected_count);
551                 }
552
553                 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
554                 if (!empty($update_fields)) {
555                         $affected_count = 0;
556                         $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
557                         while ($rows = DBA::toArray($posts, false, 100)) {
558                                 $thread_puids = array_column($rows, 'post-user-id');
559                                 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
560                                         DBA::rollback();
561                                         Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
562                                         return false;
563                                 }
564                                 $affected_count += DBA::affectedRows();
565                         }
566                         DBA::close($posts);
567                         $affected = max($affected, $affected_count);
568                 }
569
570                 DBA::commit();
571
572                 Logger::info('Updated posts', ['rows' => $affected]);
573                 return $affected;
574         }
575
576         /**
577          * Delete a row from the post table
578          *
579          * @param array        $conditions Field condition(s)
580          * @param array        $options
581          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
582          *                           relations (default: true)
583          *
584          * @return boolean was the delete successful?
585          * @throws \Exception
586          */
587         public static function delete(array $conditions, array $options = [])
588         {
589                 return DBA::delete('post', $conditions, $options);
590         }
591 }