ff86dc6f2dd752b49300f3e3aa11dc2f1d6d621b
[friendica.git/.git] / src / Model / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
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;
30
31 class Post
32 {
33         /**
34          * Insert a new post entry
35          *
36          * @param integer $uri_id
37          * @param array   $fields
38          * @return int    ID of inserted post
39          * @throws \Exception
40          */
41         public static function insert(int $uri_id, array $data = [])
42         {
43                 if (empty($uri_id)) {
44                         throw new BadMethodCallException('Empty URI_id');
45                 }
46
47                 $fields = DBStructure::getFieldsForTable('post', $data);
48
49                 // Additionally assign the key fields
50                 $fields['uri-id'] = $uri_id;
51
52                 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
53                         return 0;
54                 }
55
56                 return DBA::lastInsertId();
57         }
58
59         /**
60          * Fetch a single post row
61          *
62          * @param mixed $stmt statement object
63          * @return array|false current row or false
64          * @throws \Exception
65          */
66         public static function fetch($stmt)
67         {
68                 $row = DBA::fetch($stmt);
69
70                 if (!is_array($row)) {
71                         return $row;
72                 }
73
74                 if (array_key_exists('verb', $row)) {
75                         if (in_array($row['verb'], Item::ACTIVITIES)) {
76                                 if (array_key_exists('title', $row)) {
77                                         $row['title'] = '';
78                                 }
79                                 if (array_key_exists('body', $row)) {
80                                         $row['body'] = $row['verb'];
81                                 }
82                                 if (array_key_exists('object', $row)) {
83                                         $row['object'] = '';
84                                 }
85                                 if (array_key_exists('object-type', $row)) {
86                                         $row['object-type'] = Activity\ObjectType::NOTE;
87                                 }
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)) {
91                                         $row['target'] = '';
92                                 }
93                         }
94                 }
95
96                 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
97                         $row['extid'] = '';
98                 }
99
100                 return $row;
101         }
102
103         /**
104          * Fills an array with data from an post query
105          *
106          * @param object $stmt statement object
107          * @param bool   $do_close
108          * @return array Data array
109          */
110         public static function toArray($stmt, $do_close = true) {
111                 if (is_bool($stmt)) {
112                         return $stmt;
113                 }
114
115                 $data = [];
116                 while ($row = self::fetch($stmt)) {
117                         $data[] = $row;
118                 }
119                 if ($do_close) {
120                         DBA::close($stmt);
121                 }
122                 return $data;
123         }
124
125         /**
126          * Check if post data exists
127          *
128          * @param array $condition array of fields for condition
129          *
130          * @return boolean Are there rows for that condition?
131          * @throws \Exception
132          */
133         public static function exists($condition) {
134                 return DBA::exists('post-view', $condition);
135         }
136
137         /**
138          * Counts the posts satisfying the provided condition
139          *
140          * @param array        $condition array of fields for condition
141          * @param array        $params    Array of several parameters
142          *
143          * @return int
144          *
145          * Example:
146          * $condition = ["uid" => 1, "network" => 'dspr'];
147          * or:
148          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
149          *
150          * $count = Post::count($condition);
151          * @throws \Exception
152          */
153         public static function count(array $condition = [], array $params = [])
154         {
155                 return DBA::count('post-view', $condition, $params);
156         }
157
158         /**
159          * Retrieve a single record from the post table and returns it in an associative array
160          *
161          * @param array $fields
162          * @param array $condition
163          * @param array $params
164          * @return bool|array
165          * @throws \Exception
166          * @see   DBA::select
167          */
168         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
169         {
170                 $params['limit'] = 1;
171
172                 $result = self::select($fields, $condition, $params);
173
174                 if (is_bool($result)) {
175                         return $result;
176                 } else {
177                         $row = self::fetch($result);
178                         DBA::close($result);
179                         return $row;
180                 }
181         }
182
183         /**
184          * Select rows from the post table and returns them as an array
185          *
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
189          *
190          * @return array
191          * @throws \Exception
192          */
193         public static function selectToArray(array $fields = [], array $condition = [], $params = [])
194         {
195                 $result = self::select($fields, $condition, $params);
196
197                 if (is_bool($result)) {
198                         return [];
199                 }
200
201                 $data = [];
202                 while ($row = self::fetch($result)) {
203                         $data[] = $row;
204                 }
205                 DBA::close($result);
206
207                 return $data;
208         }
209
210         /**
211          * Select rows from the given view
212          *
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
217          *
218          * @return boolean|object
219          * @throws \Exception
220          */
221         private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
222         {
223                 if (empty($selected)) {
224                         $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
225
226                         if ($view == 'post-thread-view') {
227                                 $selected = array_merge($selected, ['ignored', 'iid']);
228                         }
229                 }
230
231                 $selected = array_unique($selected);
232
233                 return DBA::select($view, $selected, $condition, $params);
234         }
235
236         /**
237          * Select rows from the post table
238          *
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
242          *
243          * @return boolean|object
244          * @throws \Exception
245          */
246         public static function select(array $selected = [], array $condition = [], $params = [])
247         {
248                 return self::selectView('post-view', $selected, $condition, $params);
249         }
250
251         /**
252          * Select rows from the post table
253          *
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
257          *
258          * @return boolean|object
259          * @throws \Exception
260          */
261         public static function selectThread(array $selected = [], array $condition = [], $params = [])
262         {
263                 return self::selectView('post-thread-view', $selected, $condition, $params);
264         }
265
266         /**
267          * Select rows from the given view for a given user
268          *
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
274          *
275          * @return boolean|object
276          * @throws \Exception
277          */
278         private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
279         {
280                 if (empty($selected)) {
281                         $selected = Item::DISPLAY_FIELDLIST;
282                 }
283
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]);
296
297                 $select_string = '';
298
299                 if (in_array('pinned', $selected)) {
300                         $selected = array_flip($selected);
301                         unset($selected['pinned']);
302                         $selected = array_flip($selected);      
303
304                         $select_string = "(SELECT `pinned` FROM `post-thread-user` WHERE `uri-id` = `" . $view . "`.`uri-id` AND uid=`" . $view . "`.`uid`) AS `pinned`, ";
305                 }
306
307                 $select_string .= implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
308
309                 $condition_string = DBA::buildCondition($condition);
310                 $param_string = DBA::buildParameter($params);
311
312                 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
313                 $sql = DBA::cleanQuery($sql);
314
315                 return DBA::p($sql, $condition);
316         }
317
318         /**
319          * Select rows from the post view for a given user
320          *
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
325          *
326          * @return boolean|object
327          * @throws \Exception
328          */
329         public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
330         {
331                 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
332         }
333
334                 /**
335          * Select rows from the post view for a given user
336          *
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
341          *
342          * @return boolean|object
343          * @throws \Exception
344          */
345         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
346         {
347                 return self::selectViewForUser('post-thread-view', $uid, $selected, $condition, $params);
348         }
349
350         /**
351          * Retrieve a single record from the post view for a given user and returns it in an associative array
352          *
353          * @param integer $uid User ID
354          * @param array   $selected
355          * @param array   $condition
356          * @param array   $params
357          * @return bool|array
358          * @throws \Exception
359          * @see   DBA::select
360          */
361         public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
362         {
363                 $params['limit'] = 1;
364
365                 $result = self::selectForUser($uid, $selected, $condition, $params);
366
367                 if (is_bool($result)) {
368                         return $result;
369                 } else {
370                         $row = self::fetch($result);
371                         DBA::close($result);
372                         return $row;
373                 }
374         }
375
376         /**
377          * Select pinned rows from the item table for a given user
378          *
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
383          *
384          * @return boolean|object
385          * @throws \Exception
386          */
387         public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
388         {
389                 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
390                 if (!DBA::isResult($postthreaduser)) {
391                         return $postthreaduser;
392                 }
393         
394                 $pinned = [];
395                 while ($useritem = DBA::fetch($postthreaduser)) {
396                         $pinned[] = $useritem['uri-id'];
397                 }
398                 DBA::close($postthreaduser);
399
400                 if (empty($pinned)) {
401                         return [];
402                 }
403
404                 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
405
406                 return self::selectForUser($uid, $selected, $condition, $params);
407         }
408
409         /**
410          * Update existing post entries
411          *
412          * @param array $fields    The fields that are to be changed
413          * @param array $condition The condition for finding the item entries
414          *
415          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
416          *
417          * @return integer|boolean number of affected rows - or "false" if there was an error
418          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419          */
420         public static function update(array $fields, array $condition)
421         {
422                 $affected = 0;
423
424                 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition]);
425
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']);
436
437                 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
438
439                 // To ensure the data integrity we do it in an transaction
440                 DBA::transaction();
441
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])) {
447                                 DBA::rollback();
448                                 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
449                                 return false;
450                         }
451                         $affected = DBA::affectedRows();                        
452                 }
453
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])) {
459                                 DBA::rollback();
460                                 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
461                                 return false;
462                         }
463                         $affected = max($affected, DBA::affectedRows());
464                 }
465
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');
471                         }
472                         if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
473                                 DBA::rollback();
474                                 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
475                                 return false;
476                         }
477                         $affected = max($affected, DBA::affectedRows());
478                 }
479
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');
485                         }
486                         if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
487                                 DBA::rollback();
488                                 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
489                                 return false;
490                         }
491                         $affected = max($affected, DBA::affectedRows());
492                 }
493
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])) {
499                                 DBA::rollback();
500                                 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
501                                 return false;
502                         }
503                         $affected = max($affected, DBA::affectedRows());
504                 }
505
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])) {
511                                 DBA::rollback();
512                                 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
513                                 return false;
514                         }
515                         $affected = max($affected, DBA::affectedRows());
516                 }
517
518                 DBA::commit();
519
520                 Logger::info('Updated posts', ['rows' => $affected]);
521                 return $affected;
522         }
523
524         /**
525          * Delete a row from the post table
526          *
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)
531          *
532          * @return boolean was the delete successful?
533          * @throws \Exception
534          */
535         public static function delete(array $conditions, array $options = [])
536         {
537                 return DBA::delete('post', $conditions, $options);
538         }
539 }