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\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
30 use Friendica\Protocol\Activity;
35 * Insert a new post entry
37 * @param integer $uri_id
38 * @param array $fields
39 * @return int ID of inserted post
42 public static function insert(int $uri_id, array $data = []): int
45 throw new BadMethodCallException('Empty URI_id');
48 $fields = DI::dbaDefinition()->truncateFieldsForTable('post', $data);
50 // Additionally assign the key fields
51 $fields['uri-id'] = $uri_id;
53 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
57 return DBA::lastInsertId();
61 * Fetch a single post row
63 * @param mixed $stmt statement object
64 * @return array|false current row or false
67 public static function fetch($stmt)
69 $row = DBA::fetch($stmt);
71 if (!is_array($row)) {
75 if (array_key_exists('verb', $row)) {
76 if (in_array($row['verb'], Item::ACTIVITIES)) {
77 if (array_key_exists('title', $row)) {
80 if (array_key_exists('body', $row)) {
81 $row['body'] = $row['verb'];
83 if (array_key_exists('object', $row)) {
86 if (array_key_exists('object-type', $row)) {
87 $row['object-type'] = Activity\ObjectType::NOTE;
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)) {
97 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
105 * Fills an array with data from a post query
107 * @param object|bool $stmt Return value from Database->select
108 * @return array Data array
111 public static function toArray($stmt): array
113 if (is_bool($stmt)) {
118 while ($row = self::fetch($stmt)) {
128 * Check if post-user-view records exists
130 * @param array $condition array of fields for condition
132 * @return boolean Are there rows for that condition?
135 public static function exists(array $condition): bool
137 return DBA::exists('post-user-view', $condition);
141 * Counts the post-user-view records satisfying the provided condition
143 * @param array $condition array of fields for condition
144 * @param array $params Array of several parameters
149 * $condition = ["uid" => 1, "network" => 'dspr'];
151 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
153 * $count = Post::count($condition);
156 public static function count(array $condition = [], array $params = []): int
158 return DBA::count('post-user-view', $condition, $params);
162 * Counts the post-thread-user-view records satisfying the provided condition
164 * @param array $condition array of fields for condition
165 * @param array $params Array of several parameters
170 * $condition = ["uid" => 1, "network" => 'dspr'];
172 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
174 * $count = Post::count($condition);
177 public static function countThread(array $condition = [], array $params = []): int
179 return DBA::count('post-thread-user-view', $condition, $params);
183 * Counts the post-view records satisfying the provided condition
185 * @param array $condition array of fields for condition
186 * @param array $params Array of several parameters
191 * $condition = ["network" => 'dspr'];
193 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
195 * $count = Post::count($condition);
198 public static function countPosts(array $condition = [], array $params = []): int
200 return DBA::count('post-view', $condition, $params);
204 * Retrieve a single record from the post-user-view view and returns it in an associative array
206 * @param array $fields
207 * @param array $condition
208 * @param array $params
209 * @param bool $user_mode true = post-user-view, false = post-view
214 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
216 $params['limit'] = 1;
218 $result = self::select($fields, $condition, $params);
220 if (is_bool($result)) {
223 $row = self::fetch($result);
230 * Retrieve a single record from the post-user-view view and returns it in an associative array
231 * When the requested record is a reshare activity, the system fetches the reshared original post.
232 * Otherwise the function reacts similar to selectFirst
234 * @param array $fields
235 * @param array $condition
236 * @param array $params
237 * @param bool $user_mode true = post-user-view, false = post-view
242 public static function selectOriginal(array $fields = [], array $condition = [], array $params = [])
244 $original_fields = $fields;
246 if (!empty($fields)) {
247 foreach (['gravity', 'verb', 'thr-parent-id', 'uid'] as $field) {
248 if (!in_array($field, $fields)) {
254 $result = self::selectFirst($fields, $condition, $params);
255 if (empty($result)) {
259 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
260 foreach ($remove as $field) {
261 unset($result[$field]);
266 $final_query_condition = ['uri-id' => $result['thr-parent-id']];
267 $final_query_condition = DBA::mergeConditions($final_query_condition, ['uid != 0']);
268 $final_params = ['order' => ['id']];
269 return self::selectFirst($original_fields, $final_query_condition, $final_params);
273 * Retrieve a single record from the post-view view and returns it in an associative array
275 * @param array $fields
276 * @param array $condition
277 * @param array $params
282 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
284 $params['limit'] = 1;
286 $result = self::selectPosts($fields, $condition, $params);
288 if (is_bool($result)) {
291 $row = self::fetch($result);
298 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
300 * @param array $fields
301 * @param array $condition
302 * @param array $params
307 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
309 $params['limit'] = 1;
311 $result = self::selectThread($fields, $condition, $params);
313 if (is_bool($result)) {
316 $row = self::fetch($result);
323 * Select rows from the post-user-view view and returns them as an array
325 * @param array $selected Array of selected fields, empty for all
326 * @param array $condition Array of fields for condition
327 * @param array $params Array of several parameters
332 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
334 $result = self::select($fields, $condition, $params);
336 if (is_bool($result)) {
341 while ($row = self::fetch($result)) {
350 * Select rows from the given view
352 * @param string $view View (post-user-view or post-thread-user-view)
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
357 * @return boolean|object
360 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
362 if (empty($selected)) {
363 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
365 if ($view == 'post-thread-user-view') {
366 $selected = array_merge($selected, ['ignored']);
370 $selected = array_unique($selected);
372 return DBA::select($view, $selected, $condition, $params);
376 * Select rows from the post-user-view view
378 * @param array $selected Array of selected fields, empty for all
379 * @param array $condition Array of fields for condition
380 * @param array $params Array of several parameters
382 * @return boolean|object
385 public static function select(array $selected = [], array $condition = [], array $params = [])
387 return self::selectView('post-user-view', $selected, $condition, $params);
391 * Select rows from the post-view view
393 * @param array $selected Array of selected fields, empty for all
394 * @param array $condition Array of fields for condition
395 * @param array $params Array of several parameters
397 * @return boolean|object
400 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
402 return self::selectView('post-view', $selected, $condition, $params);
406 * Select rows from the post-thread-user-view view
408 * @param array $selected Array of selected fields, empty for all
409 * @param array $condition Array of fields for condition
410 * @param array $params Array of several parameters
412 * @return boolean|object
415 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
417 return self::selectView('post-thread-user-view', $selected, $condition, $params);
421 * Select rows from the post-thread-view view
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
427 * @return boolean|object
430 public static function selectPostThread(array $selected = [], array $condition = [], array $params = [])
432 return self::selectView('post-thread-view', $selected, $condition, $params);
436 * Select rows from the given view for a given user
438 * @param string $view View (post-user-view or post-thread-user-view)
439 * @param integer $uid User ID
440 * @param array $selected Array of selected fields, empty for all
441 * @param array $condition Array of fields for condition
442 * @param array $params Array of several parameters
444 * @return boolean|object
447 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
449 if (empty($selected)) {
450 $selected = Item::DISPLAY_FIELDLIST;
453 $condition = DBA::mergeConditions($condition,
454 ["`visible` AND NOT `deleted`
455 AND NOT `author-blocked` AND NOT `owner-blocked`
456 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
457 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
458 OR `self` OR `contact-uid` = ?)
459 AND NOT `" . $view . "`.`uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `hidden`)
460 AND NOT `author-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `blocked` AND `cid` = `author-id`)
461 AND NOT `owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `blocked` AND `cid` = `owner-id`)
462 AND NOT `author-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `ignored` AND `cid` = `author-id`)
463 AND NOT `owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `ignored` AND `cid` = `owner-id`)",
464 0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid, $uid, $uid]);
466 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
468 $condition_string = DBA::buildCondition($condition);
469 $param_string = DBA::buildParameter($params);
471 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
472 $sql = DBA::cleanQuery($sql);
474 return DBA::p($sql, $condition);
478 * Select rows from the post-user-view view for a given user
480 * @param integer $uid User ID
481 * @param array $selected Array of selected fields, empty for all
482 * @param array $condition Array of fields for condition
483 * @param array $params Array of several parameters
485 * @return boolean|object
488 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
490 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
494 * Select rows from the post-view view for a given user
496 * @param integer $uid User ID
497 * @param array $selected Array of selected fields, empty for all
498 * @param array $condition Array of fields for condition
499 * @param array $params Array of several parameters
501 * @return boolean|object
504 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
506 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
510 * Select rows from the post-thread-user-view view for a given user
512 * @param integer $uid User ID
513 * @param array $selected Array of selected fields, empty for all
514 * @param array $condition Array of fields for condition
515 * @param array $params Array of several parameters
517 * @return boolean|object
520 public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
522 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
526 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
528 * @param integer $uid User ID
529 * @param array $selected
530 * @param array $condition
531 * @param array $params
536 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
538 $params['limit'] = 1;
540 $result = self::selectForUser($uid, $selected, $condition, $params);
542 if (is_bool($result)) {
545 $row = self::fetch($result);
552 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
553 * When the requested record is a reshare activity, the system fetches the reshared original post.
554 * Otherwise the function reacts similar to selectFirstForUser
556 * @param integer $uid User ID
557 * @param array $selected
558 * @param array $condition
559 * @param array $params
564 public static function selectOriginalForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
566 $original_selected = $selected;
568 if (!empty($selected)) {
569 foreach (['gravity', 'verb', 'thr-parent-id'] as $field) {
570 if (!in_array($field, $selected)) {
571 $selected[] = $field;
576 $result = self::selectFirstForUser($uid, $selected, $condition, $params);
577 if (empty($result)) {
581 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
582 foreach ($remove as $field) {
583 unset($result[$field]);
588 return self::selectFirstForUser($uid, $original_selected, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $uid]], $params);
592 * Update existing post entries
594 * @param array $fields The fields that are to be changed
595 * @param array $condition The condition for finding the item entries
597 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
599 * @return integer|boolean number of affected rows - or "false" if there was an error
600 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
602 public static function update(array $fields, array $condition)
606 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId(),'callstack' => System::callstack(10)]);
608 // Don't allow changes to fields that are responsible for the relation between the records
609 unset($fields['id']);
610 unset($fields['parent']);
611 unset($fields['uid']);
612 unset($fields['uri']);
613 unset($fields['uri-id']);
614 unset($fields['thr-parent']);
615 unset($fields['thr-parent-id']);
616 unset($fields['parent-uri']);
617 unset($fields['parent-uri-id']);
619 $thread_condition = DBA::mergeConditions($condition, ['gravity' => Item::GRAVITY_PARENT]);
621 // To ensure the data integrity we do it in an transaction
624 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-user', $fields);
625 if (!empty($update_fields)) {
627 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
628 while ($rows = DBA::toArray($posts, false, 100)) {
629 $puids = array_column($rows, 'post-user-id');
630 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
632 Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
635 $affected_count += DBA::affectedRows();
638 $affected = $affected_count;
641 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-content', $fields);
642 if (!empty($update_fields)) {
644 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
645 while ($rows = DBA::toArray($posts, false, 100)) {
646 $uriids = array_column($rows, 'uri-id');
647 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
649 Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
652 $affected_count += DBA::affectedRows();
655 $affected = max($affected, $affected_count);
658 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields);
659 if (!empty($update_fields)) {
661 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
662 while ($rows = DBA::toArray($posts, false, 100)) {
663 $uriids = array_column($rows, 'uri-id');
665 // Only delete the "post" entry when all "post-user" entries are deleted
666 if (!empty($update_fields['deleted']) && DBA::exists('post-user', ['uri-id' => $uriids, 'deleted' => false])) {
667 unset($update_fields['deleted']);
670 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
672 Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
675 $affected_count += DBA::affectedRows();
678 $affected = max($affected, $affected_count);
681 $update_fields = Post\DeliveryData::extractFields($fields);
682 if (!empty($update_fields)) {
684 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
685 while ($rows = DBA::toArray($posts, false, 100)) {
686 $uriids = array_column($rows, 'uri-id');
687 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
689 Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
692 $affected_count += DBA::affectedRows();
695 $affected = max($affected, $affected_count);
698 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields);
699 if (!empty($update_fields)) {
701 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
702 while ($rows = DBA::toArray($posts, false, 100)) {
703 $uriids = array_column($rows, 'uri-id');
704 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
706 Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
709 $affected_count += DBA::affectedRows();
712 $affected = max($affected, $affected_count);
715 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields);
716 if (!empty($update_fields)) {
718 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
719 while ($rows = DBA::toArray($posts, false, 100)) {
720 $thread_puids = array_column($rows, 'post-user-id');
721 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
723 Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
726 $affected_count += DBA::affectedRows();
729 $affected = max($affected, $affected_count);
734 Logger::info('Updated posts', ['rows' => $affected]);
739 * Delete a row from the post table
741 * @param array $conditions Field condition(s)
742 * @param array $options
743 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
744 * relations (default: true)
746 * @return boolean was the delete successful?
749 public static function delete(array $conditions, array $options = []): bool
751 return DBA::delete('post', $conditions, $options);