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