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 = [])
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
111 public static function toArray($stmt, $do_close = true) {
112 if (is_bool($stmt)) {
117 while ($row = self::fetch($stmt)) {
127 * Check if post-user-view records exists
129 * @param array $condition array of fields for condition
131 * @return boolean Are there rows for that condition?
134 public static function exists($condition) {
135 return DBA::exists('post-user-view', $condition);
139 * Counts the post-user-view records satisfying the provided condition
141 * @param array $condition array of fields for condition
142 * @param array $params Array of several parameters
147 * $condition = ["uid" => 1, "network" => 'dspr'];
149 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
151 * $count = Post::count($condition);
154 public static function count(array $condition = [], array $params = [])
156 return DBA::count('post-user-view', $condition, $params);
160 * Counts the post-thread-user-view records satisfying the provided condition
162 * @param array $condition array of fields for condition
163 * @param array $params Array of several parameters
168 * $condition = ["uid" => 1, "network" => 'dspr'];
170 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
172 * $count = Post::count($condition);
175 public static function countThread(array $condition = [], array $params = [])
177 return DBA::count('post-thread-user-view', $condition, $params);
181 * Counts the post-view records satisfying the provided condition
183 * @param array $condition array of fields for condition
184 * @param array $params Array of several parameters
189 * $condition = ["network" => 'dspr'];
191 * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
193 * $count = Post::count($condition);
196 public static function countPosts(array $condition = [], array $params = [])
198 return DBA::count('post-view', $condition, $params);
202 * Retrieve a single record from the post-user-view view and returns it in an associative array
204 * @param array $fields
205 * @param array $condition
206 * @param array $params
207 * @param bool $user_mode true = post-user-view, false = post-view
212 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
214 $params['limit'] = 1;
216 $result = self::select($fields, $condition, $params);
218 if (is_bool($result)) {
221 $row = self::fetch($result);
228 * Retrieve a single record from the post-view view and returns it in an associative array
230 * @param array $fields
231 * @param array $condition
232 * @param array $params
237 public static function selectFirstPost(array $fields = [], array $condition = [], $params = [])
239 $params['limit'] = 1;
241 $result = self::selectPosts($fields, $condition, $params);
243 if (is_bool($result)) {
246 $row = self::fetch($result);
253 * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
255 * @param array $fields
256 * @param array $condition
257 * @param array $params
262 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
264 $params['limit'] = 1;
266 $result = self::selectThread($fields, $condition, $params);
268 if (is_bool($result)) {
271 $row = self::fetch($result);
278 * Select rows from the post-user-view view and returns them as an array
280 * @param array $selected Array of selected fields, empty for all
281 * @param array $condition Array of fields for condition
282 * @param array $params Array of several parameters
287 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
289 $result = self::select($fields, $condition, $params);
291 if (is_bool($result)) {
296 while ($row = self::fetch($result)) {
305 * Select rows from the given view
307 * @param string $view View (post-user-view or post-thread-user-view)
308 * @param array $selected Array of selected fields, empty for all
309 * @param array $condition Array of fields for condition
310 * @param array $params Array of several parameters
312 * @return boolean|object
315 private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
317 if (empty($selected)) {
318 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
320 if ($view == 'post-thread-user-view') {
321 $selected = array_merge($selected, ['ignored']);
325 $selected = array_unique($selected);
327 return DBA::select($view, $selected, $condition, $params);
331 * Select rows from the post-user-view view
333 * @param array $selected Array of selected fields, empty for all
334 * @param array $condition Array of fields for condition
335 * @param array $params Array of several parameters
337 * @return boolean|object
340 public static function select(array $selected = [], array $condition = [], $params = [])
342 return self::selectView('post-user-view', $selected, $condition, $params);
346 * Select rows from the post-view view
348 * @param array $selected Array of selected fields, empty for all
349 * @param array $condition Array of fields for condition
350 * @param array $params Array of several parameters
352 * @return boolean|object
355 public static function selectPosts(array $selected = [], array $condition = [], $params = [])
357 return self::selectView('post-view', $selected, $condition, $params);
361 * Select rows from the post-thread-user-view view
363 * @param array $selected Array of selected fields, empty for all
364 * @param array $condition Array of fields for condition
365 * @param array $params Array of several parameters
367 * @return boolean|object
370 public static function selectThread(array $selected = [], array $condition = [], $params = [])
372 return self::selectView('post-thread-user-view', $selected, $condition, $params);
376 * Select rows from the given view for a given user
378 * @param string $view View (post-user-view or post-thread-user-view)
379 * @param integer $uid User ID
380 * @param array $selected Array of selected fields, empty for all
381 * @param array $condition Array of fields for condition
382 * @param array $params Array of several parameters
384 * @return boolean|object
387 private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
389 if (empty($selected)) {
390 $selected = Item::DISPLAY_FIELDLIST;
393 $condition = DBA::mergeConditions($condition,
394 ["`visible` AND NOT `deleted`
395 AND NOT `author-blocked` AND NOT `owner-blocked`
396 AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
397 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
398 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
399 AND NOT EXISTS (SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = `" . $view . "`.`uri-id` AND `hidden`)
400 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
401 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
402 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
403 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
404 0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
406 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
408 $condition_string = DBA::buildCondition($condition);
409 $param_string = DBA::buildParameter($params);
411 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
412 $sql = DBA::cleanQuery($sql);
414 return DBA::p($sql, $condition);
418 * Select rows from the post-user-view view for a given user
420 * @param integer $uid User ID
421 * @param array $selected Array of selected fields, empty for all
422 * @param array $condition Array of fields for condition
423 * @param array $params Array of several parameters
425 * @return boolean|object
428 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
430 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
434 * Select rows from the post-view view for a given user
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 public static function selectPostsForUser($uid, array $selected = [], array $condition = [], $params = [])
446 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
450 * Select rows from the post-thread-user-view view for a given user
452 * @param integer $uid User ID
453 * @param array $selected Array of selected fields, empty for all
454 * @param array $condition Array of fields for condition
455 * @param array $params Array of several parameters
457 * @return boolean|object
460 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
462 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
466 * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
468 * @param integer $uid User ID
469 * @param array $selected
470 * @param array $condition
471 * @param array $params
476 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
478 $params['limit'] = 1;
480 $result = self::selectForUser($uid, $selected, $condition, $params);
482 if (is_bool($result)) {
485 $row = self::fetch($result);
492 * Select pinned rows from the post-thread-user table for a given user
494 * @param integer $uid User ID
495 * @param array $selected Array of selected fields, empty for all
496 * @param array $condition Array of fields for condition
497 * @param array $params Array of several parameters
499 * @return boolean|object
502 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
504 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
505 if (!DBA::isResult($postthreaduser)) {
506 return $postthreaduser;
510 while ($useritem = DBA::fetch($postthreaduser)) {
511 $pinned[] = $useritem['uri-id'];
513 DBA::close($postthreaduser);
515 if (empty($pinned)) {
519 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
521 return self::selectForUser($uid, $selected, $condition, $params);
525 * Update existing post entries
527 * @param array $fields The fields that are to be changed
528 * @param array $condition The condition for finding the item entries
530 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
532 * @return integer|boolean number of affected rows - or "false" if there was an error
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535 public static function update(array $fields, array $condition)
539 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => local_user(),'callstack' => System::callstack(10)]);
541 // Don't allow changes to fields that are responsible for the relation between the records
542 unset($fields['id']);
543 unset($fields['parent']);
544 unset($fields['uid']);
545 unset($fields['uri']);
546 unset($fields['uri-id']);
547 unset($fields['thr-parent']);
548 unset($fields['thr-parent-id']);
549 unset($fields['parent-uri']);
550 unset($fields['parent-uri-id']);
552 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
554 // To ensure the data integrity we do it in an transaction
557 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
558 if (!empty($update_fields)) {
560 $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
561 while ($rows = DBA::toArray($posts, false, 100)) {
562 $puids = array_column($rows, 'post-user-id');
563 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
565 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
568 $affected_count += DBA::affectedRows();
571 $affected = $affected_count;
574 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
575 if (!empty($update_fields)) {
577 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
578 while ($rows = DBA::toArray($posts, false, 100)) {
579 $uriids = array_column($rows, 'uri-id');
580 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
582 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
585 $affected_count += DBA::affectedRows();
588 $affected = max($affected, $affected_count);
591 $update_fields = DBStructure::getFieldsForTable('post', $fields);
592 if (!empty($update_fields)) {
594 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
595 while ($rows = DBA::toArray($posts, false, 100)) {
596 $uriids = array_column($rows, 'uri-id');
597 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
599 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
602 $affected_count += DBA::affectedRows();
605 $affected = max($affected, $affected_count);
608 $update_fields = Post\DeliveryData::extractFields($fields);
609 if (!empty($update_fields)) {
611 $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
612 while ($rows = DBA::toArray($posts, false, 100)) {
613 $uriids = array_column($rows, 'uri-id');
614 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
616 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
619 $affected_count += DBA::affectedRows();
622 $affected = max($affected, $affected_count);
625 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
626 if (!empty($update_fields)) {
628 $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
629 while ($rows = DBA::toArray($posts, false, 100)) {
630 $uriids = array_column($rows, 'uri-id');
631 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
633 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
636 $affected_count += DBA::affectedRows();
639 $affected = max($affected, $affected_count);
642 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
643 if (!empty($update_fields)) {
645 $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
646 while ($rows = DBA::toArray($posts, false, 100)) {
647 $thread_puids = array_column($rows, 'post-user-id');
648 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
650 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
653 $affected_count += DBA::affectedRows();
656 $affected = max($affected, $affected_count);
661 Logger::info('Updated posts', ['rows' => $affected]);
666 * Delete a row from the post table
668 * @param array $conditions Field condition(s)
669 * @param array $options
670 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
671 * relations (default: true)
673 * @return boolean was the delete successful?
676 public static function delete(array $conditions, array $options = [])
678 return DBA::delete('post', $conditions, $options);