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 return self::selectFirst($original_fields, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $result['uid']]], $params);
270 * Retrieve a single record from the post-view view and returns it in an associative array
272 * @param array $fields
273 * @param array $condition
274 * @param array $params
279 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
281 $params['limit'] = 1;
283 $result = self::selectPosts($fields, $condition, $params);
285 if (is_bool($result)) {
288 $row = self::fetch($result);
295 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
297 * @param array $fields
298 * @param array $condition
299 * @param array $params
304 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
306 $params['limit'] = 1;
308 $result = self::selectThread($fields, $condition, $params);
310 if (is_bool($result)) {
313 $row = self::fetch($result);
320 * Select rows from the post-user-view view and returns them as an array
322 * @param array $selected Array of selected fields, empty for all
323 * @param array $condition Array of fields for condition
324 * @param array $params Array of several parameters
329 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
331 $result = self::select($fields, $condition, $params);
333 if (is_bool($result)) {
338 while ($row = self::fetch($result)) {
347 * Select rows from the given view
349 * @param string $view View (post-user-view or post-thread-user-view)
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
354 * @return boolean|object
357 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
359 if (empty($selected)) {
360 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
362 if ($view == 'post-thread-user-view') {
363 $selected = array_merge($selected, ['ignored']);
367 $selected = array_unique($selected);
369 return DBA::select($view, $selected, $condition, $params);
373 * Select rows from the post-user-view view
375 * @param array $selected Array of selected fields, empty for all
376 * @param array $condition Array of fields for condition
377 * @param array $params Array of several parameters
379 * @return boolean|object
382 public static function select(array $selected = [], array $condition = [], array $params = [])
384 return self::selectView('post-user-view', $selected, $condition, $params);
388 * Select rows from the post-view view
390 * @param array $selected Array of selected fields, empty for all
391 * @param array $condition Array of fields for condition
392 * @param array $params Array of several parameters
394 * @return boolean|object
397 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
399 return self::selectView('post-view', $selected, $condition, $params);
403 * Select rows from the post-thread-user-view view
405 * @param array $selected Array of selected fields, empty for all
406 * @param array $condition Array of fields for condition
407 * @param array $params Array of several parameters
409 * @return boolean|object
412 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
414 return self::selectView('post-thread-user-view', $selected, $condition, $params);
418 * Select rows from the post-thread-view view
420 * @param array $selected Array of selected fields, empty for all
421 * @param array $condition Array of fields for condition
422 * @param array $params Array of several parameters
424 * @return boolean|object
427 public static function selectPostThread(array $selected = [], array $condition = [], array $params = [])
429 return self::selectView('post-thread-view', $selected, $condition, $params);
433 * Select rows from the given view for a given user
435 * @param string $view View (post-user-view or post-thread-user-view)
436 * @param integer $uid User ID
437 * @param array $selected Array of selected fields, empty for all
438 * @param array $condition Array of fields for condition
439 * @param array $params Array of several parameters
441 * @return boolean|object
444 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
446 if (empty($selected)) {
447 $selected = Item::DISPLAY_FIELDLIST;
450 $condition = DBA::mergeConditions($condition,
451 ["`visible` AND NOT `deleted`
452 AND NOT `author-blocked` AND NOT `owner-blocked`
453 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
454 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
455 OR `self` OR `contact-uid` = ?)
456 AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = " . DBA::quoteIdentifier($view) . ".`uri-id` AND `hidden`)
457 AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` IN (`author-id`, `owner-id`) AND (`blocked` OR `ignored`))
458 AND NOT EXISTS(SELECT `gsid` FROM `user-gserver` WHERE `uid` = ? AND `gsid` IN (`author-gsid`, `owner-gsid`, `causer-gsid`) AND `ignored`)",
459 0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid]);
461 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
463 $condition_string = DBA::buildCondition($condition);
464 $param_string = DBA::buildParameter($params);
466 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
467 $sql = DBA::cleanQuery($sql);
469 return DBA::p($sql, $condition);
473 * Select rows from the post-user-view view for a given user
475 * @param integer $uid User ID
476 * @param array $selected Array of selected fields, empty for all
477 * @param array $condition Array of fields for condition
478 * @param array $params Array of several parameters
480 * @return boolean|object
483 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
485 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
489 * Select rows from the post-view view for a given user
491 * @param integer $uid User ID
492 * @param array $selected Array of selected fields, empty for all
493 * @param array $condition Array of fields for condition
494 * @param array $params Array of several parameters
496 * @return boolean|object
499 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
501 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
505 * Select rows from the post-thread-user-view view for a given user
507 * @param integer $uid User ID
508 * @param array $selected Array of selected fields, empty for all
509 * @param array $condition Array of fields for condition
510 * @param array $params Array of several parameters
512 * @return boolean|object
515 public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
517 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
521 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
523 * @param integer $uid User ID
524 * @param array $selected
525 * @param array $condition
526 * @param array $params
531 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
533 $params['limit'] = 1;
535 $result = self::selectForUser($uid, $selected, $condition, $params);
537 if (is_bool($result)) {
540 $row = self::fetch($result);
547 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
548 * When the requested record is a reshare activity, the system fetches the reshared original post.
549 * Otherwise the function reacts similar to selectFirstForUser
551 * @param integer $uid User ID
552 * @param array $selected
553 * @param array $condition
554 * @param array $params
559 public static function selectOriginalForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
561 $original_selected = $selected;
563 if (!empty($selected)) {
564 foreach (['gravity', 'verb', 'thr-parent-id'] as $field) {
565 if (!in_array($field, $selected)) {
566 $selected[] = $field;
571 $result = self::selectFirstForUser($uid, $selected, $condition, $params);
572 if (empty($result)) {
576 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
577 foreach ($remove as $field) {
578 unset($result[$field]);
583 return self::selectFirstForUser($uid, $original_selected, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $uid]], $params);
587 * Update existing post entries
589 * @param array $fields The fields that are to be changed
590 * @param array $condition The condition for finding the item entries
592 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
594 * @return integer|boolean number of affected rows - or "false" if there was an error
595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 public static function update(array $fields, array $condition)
601 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId(),'callstack' => System::callstack(10)]);
603 // Don't allow changes to fields that are responsible for the relation between the records
604 unset($fields['id']);
605 unset($fields['parent']);
606 unset($fields['uid']);
607 unset($fields['uri']);
608 unset($fields['uri-id']);
609 unset($fields['thr-parent']);
610 unset($fields['thr-parent-id']);
611 unset($fields['parent-uri']);
612 unset($fields['parent-uri-id']);
614 $thread_condition = DBA::mergeConditions($condition, ['gravity' => Item::GRAVITY_PARENT]);
616 // To ensure the data integrity we do it in an transaction
619 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-user', $fields);
620 if (!empty($update_fields)) {
622 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
623 while ($rows = DBA::toArray($posts, false, 100)) {
624 $puids = array_column($rows, 'post-user-id');
625 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
627 Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
630 $affected_count += DBA::affectedRows();
633 $affected = $affected_count;
636 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-content', $fields);
637 if (!empty($update_fields)) {
639 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
640 while ($rows = DBA::toArray($posts, false, 100)) {
641 $uriids = array_column($rows, 'uri-id');
642 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
644 Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
647 $affected_count += DBA::affectedRows();
650 $affected = max($affected, $affected_count);
653 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields);
654 if (!empty($update_fields)) {
656 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
657 while ($rows = DBA::toArray($posts, false, 100)) {
658 $uriids = array_column($rows, 'uri-id');
660 // Only delete the "post" entry when all "post-user" entries are deleted
661 if (!empty($update_fields['deleted']) && DBA::exists('post-user', ['uri-id' => $uriids, 'deleted' => false])) {
662 unset($update_fields['deleted']);
665 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
667 Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
670 $affected_count += DBA::affectedRows();
673 $affected = max($affected, $affected_count);
676 $update_fields = Post\DeliveryData::extractFields($fields);
677 if (!empty($update_fields)) {
679 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
680 while ($rows = DBA::toArray($posts, false, 100)) {
681 $uriids = array_column($rows, 'uri-id');
682 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
684 Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
687 $affected_count += DBA::affectedRows();
690 $affected = max($affected, $affected_count);
693 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields);
694 if (!empty($update_fields)) {
696 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
697 while ($rows = DBA::toArray($posts, false, 100)) {
698 $uriids = array_column($rows, 'uri-id');
699 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
701 Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
704 $affected_count += DBA::affectedRows();
707 $affected = max($affected, $affected_count);
710 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields);
711 if (!empty($update_fields)) {
713 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
714 while ($rows = DBA::toArray($posts, false, 100)) {
715 $thread_puids = array_column($rows, 'post-user-id');
716 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
718 Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
721 $affected_count += DBA::affectedRows();
724 $affected = max($affected, $affected_count);
729 Logger::info('Updated posts', ['rows' => $affected]);
734 * Delete a row from the post table
736 * @param array $conditions Field condition(s)
737 * @param array $options
738 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
739 * relations (default: true)
741 * @return boolean was the delete successful?
744 public static function delete(array $conditions, array $options = []): bool
746 return DBA::delete('post', $conditions, $options);