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