]> git.mxchange.org Git - friendica.git/blob - src/Model/Post.php
fe2171d29432b0854797ad32fedc96a5b2a23a2a
[friendica.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\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
30 use Friendica\Protocol\Activity;
31
32 class Post
33 {
34         /**
35          * Insert a new post entry
36          *
37          * @param integer $uri_id
38          * @param array   $fields
39          * @return int    ID of inserted post
40          * @throws \Exception
41          */
42         public static function insert(int $uri_id, array $data = [])
43         {
44                 if (empty($uri_id)) {
45                         throw new BadMethodCallException('Empty URI_id');
46                 }
47
48                 $fields = DBStructure::getFieldsForTable('post', $data);
49
50                 // Additionally assign the key fields
51                 $fields['uri-id'] = $uri_id;
52
53                 if (!DBA::insert('post', $fields, Database::INSERT_IGNORE)) {
54                         return 0;
55                 }
56
57                 return DBA::lastInsertId();
58         }
59
60         /**
61          * Fetch a single post row
62          *
63          * @param mixed $stmt statement object
64          * @return array|false current row or false
65          * @throws \Exception
66          */
67         public static function fetch($stmt)
68         {
69                 $row = DBA::fetch($stmt);
70
71                 if (!is_array($row)) {
72                         return $row;
73                 }
74
75                 if (array_key_exists('verb', $row)) {
76                         if (in_array($row['verb'], Item::ACTIVITIES)) {
77                                 if (array_key_exists('title', $row)) {
78                                         $row['title'] = '';
79                                 }
80                                 if (array_key_exists('body', $row)) {
81                                         $row['body'] = $row['verb'];
82                                 }
83                                 if (array_key_exists('object', $row)) {
84                                         $row['object'] = '';
85                                 }
86                                 if (array_key_exists('object-type', $row)) {
87                                         $row['object-type'] = Activity\ObjectType::NOTE;
88                                 }
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)) {
92                                         $row['target'] = '';
93                                 }
94                         }
95                 }
96
97                 if (array_key_exists('extid', $row) && is_null($row['extid'])) {
98                         $row['extid'] = '';
99                 }
100
101                 return $row;
102         }
103
104         /**
105          * Fills an array with data from an post query
106          *
107          * @param object $stmt statement object
108          * @param bool   $do_close
109          * @return array Data array
110          */
111         public static function toArray($stmt, $do_close = true) {
112                 if (is_bool($stmt)) {
113                         return $stmt;
114                 }
115
116                 $data = [];
117                 while ($row = self::fetch($stmt)) {
118                         $data[] = $row;
119                 }
120                 if ($do_close) {
121                         DBA::close($stmt);
122                 }
123                 return $data;
124         }
125
126         /**
127          * Check if post data exists
128          *
129          * @param array $condition array of fields for condition
130          *
131          * @return boolean Are there rows for that condition?
132          * @throws \Exception
133          */
134         public static function exists($condition) {
135                 return DBA::exists('post-view', $condition);
136         }
137
138         /**
139          * Counts the posts satisfying the provided condition
140          *
141          * @param array        $condition array of fields for condition
142          * @param array        $params    Array of several parameters
143          *
144          * @return int
145          *
146          * Example:
147          * $condition = ["uid" => 1, "network" => 'dspr'];
148          * or:
149          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
150          *
151          * $count = Post::count($condition);
152          * @throws \Exception
153          */
154         public static function count(array $condition = [], array $params = [])
155         {
156                 return DBA::count('post-view', $condition, $params);
157         }
158
159         /**
160          * Retrieve a single record from the post table and returns it in an associative array
161          *
162          * @param array $fields
163          * @param array $condition
164          * @param array $params
165          * @return bool|array
166          * @throws \Exception
167          * @see   DBA::select
168          */
169         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
170         {
171                 $params['limit'] = 1;
172
173                 $result = self::select($fields, $condition, $params);
174
175                 if (is_bool($result)) {
176                         return $result;
177                 } else {
178                         $row = self::fetch($result);
179                         DBA::close($result);
180                         return $row;
181                 }
182         }
183
184         /**
185          * Select rows from the post table and returns them as an array
186          *
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
190          *
191          * @return array
192          * @throws \Exception
193          */
194         public static function selectToArray(array $fields = [], array $condition = [], $params = [])
195         {
196                 $result = self::select($fields, $condition, $params);
197
198                 if (is_bool($result)) {
199                         return [];
200                 }
201
202                 $data = [];
203                 while ($row = self::fetch($result)) {
204                         $data[] = $row;
205                 }
206                 DBA::close($result);
207
208                 return $data;
209         }
210
211         /**
212          * Select rows from the given view
213          *
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
218          *
219          * @return boolean|object
220          * @throws \Exception
221          */
222         private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
223         {
224                 if (empty($selected)) {
225                         $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
226
227                         if ($view == 'post-thread-view') {
228                                 $selected = array_merge($selected, ['ignored', 'iid']);
229                         }
230                 }
231
232                 $selected = array_unique($selected);
233
234                 return DBA::select($view, $selected, $condition, $params);
235         }
236
237         /**
238          * Select rows from the post table
239          *
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
243          *
244          * @return boolean|object
245          * @throws \Exception
246          */
247         public static function select(array $selected = [], array $condition = [], $params = [])
248         {
249                 return self::selectView('post-view', $selected, $condition, $params);
250         }
251
252         /**
253          * Select rows from the post table
254          *
255          * @param array $selected  Array of selected fields, empty for all
256          * @param array $condition Array of fields for condition
257          * @param array $params    Array of several parameters
258          *
259          * @return boolean|object
260          * @throws \Exception
261          */
262         public static function selectThread(array $selected = [], array $condition = [], $params = [])
263         {
264                 return self::selectView('post-thread-view', $selected, $condition, $params);
265         }
266
267         /**
268          * Select rows from the given view for a given user
269          *
270          * @param string  $view      View (post-view or post-thread-view)
271          * @param integer $uid       User ID
272          * @param array   $selected  Array of selected fields, empty for all
273          * @param array   $condition Array of fields for condition
274          * @param array   $params    Array of several parameters
275          *
276          * @return boolean|object
277          * @throws \Exception
278          */
279         private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
280         {
281                 if (empty($selected)) {
282                         $selected = Item::DISPLAY_FIELDLIST;
283                 }
284
285                 $condition = DBA::mergeConditions($condition,
286                         ["`visible` AND NOT `deleted`
287                         AND NOT `author-blocked` AND NOT `owner-blocked`
288                         AND (NOT `causer-blocked` OR `causer-id` = ?) AND NOT `contact-blocked`
289                         AND ((NOT `contact-readonly` AND NOT `contact-pending` AND (`contact-rel` IN (?, ?)))
290                                 OR `self` OR `gravity` != ? OR `contact-uid` = ?)
291                         AND NOT EXISTS (SELECT `uri-id` FROM `post-user` WHERE `hidden` AND `uri-id` = `" . $view . "`.`uri-id` AND `uid` = ?)
292                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `blocked`)
293                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `blocked`)
294                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `author-id` AND `ignored` AND `gravity` = ?)
295                         AND NOT EXISTS (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `owner-id` AND `ignored` AND `gravity` = ?)",
296                         0, Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, 0, $uid, $uid, $uid, $uid, GRAVITY_PARENT, $uid, GRAVITY_PARENT]);
297
298                 $select_string = '';
299
300                 if (in_array('pinned', $selected)) {
301                         $selected = array_flip($selected);
302                         unset($selected['pinned']);
303                         $selected = array_flip($selected);      
304
305                         $select_string = "(SELECT `pinned` FROM `post-thread-user` WHERE `uri-id` = `" . $view . "`.`uri-id` AND uid=`" . $view . "`.`uid`) AS `pinned`, ";
306                 }
307
308                 $select_string .= implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
309
310                 $condition_string = DBA::buildCondition($condition);
311                 $param_string = DBA::buildParameter($params);
312
313                 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
314                 $sql = DBA::cleanQuery($sql);
315
316                 return DBA::p($sql, $condition);
317         }
318
319         /**
320          * Select rows from the post view for a given user
321          *
322          * @param integer $uid       User ID
323          * @param array   $selected  Array of selected fields, empty for all
324          * @param array   $condition Array of fields for condition
325          * @param array   $params    Array of several parameters
326          *
327          * @return boolean|object
328          * @throws \Exception
329          */
330         public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
331         {
332                 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
333         }
334
335                 /**
336          * Select rows from the post view for a given user
337          *
338          * @param integer $uid       User ID
339          * @param array   $selected  Array of selected fields, empty for all
340          * @param array   $condition Array of fields for condition
341          * @param array   $params    Array of several parameters
342          *
343          * @return boolean|object
344          * @throws \Exception
345          */
346         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
347         {
348                 return self::selectViewForUser('post-thread-view', $uid, $selected, $condition, $params);
349         }
350
351         /**
352          * Retrieve a single record from the post view for a given user and returns it in an associative array
353          *
354          * @param integer $uid User ID
355          * @param array   $selected
356          * @param array   $condition
357          * @param array   $params
358          * @return bool|array
359          * @throws \Exception
360          * @see   DBA::select
361          */
362         public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
363         {
364                 $params['limit'] = 1;
365
366                 $result = self::selectForUser($uid, $selected, $condition, $params);
367
368                 if (is_bool($result)) {
369                         return $result;
370                 } else {
371                         $row = self::fetch($result);
372                         DBA::close($result);
373                         return $row;
374                 }
375         }
376
377         /**
378          * Select pinned rows from the item table for a given user
379          *
380          * @param integer $uid       User ID
381          * @param array   $selected  Array of selected fields, empty for all
382          * @param array   $condition Array of fields for condition
383          * @param array   $params    Array of several parameters
384          *
385          * @return boolean|object
386          * @throws \Exception
387          */
388         public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
389         {
390                 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
391                 if (!DBA::isResult($postthreaduser)) {
392                         return $postthreaduser;
393                 }
394         
395                 $pinned = [];
396                 while ($useritem = DBA::fetch($postthreaduser)) {
397                         $pinned[] = $useritem['uri-id'];
398                 }
399                 DBA::close($postthreaduser);
400
401                 if (empty($pinned)) {
402                         return [];
403                 }
404
405                 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
406
407                 return self::selectForUser($uid, $selected, $condition, $params);
408         }
409
410         /**
411          * Update existing post entries
412          *
413          * @param array $fields    The fields that are to be changed
414          * @param array $condition The condition for finding the item entries
415          *
416          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
417          *
418          * @return integer|boolean number of affected rows - or "false" if there was an error
419          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420          */
421         public static function update(array $fields, array $condition)
422         {
423                 $affected = 0;
424
425                 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition]);
426
427                 // Don't allow changes to fields that are responsible for the relation between the records
428                 unset($fields['id']);
429                 unset($fields['parent']);
430                 unset($fields['uid']);
431                 unset($fields['uri']);
432                 unset($fields['uri-id']);
433                 unset($fields['thr-parent']);
434                 unset($fields['thr-parent-id']);
435                 unset($fields['parent-uri']);
436                 unset($fields['parent-uri-id']);
437
438                 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
439
440                 // To ensure the data integrity we do it in an transaction
441                 DBA::transaction();
442
443                 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
444                 if (!empty($update_fields)) {
445                         $rows = DBA::selectToArray('post-view', ['post-user-id'], $condition);
446                         $puids = array_column($rows, 'post-user-id');
447                         if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
448                                 DBA::rollback();
449                                 Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
450                                 return false;
451                         }
452                         $affected = DBA::affectedRows();                        
453                 }
454
455                 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
456                 if (!empty($update_fields)) {
457                         $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
458                         $uriids = array_column($rows, 'uri-id');
459                         if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
460                                 DBA::rollback();
461                                 Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
462                                 return false;
463                         }
464                         $affected = max($affected, DBA::affectedRows());
465                 }
466
467                 $update_fields = DBStructure::getFieldsForTable('post', $fields);
468                 if (!empty($update_fields)) {
469                         if (empty($uriids)) {
470                                 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
471                                 $uriids = array_column($rows, 'uri-id');
472                         }
473                         if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
474                                 DBA::rollback();
475                                 Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
476                                 return false;
477                         }
478                         $affected = max($affected, DBA::affectedRows());
479                 }
480
481                 $update_fields = Post\DeliveryData::extractFields($fields);
482                 if (!empty($update_fields)) {
483                         if (empty($uriids)) {
484                                 $rows = DBA::selectToArray('post-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
485                                 $uriids = array_column($rows, 'uri-id');
486                         }
487                         if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
488                                 DBA::rollback();
489                                 Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
490                                 return false;
491                         }
492                         $affected = max($affected, DBA::affectedRows());
493                 }
494
495                 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
496                 if (!empty($update_fields)) {
497                         $rows = DBA::selectToArray('post-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
498                         $uriids = array_column($rows, 'uri-id');
499                         if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
500                                 DBA::rollback();
501                                 Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
502                                 return false;
503                         }
504                         $affected = max($affected, DBA::affectedRows());
505                 }
506
507                 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
508                 if (!empty($update_fields)) {
509                         $rows = DBA::selectToArray('post-view', ['post-user-id'], $thread_condition);
510                         $thread_puids = array_column($rows, 'post-user-id');
511                         if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
512                                 DBA::rollback();
513                                 Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
514                                 return false;
515                         }
516                         $affected = max($affected, DBA::affectedRows());
517                 }
518
519                 $update_fields = [];
520                 foreach (Item::USED_FIELDLIST as $field) {
521                         if (array_key_exists($field, $fields)) {
522                                 $update_fields[$field] = $fields[$field];
523                         }
524                 }
525                 if (!empty($update_fields)) {
526                         $rows = DBA::selectToArray('post-view', ['item-id'], $condition, []);
527                         $ids = array_column($rows, 'item-id');
528                         if (!DBA::update('item', $update_fields, ['id' => $ids])) {
529                                 DBA::rollback();
530                                 Logger::notice('Updating item failed', ['fields' => $update_fields, 'condition' => $condition]);
531                                 return false;
532                         }
533                         $affected = max($affected, DBA::affectedRows());
534                 }
535
536                 DBA::commit();
537
538                 Logger::info('Updated posts', ['rows' => $affected]);
539                 return $affected;
540         }
541
542         /**
543          * Delete a row from the post table
544          *
545          * @param array        $conditions Field condition(s)
546          * @param array        $options
547          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
548          *                           relations (default: true)
549          *
550          * @return boolean was the delete successful?
551          * @throws \Exception
552          */
553         public static function delete(array $conditions, array $options = [])
554         {
555                 return DBA::delete('post', $conditions, $options);
556         }
557 }