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\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
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 = DBStructure::getFieldsForTable('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 an post query
107 * @param object $stmt statement object
108 * @param bool $do_close
109 * @return array Data array
110 * @todo Find proper type-hint for $stmt and maybe avoid boolean
112 public static function toArray($stmt, bool $do_close = true)
114 if (is_bool($stmt)) {
119 while ($row = self::fetch($stmt)) {
129 * Check if post-user-view records exists
131 * @param array $condition array of fields for condition
133 * @return boolean Are there rows for that condition?
136 public static function exists(array $condition): bool
138 return DBA::exists('post-user-view', $condition);
142 * Counts the post-user-view records satisfying the provided condition
144 * @param array $condition array of fields for condition
145 * @param array $params Array of several parameters
150 * $condition = ["uid" => 1, "network" => 'dspr'];
152 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
154 * $count = Post::count($condition);
157 public static function count(array $condition = [], array $params = []): int
159 return DBA::count('post-user-view', $condition, $params);
163 * Counts the post-thread-user-view records satisfying the provided condition
165 * @param array $condition array of fields for condition
166 * @param array $params Array of several parameters
171 * $condition = ["uid" => 1, "network" => 'dspr'];
173 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
175 * $count = Post::count($condition);
178 public static function countThread(array $condition = [], array $params = []): int
180 return DBA::count('post-thread-user-view', $condition, $params);
184 * Counts the post-view records satisfying the provided condition
186 * @param array $condition array of fields for condition
187 * @param array $params Array of several parameters
192 * $condition = ["network" => 'dspr'];
194 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
196 * $count = Post::count($condition);
199 public static function countPosts(array $condition = [], array $params = []): int
201 return DBA::count('post-view', $condition, $params);
205 * Retrieve a single record from the post-user-view view and returns it in an associative array
207 * @param array $fields
208 * @param array $condition
209 * @param array $params
210 * @param bool $user_mode true = post-user-view, false = post-view
215 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
217 $params['limit'] = 1;
219 $result = self::select($fields, $condition, $params);
221 if (is_bool($result)) {
224 $row = self::fetch($result);
231 * Retrieve a single record from the post-view view and returns it in an associative array
233 * @param array $fields
234 * @param array $condition
235 * @param array $params
240 public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
242 $params['limit'] = 1;
244 $result = self::selectPosts($fields, $condition, $params);
246 if (is_bool($result)) {
249 $row = self::fetch($result);
256 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
258 * @param array $fields
259 * @param array $condition
260 * @param array $params
265 public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
267 $params['limit'] = 1;
269 $result = self::selectThread($fields, $condition, $params);
271 if (is_bool($result)) {
274 $row = self::fetch($result);
281 * Select rows from the post-user-view view and returns them as an array
283 * @param array $selected Array of selected fields, empty for all
284 * @param array $condition Array of fields for condition
285 * @param array $params Array of several parameters
290 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
292 $result = self::select($fields, $condition, $params);
294 if (is_bool($result)) {
299 while ($row = self::fetch($result)) {
308 * Select rows from the given view
310 * @param string $view View (post-user-view or post-thread-user-view)
311 * @param array $selected Array of selected fields, empty for all
312 * @param array $condition Array of fields for condition
313 * @param array $params Array of several parameters
315 * @return boolean|object
318 private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
320 if (empty($selected)) {
321 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
323 if ($view == 'post-thread-user-view') {
324 $selected = array_merge($selected, ['ignored']);
328 $selected = array_unique($selected);
330 return DBA::select($view, $selected, $condition, $params);
334 * Select rows from the post-user-view view
336 * @param array $selected Array of selected fields, empty for all
337 * @param array $condition Array of fields for condition
338 * @param array $params Array of several parameters
340 * @return boolean|object
343 public static function select(array $selected = [], array $condition = [], array $params = [])
345 return self::selectView('post-user-view', $selected, $condition, $params);
349 * Select rows from the post-view view
351 * @param array $selected Array of selected fields, empty for all
352 * @param array $condition Array of fields for condition
353 * @param array $params Array of several parameters
355 * @return boolean|object
358 public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
360 return self::selectView('post-view', $selected, $condition, $params);
364 * Select rows from the post-thread-user-view view
366 * @param array $selected Array of selected fields, empty for all
367 * @param array $condition Array of fields for condition
368 * @param array $params Array of several parameters
370 * @return boolean|object
373 public static function selectThread(array $selected = [], array $condition = [], array $params = [])
375 return self::selectView('post-thread-user-view', $selected, $condition, $params);
379 * Select rows from the given view for a given user
381 * @param string $view View (post-user-view or post-thread-user-view)
382 * @param integer $uid User ID
383 * @param array $selected Array of selected fields, empty for all
384 * @param array $condition Array of fields for condition
385 * @param array $params Array of several parameters
387 * @return boolean|object
390 private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
392 if (empty($selected)) {
393 $selected = Item::DISPLAY_FIELDLIST;
396 $condition = DBA::mergeConditions($condition,
397 ["`visible` AND NOT `deleted`
398 AND NOT `author-blocked` AND NOT `owner-blocked`
399 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
400 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
401 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
402 AND NOT EXISTS (SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = `" . $view . "`.`uri-id` AND `hidden`)
403 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
404 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
405 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
406 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
407 0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
409 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
411 $condition_string = DBA::buildCondition($condition);
412 $param_string = DBA::buildParameter($params);
414 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
415 $sql = DBA::cleanQuery($sql);
417 return DBA::p($sql, $condition);
421 * Select rows from the post-user-view view for a given user
423 * @param integer $uid User ID
424 * @param array $selected Array of selected fields, empty for all
425 * @param array $condition Array of fields for condition
426 * @param array $params Array of several parameters
428 * @return boolean|object
431 public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
433 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
437 * Select rows from the post-view view for a given user
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 public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
449 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
453 * Select rows from the post-thread-user-view view for a given user
455 * @param integer $uid User ID
456 * @param array $selected Array of selected fields, empty for all
457 * @param array $condition Array of fields for condition
458 * @param array $params Array of several parameters
460 * @return boolean|object
463 public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
465 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
469 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
471 * @param integer $uid User ID
472 * @param array $selected
473 * @param array $condition
474 * @param array $params
479 public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
481 $params['limit'] = 1;
483 $result = self::selectForUser($uid, $selected, $condition, $params);
485 if (is_bool($result)) {
488 $row = self::fetch($result);
495 * Update existing post entries
497 * @param array $fields The fields that are to be changed
498 * @param array $condition The condition for finding the item entries
500 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
502 * @return integer|boolean number of affected rows - or "false" if there was an error
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
505 public static function update(array $fields, array $condition)
509 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => local_user(),'callstack' => System::callstack(10)]);
511 // Don't allow changes to fields that are responsible for the relation between the records
512 unset($fields['id']);
513 unset($fields['parent']);
514 unset($fields['uid']);
515 unset($fields['uri']);
516 unset($fields['uri-id']);
517 unset($fields['thr-parent']);
518 unset($fields['thr-parent-id']);
519 unset($fields['parent-uri']);
520 unset($fields['parent-uri-id']);
522 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
524 // To ensure the data integrity we do it in an transaction
527 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
528 if (!empty($update_fields)) {
530 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
531 while ($rows = DBA::toArray($posts, false, 100)) {
532 $puids = array_column($rows, 'post-user-id');
533 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
535 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
538 $affected_count += DBA::affectedRows();
541 $affected = $affected_count;
544 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
545 if (!empty($update_fields)) {
547 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
548 while ($rows = DBA::toArray($posts, false, 100)) {
549 $uriids = array_column($rows, 'uri-id');
550 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
552 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
555 $affected_count += DBA::affectedRows();
558 $affected = max($affected, $affected_count);
561 $update_fields = DBStructure::getFieldsForTable('post', $fields);
562 if (!empty($update_fields)) {
564 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
565 while ($rows = DBA::toArray($posts, false, 100)) {
566 $uriids = array_column($rows, 'uri-id');
567 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
569 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
572 $affected_count += DBA::affectedRows();
575 $affected = max($affected, $affected_count);
578 $update_fields = Post\DeliveryData::extractFields($fields);
579 if (!empty($update_fields)) {
581 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
582 while ($rows = DBA::toArray($posts, false, 100)) {
583 $uriids = array_column($rows, 'uri-id');
584 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
586 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
589 $affected_count += DBA::affectedRows();
592 $affected = max($affected, $affected_count);
595 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
596 if (!empty($update_fields)) {
598 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
599 while ($rows = DBA::toArray($posts, false, 100)) {
600 $uriids = array_column($rows, 'uri-id');
601 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
603 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
606 $affected_count += DBA::affectedRows();
609 $affected = max($affected, $affected_count);
612 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
613 if (!empty($update_fields)) {
615 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
616 while ($rows = DBA::toArray($posts, false, 100)) {
617 $thread_puids = array_column($rows, 'post-user-id');
618 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
620 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
623 $affected_count += DBA::affectedRows();
626 $affected = max($affected, $affected_count);
631 Logger::info('Updated posts', ['rows' => $affected]);
636 * Delete a row from the post table
638 * @param array $conditions Field condition(s)
639 * @param array $options
640 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
641 * relations (default: true)
643 * @return boolean was the delete successful?
646 public static function delete(array $conditions, array $options = []): bool
648 return DBA::delete('post', $conditions, $options);