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\Database\Database;
27 use Friendica\Database\DBA;
28 use Friendica\Database\DBStructure;
29 use Friendica\Protocol\Activity;
34 * Insert a new post entry
36 * @param integer $uri_id
37 * @param array $fields
38 * @return int ID of inserted post
41 public static function insert(int $uri_id, array $data = [])
44 throw new BadMethodCallException('Empty URI_id');
47 $fields = DBStructure::getFieldsForTable('post', $data);
49 // Additionally assign the key fields
50 $fields['uri-id'] = $uri_id;
52 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
56 return DBA::lastInsertId();
60 * Fetch a single post row
62 * @param mixed $stmt statement object
63 * @return array|false current row or false
66 public static function fetch($stmt)
68 $row = DBA::fetch($stmt);
70 if (!is_array($row)) {
74 if (array_key_exists('verb', $row)) {
75 if (in_array($row['verb'], Item::ACTIVITIES)) {
76 if (array_key_exists('title', $row)) {
79 if (array_key_exists('body', $row)) {
80 $row['body'] = $row['verb'];
82 if (array_key_exists('object', $row)) {
85 if (array_key_exists('object-type', $row)) {
86 $row['object-type'] = Activity\ObjectType::NOTE;
88 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
89 // Posts don't have a target - but having tags or files.
90 if (array_key_exists('target', $row)) {
96 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
104 * Fills an array with data from an post query
106 * @param object $stmt statement object
107 * @param bool $do_close
108 * @return array Data array
110 public static function toArray($stmt, $do_close = true) {
111 if (is_bool($stmt)) {
116 while ($row = self::fetch($stmt)) {
126 * Check if post data exists
128 * @param array $condition array of fields for condition
130 * @return boolean Are there rows for that condition?
133 public static function exists($condition) {
134 return DBA::exists('post-view', $condition);
138 * Counts the posts satisfying the provided condition
140 * @param array $condition array of fields for condition
141 * @param array $params Array of several parameters
146 * $condition = ["uid" => 1, "network" => 'dspr'];
148 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
150 * $count = Post::count($condition);
153 public static function count(array $condition = [], array $params = [])
155 return DBA::count('post-view', $condition, $params);
159 * Retrieve a single record from the post table and returns it in an associative array
161 * @param array $fields
162 * @param array $condition
163 * @param array $params
168 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
170 $params['limit'] = 1;
172 $result = self::select($fields, $condition, $params);
174 if (is_bool($result)) {
177 $row = self::fetch($result);
184 * Select rows from the post table and returns them as an array
186 * @param array $selected Array of selected fields, empty for all
187 * @param array $condition Array of fields for condition
188 * @param array $params Array of several parameters
193 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
195 $result = self::select($fields, $condition, $params);
197 if (is_bool($result)) {
202 while ($row = self::fetch($result)) {
211 * Select rows from the given view
213 * @param string $view View (post-view or post-thread-view)
214 * @param array $selected Array of selected fields, empty for all
215 * @param array $condition Array of fields for condition
216 * @param array $params Array of several parameters
218 * @return boolean|object
221 private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
223 if (empty($selected)) {
224 $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
226 if ($view == 'post-thread-view') {
227 $selected = array_merge($selected, ['ignored', 'iid']);
231 $selected = array_unique($selected);
233 return DBA::select($view, $selected, $condition, $params);
237 * Select rows from the post table
239 * @param array $selected Array of selected fields, empty for all
240 * @param array $condition Array of fields for condition
241 * @param array $params Array of several parameters
243 * @return boolean|object
246 public static function select(array $selected = [], array $condition = [], $params = [])
248 return self::selectView('post-view', $selected, $condition, $params);
252 * Select rows from the post table
254 * @param array $selected Array of selected fields, empty for all
255 * @param array $condition Array of fields for condition
256 * @param array $params Array of several parameters
258 * @return boolean|object
261 public static function selectThread(array $selected = [], array $condition = [], $params = [])
263 return self::selectView('post-thread-view', $selected, $condition, $params);
267 * Select rows from the given view for a given user
269 * @param string $view View (post-view or post-thread-view)
270 * @param integer $uid User ID
271 * @param array $selected Array of selected fields, empty for all
272 * @param array $condition Array of fields for condition
273 * @param array $params Array of several parameters
275 * @return boolean|object
278 private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
280 if (empty($selected)) {
281 $selected = Item::DISPLAY_FIELDLIST;
284 $condition = DBA::mergeConditions($condition,
285 ["`visible` AND NOT `deleted`
286 AND NOT `author-blocked` AND NOT `owner-blocked`
287 AND (NOT `causer-blocked` OR `causer-id` = ?) AND NOT `contact-blocked`
288 AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
289 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
290 AND NOT EXISTS (SELECT `uri-id` FROM `post-user` WHERE `hidden` AND `uri-id` = `" . $view . "`.`uri-id` AND `uid` = ?)
291 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
292 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
293 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
294 AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
295 0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
299 if (in_array('pinned', $selected)) {
300 $selected = array_flip($selected);
301 unset($selected['pinned']);
302 $selected = array_flip($selected);
304 $select_string = "(SELECT `pinned` FROM `post-thread-user` WHERE `uri-id` = `" . $view . "`.`uri-id` AND uid=`" . $view . "`.`uid`) AS `pinned`, ";
307 $select_string .= implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
309 $condition_string = DBA::buildCondition($condition);
310 $param_string = DBA::buildParameter($params);
312 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
313 $sql = DBA::cleanQuery($sql);
315 return DBA::p($sql, $condition);
319 * Select rows from the post view for a given user
321 * @param integer $uid User ID
322 * @param array $selected Array of selected fields, empty for all
323 * @param array $condition Array of fields for condition
324 * @param array $params Array of several parameters
326 * @return boolean|object
329 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
331 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
335 * Select rows from the post view for a given user
337 * @param integer $uid User ID
338 * @param array $selected Array of selected fields, empty for all
339 * @param array $condition Array of fields for condition
340 * @param array $params Array of several parameters
342 * @return boolean|object
345 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
347 return self::selectViewForUser('post-thread-view', $uid, $selected, $condition, $params);
351 * Retrieve a single record from the post view for a given user and returns it in an associative array
353 * @param integer $uid User ID
354 * @param array $selected
355 * @param array $condition
356 * @param array $params
361 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
363 $params['limit'] = 1;
365 $result = self::selectForUser($uid, $selected, $condition, $params);
367 if (is_bool($result)) {
370 $row = self::fetch($result);
377 * Select pinned rows from the item table for a given user
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 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
389 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
390 if (!DBA::isResult($postthreaduser)) {
391 return $postthreaduser;
395 while ($useritem = DBA::fetch($postthreaduser)) {
396 $pinned[] = $useritem['uri-id'];
398 DBA::close($postthreaduser);
400 if (empty($pinned)) {
404 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
406 return self::selectForUser($uid, $selected, $condition, $params);
410 * Update existing post entries
412 * @param array $fields The fields that are to be changed
413 * @param array $condition The condition for finding the item entries
415 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
417 * @return integer|boolean number of affected rows - or "false" if there was an error
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 public static function update(array $fields, array $condition)
424 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition]);
426 // Don't allow changes to fields that are responsible for the relation between the records
427 unset($fields['id']);
428 unset($fields['parent']);
429 unset($fields['uid']);
430 unset($fields['uri']);
431 unset($fields['uri-id']);
432 unset($fields['thr-parent']);
433 unset($fields['thr-parent-id']);
434 unset($fields['parent-uri']);
435 unset($fields['parent-uri-id']);
437 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
439 // To ensure the data integrity we do it in an transaction
442 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
443 if (!empty($update_fields)) {
444 $rows = DBA::selectToArray('post-view', ['post-user-id'], $condition);
445 $puids = array_column($rows, 'post-user-id');
446 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
448 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
451 $affected = DBA::affectedRows();
454 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
455 if (!empty($update_fields)) {
456 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
457 $uriids = array_column($rows, 'uri-id');
458 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
460 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
463 $affected = max($affected, DBA::affectedRows());
466 $update_fields = DBStructure::getFieldsForTable('post', $fields);
467 if (!empty($update_fields)) {
468 if (empty($uriids)) {
469 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
470 $uriids = array_column($rows, 'uri-id');
472 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
474 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
477 $affected = max($affected, DBA::affectedRows());
480 $update_fields = Post\DeliveryData::extractFields($fields);
481 if (!empty($update_fields)) {
482 if (empty($uriids)) {
483 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
484 $uriids = array_column($rows, 'uri-id');
486 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
488 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
491 $affected = max($affected, DBA::affectedRows());
494 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
495 if (!empty($update_fields)) {
496 $rows = DBA::selectToArray('post-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
497 $uriids = array_column($rows, 'uri-id');
498 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
500 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
503 $affected = max($affected, DBA::affectedRows());
506 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
507 if (!empty($update_fields)) {
508 $rows = DBA::selectToArray('post-view', ['post-user-id'], $thread_condition);
509 $thread_puids = array_column($rows, 'post-user-id');
510 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
512 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
515 $affected = max($affected, DBA::affectedRows());
520 Logger::info('Updated posts', ['rows' => $affected]);
525 * Delete a row from the post table
527 * @param array $conditions Field condition(s)
528 * @param array $options
529 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
530 * relations (default: true)
532 * @return boolean was the delete successful?
535 public static function delete(array $conditions, array $options = [])
537 return DBA::delete('post', $conditions, $options);