3 * @copyright Copyright (C) 2010-2022, 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\Session;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
30 use Friendica\Database\DBStructure;
32 use Friendica\Model\Item;
33 use Friendica\Protocol\Activity;
38 * Insert a new post entry
40 * @param integer $uri_id
41 * @param array $fields
42 * @return int ID of inserted post
45 public static function insert(int $uri_id, array $data = []): int
48 throw new BadMethodCallException('Empty URI_id');
51 $fields = DI::dbaDefinition()->truncateFieldsForTable('post', $data);
53 // Additionally assign the key fields
54 $fields['uri-id'] = $uri_id;
56 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
60 return DBA::lastInsertId();
64 * Fetch a single post row
66 * @param mixed $stmt statement object
67 * @return array|false current row or false
70 public static function fetch($stmt)
72 $row = DBA::fetch($stmt);
74 if (!is_array($row)) {
78 if (array_key_exists('verb', $row)) {
79 if (in_array($row['verb'], Item::ACTIVITIES)) {
80 if (array_key_exists('title', $row)) {
83 if (array_key_exists('body', $row)) {
84 $row['body'] = $row['verb'];
86 if (array_key_exists('object', $row)) {
89 if (array_key_exists('object-type', $row)) {
90 $row['object-type'] = Activity\ObjectType::NOTE;
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)) {
100 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
108 * Fills an array with data from an post query
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
115 public static function toArray($stmt, bool $do_close = true)
117 if (is_bool($stmt)) {
122 while ($row = self::fetch($stmt)) {
132 * Check if post-user-view records exists
134 * @param array $condition array of fields for condition
136 * @return boolean Are there rows for that condition?
139 public static function exists(array $condition): bool
141 return DBA::exists('post-user-view', $condition);
145 * Counts the post-user-view records satisfying the provided condition
147 * @param array $condition array of fields for condition
148 * @param array $params Array of several parameters
153 * $condition = ["uid" => 1, "network" => 'dspr'];
155 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
157 * $count = Post::count($condition);
160 public static function count(array $condition = [], array $params = []): int
162 return DBA::count('post-user-view', $condition, $params);
166 * Counts the post-thread-user-view records satisfying the provided condition
168 * @param array $condition array of fields for condition
169 * @param array $params Array of several parameters
174 * $condition = ["uid" => 1, "network" => 'dspr'];
176 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
178 * $count = Post::count($condition);
181 public static function countThread(array $condition = [], array $params = []): int
183 return DBA::count('post-thread-user-view', $condition, $params);
187 * Counts the post-view records satisfying the provided condition
189 * @param array $condition array of fields for condition
190 * @param array $params Array of several parameters
195 * $condition = ["network" => 'dspr'];
197 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
199 * $count = Post::count($condition);
202 public static function countPosts(array $condition = [], array $params = []): int
204 return DBA::count('post-view', $condition, $params);
208 * Retrieve a single record from the post-user-view view and returns it in an associative array
210 * @param array $fields
211 * @param array $condition
212 * @param array $params
213 * @param bool $user_mode true = post-user-view, false = post-view
218 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
220 $params['limit'] = 1;
222 $result = self::select($fields, $condition, $params);
224 if (is_bool($result)) {
227 $row = self::fetch($result);
234 * Retrieve a single record from the post-view view and returns it in an associative array
236 * @param array $fields
237 * @param array $condition
238 * @param array $params
243 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
245 $params['limit'] = 1;
247 $result = self::selectPosts($fields, $condition, $params);
249 if (is_bool($result)) {
252 $row = self::fetch($result);
259 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
261 * @param array $fields
262 * @param array $condition
263 * @param array $params
268 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
270 $params['limit'] = 1;
272 $result = self::selectThread($fields, $condition, $params);
274 if (is_bool($result)) {
277 $row = self::fetch($result);
284 * Select rows from the post-user-view view and returns them as an array
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
293 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
295 $result = self::select($fields, $condition, $params);
297 if (is_bool($result)) {
302 while ($row = self::fetch($result)) {
311 * Select rows from the given view
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
318 * @return boolean|object
321 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
323 if (empty($selected)) {
324 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
326 if ($view == 'post-thread-user-view') {
327 $selected = array_merge($selected, ['ignored']);
331 $selected = array_unique($selected);
333 return DBA::select($view, $selected, $condition, $params);
337 * Select rows from the post-user-view view
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
343 * @return boolean|object
346 public static function select(array $selected = [], array $condition = [], array $params = [])
348 return self::selectView('post-user-view', $selected, $condition, $params);
352 * Select rows from the post-view view
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
358 * @return boolean|object
361 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
363 return self::selectView('post-view', $selected, $condition, $params);
367 * Select rows from the post-thread-user-view view
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
373 * @return boolean|object
376 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
378 return self::selectView('post-thread-user-view', $selected, $condition, $params);
382 * Select rows from the given view for a given user
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
390 * @return boolean|object
393 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
395 if (empty($selected)) {
396 $selected = Item::DISPLAY_FIELDLIST;
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]);
412 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
414 $condition_string = DBA::buildCondition($condition);
415 $param_string = DBA::buildParameter($params);
417 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
418 $sql = DBA::cleanQuery($sql);
420 return DBA::p($sql, $condition);
424 * Select rows from the post-user-view view for a given user
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
431 * @return boolean|object
434 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
436 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
440 * Select rows from the post-view view for a given user
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
447 * @return boolean|object
450 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
452 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
456 * Select rows from the post-thread-user-view view for a given user
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
463 * @return boolean|object
466 public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
468 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
472 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
474 * @param integer $uid User ID
475 * @param array $selected
476 * @param array $condition
477 * @param array $params
482 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
484 $params['limit'] = 1;
486 $result = self::selectForUser($uid, $selected, $condition, $params);
488 if (is_bool($result)) {
491 $row = self::fetch($result);
498 * Update existing post entries
500 * @param array $fields The fields that are to be changed
501 * @param array $condition The condition for finding the item entries
503 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
505 * @return integer|boolean number of affected rows - or "false" if there was an error
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 public static function update(array $fields, array $condition)
512 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => Session::getLocalUser(),'callstack' => System::callstack(10)]);
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']);
525 $thread_condition = DBA::mergeConditions($condition, ['gravity' => Item::GRAVITY_PARENT]);
527 // To ensure the data integrity we do it in an transaction
530 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-user', $fields);
531 if (!empty($update_fields)) {
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])) {
538 Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
541 $affected_count += DBA::affectedRows();
544 $affected = $affected_count;
547 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-content', $fields);
548 if (!empty($update_fields)) {
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])) {
555 Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
558 $affected_count += DBA::affectedRows();
561 $affected = max($affected, $affected_count);
564 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields);
565 if (!empty($update_fields)) {
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');
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']);
576 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
578 Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
581 $affected_count += DBA::affectedRows();
584 $affected = max($affected, $affected_count);
587 $update_fields = Post\DeliveryData::extractFields($fields);
588 if (!empty($update_fields)) {
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])) {
595 Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
598 $affected_count += DBA::affectedRows();
601 $affected = max($affected, $affected_count);
604 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields);
605 if (!empty($update_fields)) {
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])) {
612 Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
615 $affected_count += DBA::affectedRows();
618 $affected = max($affected, $affected_count);
621 $update_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields);
622 if (!empty($update_fields)) {
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])) {
629 Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
632 $affected_count += DBA::affectedRows();
635 $affected = max($affected, $affected_count);
640 Logger::info('Updated posts', ['rows' => $affected]);
645 * Delete a row from the post table
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)
652 * @return boolean was the delete successful?
655 public static function delete(array $conditions, array $options = []): bool
657 return DBA::delete('post', $conditions, $options);