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 bool Success of the insert process
42 public static function insert(int $uri_id, array $data = []): bool
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 return DBA::insert('post', $fields, Database::INSERT_IGNORE);
57 * Fetch a single post row
59 * @param mixed $stmt statement object
60 * @return array|false current row or false
63 public static function fetch($stmt)
65 $row = DBA::fetch($stmt);
67 if (!is_array($row)) {
71 if (array_key_exists('verb', $row)) {
72 if (in_array($row['verb'], Item::ACTIVITIES)) {
73 if (array_key_exists('title', $row)) {
76 if (array_key_exists('body', $row)) {
77 $row['body'] = $row['verb'];
79 if (array_key_exists('object', $row)) {
82 if (array_key_exists('object-type', $row)) {
83 $row['object-type'] = Activity\ObjectType::NOTE;
85 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
86 // Posts don't have a target - but having tags or files.
87 if (array_key_exists('target', $row)) {
93 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
101 * Fills an array with data from a post query
103 * @param object|bool $stmt Return value from Database->select
104 * @return array Data array
107 public static function toArray($stmt): array
109 if (is_bool($stmt)) {
114 while ($row = self::fetch($stmt)) {
124 * Check if post-user-view records exists
126 * @param array $condition array of fields for condition
128 * @return boolean Are there rows for that condition?
131 public static function exists(array $condition): bool
133 return DBA::exists('post-user-view', $condition);
137 * Counts the post-user-view records satisfying the provided condition
139 * @param array $condition array of fields for condition
140 * @param array $params Array of several parameters
145 * $condition = ["uid" => 1, "network" => 'dspr'];
147 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
149 * $count = Post::count($condition);
152 public static function count(array $condition = [], array $params = []): int
154 return DBA::count('post-user-view', $condition, $params);
158 * Counts the post-thread-user-view records satisfying the provided condition
160 * @param array $condition array of fields for condition
161 * @param array $params Array of several parameters
166 * $condition = ["uid" => 1, "network" => 'dspr'];
168 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
170 * $count = Post::count($condition);
173 public static function countThread(array $condition = [], array $params = []): int
175 return DBA::count('post-thread-user-view', $condition, $params);
179 * Counts the post-view records satisfying the provided condition
181 * @param array $condition array of fields for condition
182 * @param array $params Array of several parameters
187 * $condition = ["network" => 'dspr'];
189 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
191 * $count = Post::count($condition);
194 public static function countPosts(array $condition = [], array $params = []): int
196 return DBA::count('post-view', $condition, $params);
200 * Retrieve a single record from the post-user-view view and returns it in an associative array
202 * @param array $fields
203 * @param array $condition
204 * @param array $params
205 * @param bool $user_mode true = post-user-view, false = post-view
210 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
212 $params['limit'] = 1;
214 $result = self::select($fields, $condition, $params);
216 if (is_bool($result)) {
219 $row = self::fetch($result);
226 * Retrieve a single record from the post-user-view view and returns it in an associative array
227 * When the requested record is a reshare activity, the system fetches the reshared original post.
228 * Otherwise the function reacts similar to selectFirst
230 * @param array $fields
231 * @param array $condition
232 * @param array $params
233 * @param bool $user_mode true = post-user-view, false = post-view
238 public static function selectOriginal(array $fields = [], array $condition = [], array $params = [])
240 $original_fields = $fields;
242 if (!empty($fields)) {
243 foreach (['gravity', 'verb', 'thr-parent-id', 'uid'] as $field) {
244 if (!in_array($field, $fields)) {
250 $result = self::selectFirst($fields, $condition, $params);
251 if (empty($result)) {
255 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
256 foreach ($remove as $field) {
257 unset($result[$field]);
262 return self::selectFirst($original_fields, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $result['uid']]], $params);
266 * Retrieve a single record from the post-view view and returns it in an associative array
268 * @param array $fields
269 * @param array $condition
270 * @param array $params
275 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
277 $params['limit'] = 1;
279 $result = self::selectPosts($fields, $condition, $params);
281 if (is_bool($result)) {
284 $row = self::fetch($result);
291 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
293 * @param array $fields
294 * @param array $condition
295 * @param array $params
300 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
302 $params['limit'] = 1;
304 $result = self::selectThread($fields, $condition, $params);
306 if (is_bool($result)) {
309 $row = self::fetch($result);
316 * Select rows from the post-user-view view and returns them as an array
318 * @param array $selected Array of selected fields, empty for all
319 * @param array $condition Array of fields for condition
320 * @param array $params Array of several parameters
325 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
327 $result = self::select($fields, $condition, $params);
329 if (is_bool($result)) {
334 while ($row = self::fetch($result)) {
343 * Select rows from the given view
345 * @param string $view View (post-user-view or post-thread-user-view)
346 * @param array $selected Array of selected fields, empty for all
347 * @param array $condition Array of fields for condition
348 * @param array $params Array of several parameters
350 * @return boolean|object
353 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
355 if (empty($selected)) {
356 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
358 if ($view == 'post-thread-user-view') {
359 $selected = array_merge($selected, ['ignored']);
363 $selected = array_unique($selected);
365 return DBA::select($view, $selected, $condition, $params);
369 * Select rows from the post-user-view view
371 * @param array $selected Array of selected fields, empty for all
372 * @param array $condition Array of fields for condition
373 * @param array $params Array of several parameters
375 * @return boolean|object
378 public static function select(array $selected = [], array $condition = [], array $params = [])
380 return self::selectView('post-user-view', $selected, $condition, $params);
384 * Select rows from the post-view view
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
390 * @return boolean|object
393 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
395 return self::selectView('post-view', $selected, $condition, $params);
399 * Select rows from the post-thread-user-view view
401 * @param array $selected Array of selected fields, empty for all
402 * @param array $condition Array of fields for condition
403 * @param array $params Array of several parameters
405 * @return boolean|object
408 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
410 return self::selectView('post-thread-user-view', $selected, $condition, $params);
414 * Select rows from the post-thread-view view
416 * @param array $selected Array of selected fields, empty for all
417 * @param array $condition Array of fields for condition
418 * @param array $params Array of several parameters
420 * @return boolean|object
423 public static function selectPostThread(array $selected = [], array $condition = [], array $params = [])
425 return self::selectView('post-thread-view', $selected, $condition, $params);
429 * Select rows from the given view for a given user
431 * @param string $view View (post-user-view or post-thread-user-view)
432 * @param integer $uid User ID
433 * @param array $selected Array of selected fields, empty for all
434 * @param array $condition Array of fields for condition
435 * @param array $params Array of several parameters
437 * @return boolean|object
440 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
442 if (empty($selected)) {
443 $selected = Item::DISPLAY_FIELDLIST;
446 $condition = DBA::mergeConditions($condition,
447 ["`visible` AND NOT `deleted`
448 AND NOT `author-blocked` AND NOT `owner-blocked`
449 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
450 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
451 OR `self` OR `contact-uid` = ?)
452 AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = " . DBA::quoteIdentifier($view) . ".`uri-id` AND `hidden`)
453 AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` IN (`author-id`, `owner-id`) AND (`blocked` OR `ignored`))
454 AND NOT EXISTS(SELECT `gsid` FROM `user-gserver` WHERE `uid` = ? AND `gsid` IN (`author-gsid`, `owner-gsid`, `causer-gsid`) AND `ignored`)",
455 0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid]);
457 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
459 $condition_string = DBA::buildCondition($condition);
460 $param_string = DBA::buildParameter($params);
462 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
463 $sql = DBA::cleanQuery($sql);
465 return DBA::p($sql, $condition);
469 * Select rows from the post-user-view view for a given user
471 * @param integer $uid User ID
472 * @param array $selected Array of selected fields, empty for all
473 * @param array $condition Array of fields for condition
474 * @param array $params Array of several parameters
476 * @return boolean|object
479 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
481 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
485 * Select rows from the post-view view for a given user
487 * @param integer $uid User ID
488 * @param array $selected Array of selected fields, empty for all
489 * @param array $condition Array of fields for condition
490 * @param array $params Array of several parameters
492 * @return boolean|object
495 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
497 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
501 * Select rows from the post-thread-user-view view for a given user
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 selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
513 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
517 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
519 * @param integer $uid User ID
520 * @param array $selected
521 * @param array $condition
522 * @param array $params
527 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
529 $params['limit'] = 1;
531 $result = self::selectForUser($uid, $selected, $condition, $params);
533 if (is_bool($result)) {
536 $row = self::fetch($result);
543 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
544 * When the requested record is a reshare activity, the system fetches the reshared original post.
545 * Otherwise the function reacts similar to selectFirstForUser
547 * @param integer $uid User ID
548 * @param array $selected
549 * @param array $condition
550 * @param array $params
555 public static function selectOriginalForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
557 $original_selected = $selected;
559 if (!empty($selected)) {
560 foreach (['gravity', 'verb', 'thr-parent-id'] as $field) {
561 if (!in_array($field, $selected)) {
562 $selected[] = $field;
567 $result = self::selectFirstForUser($uid, $selected, $condition, $params);
568 if (empty($result)) {
572 if (($result['gravity'] != Item::GRAVITY_ACTIVITY) || ($result['verb'] != Activity::ANNOUNCE)) {
573 foreach ($remove as $field) {
574 unset($result[$field]);
579 return self::selectFirstForUser($uid, $original_selected, ['uri-id' => $result['thr-parent-id'], 'uid' => [0, $uid]], $params);
583 * Update existing post entries
585 * @param array $fields The fields that are to be changed
586 * @param array $condition The condition for finding the item entries
588 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
590 * @return integer|boolean number of affected rows - or "false" if there was an error
591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
593 public static function update(array $fields, array $condition)
597 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId(),'callstack' => System::callstack(10)]);
599 // Don't allow changes to fields that are responsible for the relation between the records
600 unset($fields['id']);
601 unset($fields['parent']);
602 unset($fields['uid']);
603 unset($fields['uri']);
604 unset($fields['uri-id']);
605 unset($fields['thr-parent']);
606 unset($fields['thr-parent-id']);
607 unset($fields['parent-uri']);
608 unset($fields['parent-uri-id']);
610 $thread_condition = DBA::mergeConditions($condition, ['gravity' => Item::GRAVITY_PARENT]);
612 // To ensure the data integrity we do it in an transaction
615 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-user', $fields);
616 if (!empty($update_fields)) {
618 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
619 while ($rows = DBA::toArray($posts, false, 100)) {
620 $puids = array_column($rows, 'post-user-id');
621 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
623 Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
626 $affected_count += DBA::affectedRows();
629 $affected = $affected_count;
632 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-content', $fields);
633 if (!empty($update_fields)) {
635 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
636 while ($rows = DBA::toArray($posts, false, 100)) {
637 $uriids = array_column($rows, 'uri-id');
638 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
640 Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
643 $affected_count += DBA::affectedRows();
646 $affected = max($affected, $affected_count);
649 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields);
650 if (!empty($update_fields)) {
652 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
653 while ($rows = DBA::toArray($posts, false, 100)) {
654 $uriids = array_column($rows, 'uri-id');
656 // Only delete the "post" entry when all "post-user" entries are deleted
657 if (!empty($update_fields['deleted']) && DBA::exists('post-user', ['uri-id' => $uriids, 'deleted' => false])) {
658 unset($update_fields['deleted']);
661 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
663 Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
666 $affected_count += DBA::affectedRows();
669 $affected = max($affected, $affected_count);
672 $update_fields = Post\DeliveryData::extractFields($fields);
673 if (!empty($update_fields)) {
675 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
676 while ($rows = DBA::toArray($posts, false, 100)) {
677 $uriids = array_column($rows, 'uri-id');
678 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
680 Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
683 $affected_count += DBA::affectedRows();
686 $affected = max($affected, $affected_count);
689 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields);
690 if (!empty($update_fields)) {
692 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
693 while ($rows = DBA::toArray($posts, false, 100)) {
694 $uriids = array_column($rows, 'uri-id');
695 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
697 Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
700 $affected_count += DBA::affectedRows();
703 $affected = max($affected, $affected_count);
706 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields);
707 if (!empty($update_fields)) {
709 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
710 while ($rows = DBA::toArray($posts, false, 100)) {
711 $thread_puids = array_column($rows, 'post-user-id');
712 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
714 Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
717 $affected_count += DBA::affectedRows();
720 $affected = max($affected, $affected_count);
725 Logger::info('Updated posts', ['rows' => $affected]);
730 * Delete a row from the post table
732 * @param array $conditions Field condition(s)
733 * @param array $options
734 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
735 * relations (default: true)
737 * @return boolean was the delete successful?
740 public static function delete(array $conditions, array $options = []): bool
742 return DBA::delete('post', $conditions, $options);