3 * @copyright Copyright (C) 2020, Friendica
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 data 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-view', $condition);
139 * Counts the posts 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-view', $condition, $params);
160 * Retrieve a single record from the post table and returns it in an associative array
162 * @param array $fields
163 * @param array $condition
164 * @param array $params
169 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
171 $params['limit'] = 1;
173 $result = self::select($fields, $condition, $params);
175 if (is_bool($result)) {
178 $row = self::fetch($result);
185 * Select rows from the post table and returns them as an array
187 * @param array $selected Array of selected fields, empty for all
188 * @param array $condition Array of fields for condition
189 * @param array $params Array of several parameters
194 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
196 $result = self::select($fields, $condition, $params);
198 if (is_bool($result)) {
203 while ($row = self::fetch($result)) {
212 * Select rows from the given view
214 * @param string $view View (post-view or post-thread-view)
215 * @param array $selected Array of selected fields, empty for all
216 * @param array $condition Array of fields for condition
217 * @param array $params Array of several parameters
219 * @return boolean|object
222 private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
224 if (empty($selected)) {
225 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
227 if ($view == 'post-thread-view') {
228 $selected = array_merge($selected, ['ignored', 'iid']);
232 $selected = array_unique($selected);
234 return DBA::select($view, $selected, $condition, $params);
238 * Select rows from the post table
240 * @param array $selected Array of selected fields, empty for all
241 * @param array $condition Array of fields for condition
242 * @param array $params Array of several parameters
244 * @return boolean|object
247 public static function select(array $selected = [], array $condition = [], $params = [])
249 $timestamp = microtime(true);
250 $data = self::selectView('post-view', $selected, $condition, $params);
252 $duration = microtime(true) - $timestamp;;
254 Logger::info('Blubb', ['duration' => $duration, 'selected' => $selected, 'condition' => $condition, 'params' => $params, 'callstack' => System::callstack(20)]);
259 * Select rows from the post table
261 * @param array $selected Array of selected fields, empty for all
262 * @param array $condition Array of fields for condition
263 * @param array $params Array of several parameters
265 * @return boolean|object
268 public static function selectThread(array $selected = [], array $condition = [], $params = [])
270 return self::selectView('post-thread-view', $selected, $condition, $params);
274 * Select rows from the given view for a given user
276 * @param string $view View (post-view or post-thread-view)
277 * @param integer $uid User ID
278 * @param array $selected Array of selected fields, empty for all
279 * @param array $condition Array of fields for condition
280 * @param array $params Array of several parameters
282 * @return boolean|object
285 private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
287 if (empty($selected)) {
288 $selected = Item::DISPLAY_FIELDLIST;
291 $condition = DBA::mergeConditions($condition,
292 ["`visible` AND NOT `deleted`
293 AND NOT `author-blocked` AND NOT `owner-blocked`
294 AND (NOT `causer-blocked` OR `causer-id` = ?) AND NOT `contact-blocked`
295 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
296 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
297 AND NOT EXISTS (SELECT `uri-id` FROM `post-user` WHERE `hidden` AND `uri-id` = `" . $view . "`.`uri-id` AND `uid` = ?)
298 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
299 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
300 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
301 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
302 0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
306 if (in_array('pinned', $selected)) {
307 $selected = array_flip($selected);
308 unset($selected['pinned']);
309 $selected = array_flip($selected);
311 $select_string = "(SELECT `pinned` FROM `post-thread-user` WHERE `uri-id` = `" . $view . "`.`uri-id` AND uid=`" . $view . "`.`uid`) AS `pinned`, ";
314 $select_string .= implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
316 $condition_string = DBA::buildCondition($condition);
317 $param_string = DBA::buildParameter($params);
319 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
320 $sql = DBA::cleanQuery($sql);
322 return DBA::p($sql, $condition);
326 * Select rows from the post view for a given user
328 * @param integer $uid User ID
329 * @param array $selected Array of selected fields, empty for all
330 * @param array $condition Array of fields for condition
331 * @param array $params Array of several parameters
333 * @return boolean|object
336 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
338 //Logger::info('Blubb', ['uid' => $uid, 'selected' => $selected, 'condition' => $condition, 'params' => $params]);
339 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
343 * Select rows from the post view for a given user
345 * @param integer $uid User ID
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 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
355 return self::selectViewForUser('post-thread-view', $uid, $selected, $condition, $params);
359 * Retrieve a single record from the post view for a given user and returns it in an associative array
361 * @param integer $uid User ID
362 * @param array $selected
363 * @param array $condition
364 * @param array $params
369 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
371 $params['limit'] = 1;
373 $result = self::selectForUser($uid, $selected, $condition, $params);
375 if (is_bool($result)) {
378 $row = self::fetch($result);
385 * Select pinned rows from the item table for a given user
387 * @param integer $uid User ID
388 * @param array $selected Array of selected fields, empty for all
389 * @param array $condition Array of fields for condition
390 * @param array $params Array of several parameters
392 * @return boolean|object
395 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
397 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
398 if (!DBA::isResult($postthreaduser)) {
399 return $postthreaduser;
403 while ($useritem = DBA::fetch($postthreaduser)) {
404 $pinned[] = $useritem['uri-id'];
406 DBA::close($postthreaduser);
408 if (empty($pinned)) {
412 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
414 return self::selectForUser($uid, $selected, $condition, $params);
418 * Update existing post entries
420 * @param array $fields The fields that are to be changed
421 * @param array $condition The condition for finding the item entries
423 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
425 * @return integer|boolean number of affected rows - or "false" if there was an error
426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
428 public static function update(array $fields, array $condition)
432 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition]);
434 // Don't allow changes to fields that are responsible for the relation between the records
435 unset($fields['id']);
436 unset($fields['parent']);
437 unset($fields['uid']);
438 unset($fields['uri']);
439 unset($fields['uri-id']);
440 unset($fields['thr-parent']);
441 unset($fields['thr-parent-id']);
442 unset($fields['parent-uri']);
443 unset($fields['parent-uri-id']);
445 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
447 // To ensure the data integrity we do it in an transaction
450 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
451 if (!empty($update_fields)) {
452 $rows = DBA::selectToArray('post-view', ['post-user-id'], $condition);
453 $puids = array_column($rows, 'post-user-id');
454 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
456 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
459 $affected = DBA::affectedRows();
462 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
463 if (!empty($update_fields)) {
464 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
465 $uriids = array_column($rows, 'uri-id');
466 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
468 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
471 $affected = max($affected, DBA::affectedRows());
474 $update_fields = DBStructure::getFieldsForTable('post', $fields);
475 if (!empty($update_fields)) {
476 if (empty($uriids)) {
477 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
478 $uriids = array_column($rows, 'uri-id');
480 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
482 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
485 $affected = max($affected, DBA::affectedRows());
488 $update_fields = Post\DeliveryData::extractFields($fields);
489 if (!empty($update_fields)) {
490 if (empty($uriids)) {
491 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
492 $uriids = array_column($rows, 'uri-id');
494 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
496 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
499 $affected = max($affected, DBA::affectedRows());
502 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
503 if (!empty($update_fields)) {
504 $rows = DBA::selectToArray('post-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
505 $uriids = array_column($rows, 'uri-id');
506 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
508 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
511 $affected = max($affected, DBA::affectedRows());
514 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
515 if (!empty($update_fields)) {
516 $rows = DBA::selectToArray('post-view', ['post-user-id'], $thread_condition);
517 $thread_puids = array_column($rows, 'post-user-id');
518 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
520 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
523 $affected = max($affected, DBA::affectedRows());
527 foreach (Item::USED_FIELDLIST as $field) {
528 if (array_key_exists($field, $fields)) {
529 $update_fields[$field] = $fields[$field];
532 if (!empty($update_fields)) {
533 $rows = DBA::selectToArray('post-view', ['item-id'], $condition, []);
534 $ids = array_column($rows, 'item-id');
535 if (!DBA::update('item', $update_fields, ['id' => $ids])) {
537 Logger::notice('Updating item failed', ['fields' => $update_fields, 'condition' => $condition]);
540 $affected = max($affected, DBA::affectedRows());
545 Logger::info('Updated posts', ['rows' => $affected]);
550 * Delete a row from the post table
552 * @param array $conditions Field condition(s)
553 * @param array $options
554 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
555 * relations (default: true)
557 * @return boolean was the delete successful?
560 public static function delete(array $conditions, array $options = [])
562 return DBA::delete('post', $conditions, $options);