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