3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model;
24 use BadMethodCallException;
25 use Friendica\Core\Logger;
26 use Friendica\Database\Database;
27 use Friendica\Database\DBA;
29 use Friendica\Protocol\Activity;
34 * Insert a new post entry
36 * @param integer $uri_id
37 * @param array $fields
38 * @return bool Success of the insert process
41 public static function insert(int $uri_id, array $data = []): bool
44 throw new BadMethodCallException('Empty URI_id');
47 $fields = DI::dbaDefinition()->truncateFieldsForTable('post', $data);
49 // Additionally assign the key fields
50 $fields['uri-id'] = $uri_id;
52 return DBA::insert('post', $fields, Database::INSERT_IGNORE);
56 * Fetch a single post row
58 * @param mixed $stmt statement object
59 * @return array|false current row or false
62 public static function fetch($stmt)
64 $row = DBA::fetch($stmt);
66 if (!is_array($row)) {
70 if (array_key_exists('verb', $row)) {
71 if (in_array($row['verb'], Item::ACTIVITIES)) {
72 if (array_key_exists('title', $row)) {
75 if (array_key_exists('body', $row)) {
76 $row['body'] = $row['verb'];
78 if (array_key_exists('object', $row)) {
81 if (array_key_exists('object-type', $row)) {
82 $row['object-type'] = Activity\ObjectType::NOTE;
84 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
85 // Posts don't have a target - but having tags or files.
86 if (array_key_exists('target', $row)) {
92 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
100 * Fills an array with data from a post query
102 * @param object|bool $stmt Return value from Database->select
103 * @return array Data array
106 public static function toArray($stmt): array
108 if (is_bool($stmt)) {
113 while ($row = self::fetch($stmt)) {
123 * Check if post-user-view records exists
125 * @param array $condition array of fields for condition
127 * @return boolean Are there rows for that condition?
130 public static function exists(array $condition): bool
132 return DBA::exists('post-user-view', $condition);
136 * Counts the post-user-view records satisfying the provided condition
138 * @param array $condition array of fields for condition
139 * @param array $params Array of several parameters
144 * $condition = ["uid" => 1, "network" => 'dspr'];
146 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
148 * $count = Post::count($condition);
151 public static function count(array $condition = [], array $params = []): int
153 return DBA::count('post-user-view', $condition, $params);
157 * Counts the post-thread-user-view records satisfying the provided condition
159 * @param array $condition array of fields for condition
160 * @param array $params Array of several parameters
165 * $condition = ["uid" => 1, "network" => 'dspr'];
167 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
169 * $count = Post::count($condition);
172 public static function countThread(array $condition = [], array $params = []): int
174 return DBA::count('post-thread-user-view', $condition, $params);
178 * Counts the post-view records satisfying the provided condition
180 * @param array $condition array of fields for condition
181 * @param array $params Array of several parameters
186 * $condition = ["network" => 'dspr'];
188 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
190 * $count = Post::count($condition);
193 public static function countPosts(array $condition = [], array $params = []): int
195 return DBA::count('post-view', $condition, $params);
199 * Retrieve a single record from the post-user-view view and returns it in an associative array
201 * @param array $fields
202 * @param array $condition
203 * @param array $params
204 * @param bool $user_mode true = post-user-view, false = post-view
209 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
211 $params['limit'] = 1;
213 $result = self::select($fields, $condition, $params);
215 if (is_bool($result)) {
218 $row = self::fetch($result);
225 * Retrieve a single record from the post-user-view view and returns it in an associative array
226 * When the requested record is a reshare activity, the system fetches the reshared original post.
227 * Otherwise the function reacts similar to selectFirst
229 * @param array $fields
230 * @param array $condition
231 * @param array $params
232 * @param bool $user_mode true = post-user-view, false = post-view
237 public static function selectOriginal(array $fields = [], array $condition = [], array $params = [])
239 $original_fields = $fields;
241 if (!empty($fields)) {
242 foreach (['gravity', 'verb', 'thr-parent-id', 'uid'] as $field) {
243 if (!in_array($field, $fields)) {
249 $result = self::selectFirst($fields, $condition, $params);
250 if (empty($result)) {
254 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
255 foreach ($remove as $field) {
256 unset($result[$field]);
261 return self::selectFirst($original_fields, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $result['uid']]], $params);
265 * Retrieve a single record from the post-view view and returns it in an associative array
267 * @param array $fields
268 * @param array $condition
269 * @param array $params
274 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
276 $params['limit'] = 1;
278 $result = self::selectPosts($fields, $condition, $params);
280 if (is_bool($result)) {
283 $row = self::fetch($result);
290 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
292 * @param array $fields
293 * @param array $condition
294 * @param array $params
299 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
301 $params['limit'] = 1;
303 $result = self::selectThread($fields, $condition, $params);
305 if (is_bool($result)) {
308 $row = self::fetch($result);
315 * Select rows from the post-user-view view and returns them as an array
317 * @param array $selected Array of selected fields, empty for all
318 * @param array $condition Array of fields for condition
319 * @param array $params Array of several parameters
324 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
326 $result = self::select($fields, $condition, $params);
328 if (is_bool($result)) {
333 while ($row = self::fetch($result)) {
342 * Select rows from the given view
344 * @param string $view View (post-user-view or post-thread-user-view)
345 * @param array $selected Array of selected fields, empty for all
346 * @param array $condition Array of fields for condition
347 * @param array $params Array of several parameters
349 * @return boolean|object
352 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
354 if (empty($selected)) {
355 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
357 if ($view == 'post-thread-user-view') {
358 $selected = array_merge($selected, ['ignored']);
362 $selected = array_unique($selected);
364 return DBA::select($view, $selected, $condition, $params);
368 * Select rows from the post-user-view view
370 * @param array $selected Array of selected fields, empty for all
371 * @param array $condition Array of fields for condition
372 * @param array $params Array of several parameters
374 * @return boolean|object
377 public static function select(array $selected = [], array $condition = [], array $params = [])
379 return self::selectView('post-user-view', $selected, $condition, $params);
383 * Select rows from the post-view view
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
389 * @return boolean|object
392 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
394 return self::selectView('post-view', $selected, $condition, $params);
398 * Select rows from the post-thread-user-view view
400 * @param array $selected Array of selected fields, empty for all
401 * @param array $condition Array of fields for condition
402 * @param array $params Array of several parameters
404 * @return boolean|object
407 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
409 return self::selectView('post-thread-user-view', $selected, $condition, $params);
413 * Select rows from the post-thread-view view
415 * @param array $selected Array of selected fields, empty for all
416 * @param array $condition Array of fields for condition
417 * @param array $params Array of several parameters
419 * @return boolean|object
422 public static function selectPostThread(array $selected = [], array $condition = [], array $params = [])
424 return self::selectView('post-thread-view', $selected, $condition, $params);
428 * Select rows from the given view for a given user
430 * @param string $view View (post-user-view or post-thread-user-view)
431 * @param integer $uid User ID
432 * @param array $selected Array of selected fields, empty for all
433 * @param array $condition Array of fields for condition
434 * @param array $params Array of several parameters
436 * @return boolean|object
439 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
441 if (empty($selected)) {
442 $selected = Item::DISPLAY_FIELDLIST;
445 $condition = DBA::mergeConditions($condition,
446 ["`visible` AND NOT `deleted`
447 AND NOT `author-blocked` AND NOT `owner-blocked`
448 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
449 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
450 OR `self` OR `contact-uid` = ?)
451 AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = " . DBA::quoteIdentifier($view) . ".`uri-id` AND `hidden`)
452 AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` IN (`author-id`, `owner-id`) AND (`blocked` OR `ignored`))
453 AND NOT EXISTS(SELECT `gsid` FROM `user-gserver` WHERE `uid` = ? AND `gsid` IN (`author-gsid`, `owner-gsid`, `causer-gsid`) AND `ignored`)",
454 0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid]);
456 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
458 $condition_string = DBA::buildCondition($condition);
459 $param_string = DBA::buildParameter($params);
461 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
462 $sql = DBA::cleanQuery($sql);
464 return DBA::p($sql, $condition);
468 * Select rows from the post-user-view view for a given user
470 * @param integer $uid User ID
471 * @param array $selected Array of selected fields, empty for all
472 * @param array $condition Array of fields for condition
473 * @param array $params Array of several parameters
475 * @return boolean|object
478 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
480 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
484 * Select rows from the post-view view for a given user
486 * @param integer $uid User ID
487 * @param array $selected Array of selected fields, empty for all
488 * @param array $condition Array of fields for condition
489 * @param array $params Array of several parameters
491 * @return boolean|object
494 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
496 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
500 * Select rows from the post-timeline-view view for a given user
501 * This function is used for API calls.
503 * @param integer $uid User ID
504 * @param array $selected Array of selected fields, empty for all
505 * @param array $condition Array of fields for condition
506 * @param array $params Array of several parameters
508 * @return boolean|object
511 public static function selectTimelineForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
513 return self::selectViewForUser('post-timeline-view', $uid, $selected, $condition, $params);
517 * Select rows from the post-thread-user-view view for a given user
519 * @param integer $uid User ID
520 * @param array $selected Array of selected fields, empty for all
521 * @param array $condition Array of fields for condition
522 * @param array $params Array of several parameters
524 * @return boolean|object
527 public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
529 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
533 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
535 * @param integer $uid User ID
536 * @param array $selected
537 * @param array $condition
538 * @param array $params
543 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
545 $params['limit'] = 1;
547 $result = self::selectForUser($uid, $selected, $condition, $params);
549 if (is_bool($result)) {
552 $row = self::fetch($result);
559 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
560 * When the requested record is a reshare activity, the system fetches the reshared original post.
561 * Otherwise the function reacts similar to selectFirstForUser
563 * @param integer $uid User ID
564 * @param array $selected
565 * @param array $condition
566 * @param array $params
571 public static function selectOriginalForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
573 $original_selected = $selected;
575 if (!empty($selected)) {
576 foreach (['gravity', 'verb', 'thr-parent-id'] as $field) {
577 if (!in_array($field, $selected)) {
578 $selected[] = $field;
583 $result = self::selectFirstForUser($uid, $selected, $condition, $params);
584 if (empty($result)) {
588 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
589 foreach ($remove as $field) {
590 unset($result[$field]);
595 return self::selectFirstForUser($uid, $original_selected, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $uid]], $params);
599 * Update existing post entries
601 * @param array $fields The fields that are to be changed
602 * @param array $condition The condition for finding the item entries
604 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
606 * @return integer|boolean number of affected rows - or "false" if there was an error
607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
609 public static function update(array $fields, array $condition)
613 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId()]);
615 // Don't allow changes to fields that are responsible for the relation between the records
616 unset($fields['id']);
617 unset($fields['parent']);
618 unset($fields['uid']);
619 unset($fields['uri']);
620 unset($fields['uri-id']);
621 unset($fields['thr-parent']);
622 unset($fields['thr-parent-id']);
623 unset($fields['parent-uri']);
624 unset($fields['parent-uri-id']);
626 $thread_condition = DBA::mergeConditions($condition, ['gravity' => Item::GRAVITY_PARENT]);
628 // To ensure the data integrity we do it in an transaction
631 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-user', $fields);
632 if (!empty($update_fields)) {
634 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
635 while ($rows = DBA::toArray($posts, false, 100)) {
636 $puids = array_column($rows, 'post-user-id');
637 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
639 Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
642 $affected_count += DBA::affectedRows();
645 $affected = $affected_count;
648 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-content', $fields);
649 if (!empty($update_fields)) {
651 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
652 while ($rows = DBA::toArray($posts, false, 100)) {
653 $uriids = array_column($rows, 'uri-id');
654 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
656 Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
659 $affected_count += DBA::affectedRows();
662 $affected = max($affected, $affected_count);
665 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields);
666 if (!empty($update_fields)) {
668 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
669 while ($rows = DBA::toArray($posts, false, 100)) {
670 $uriids = array_column($rows, 'uri-id');
672 // Only delete the "post" entry when all "post-user" entries are deleted
673 if (!empty($update_fields['deleted']) && DBA::exists('post-user', ['uri-id' => $uriids, 'deleted' => false])) {
674 unset($update_fields['deleted']);
677 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
679 Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
682 $affected_count += DBA::affectedRows();
685 $affected = max($affected, $affected_count);
688 $update_fields = Post\DeliveryData::extractFields($fields);
689 if (!empty($update_fields)) {
691 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
692 while ($rows = DBA::toArray($posts, false, 100)) {
693 $uriids = array_column($rows, 'uri-id');
694 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
696 Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
699 $affected_count += DBA::affectedRows();
702 $affected = max($affected, $affected_count);
705 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields);
706 if (!empty($update_fields)) {
708 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
709 while ($rows = DBA::toArray($posts, false, 100)) {
710 $uriids = array_column($rows, 'uri-id');
711 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
713 Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
716 $affected_count += DBA::affectedRows();
719 $affected = max($affected, $affected_count);
722 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields);
723 if (!empty($update_fields)) {
725 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
726 while ($rows = DBA::toArray($posts, false, 100)) {
727 $thread_puids = array_column($rows, 'post-user-id');
728 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
730 Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
733 $affected_count += DBA::affectedRows();
736 $affected = max($affected, $affected_count);
741 Logger::info('Updated posts', ['rows' => $affected]);
746 * Delete a row from the post table
748 * @param array $conditions Field condition(s)
749 * @param array $options
750 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
751 * relations (default: true)
753 * @return boolean was the delete successful?
756 public static function delete(array $conditions, array $options = []): bool
758 return DBA::delete('post', $conditions, $options);