]> git.mxchange.org Git - friendica.git/blob - src/Model/Post.php
Display featured posts for contacts
[friendica.git] / src / Model / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
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-user-view records 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-user-view', $condition);
136         }
137
138         /**
139          * Counts the post-user-view records 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-user-view', $condition, $params);
157         }
158
159         /**
160          * Counts the post-thread-user-view records satisfying the provided condition
161          *
162          * @param array        $condition array of fields for condition
163          * @param array        $params    Array of several parameters
164          *
165          * @return int
166          *
167          * Example:
168          * $condition = ["uid" => 1, "network" => 'dspr'];
169          * or:
170          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
171          *
172          * $count = Post::count($condition);
173          * @throws \Exception
174          */
175         public static function countThread(array $condition = [], array $params = [])
176         {
177                 return DBA::count('post-thread-user-view', $condition, $params);
178         }
179
180         /**
181          * Counts the post-view records satisfying the provided condition
182          *
183          * @param array        $condition array of fields for condition
184          * @param array        $params    Array of several parameters
185          *
186          * @return int
187          *
188          * Example:
189          * $condition = ["network" => 'dspr'];
190          * or:
191          * $condition = ["`network` IN (?, ?)", 1, 'dfrn', 'dspr'];
192          *
193          * $count = Post::count($condition);
194          * @throws \Exception
195          */
196         public static function countPosts(array $condition = [], array $params = [])
197         {
198                 return DBA::count('post-view', $condition, $params);
199         }
200
201         /**
202          * Retrieve a single record from the post-user-view view and returns it in an associative array
203          *
204          * @param array $fields
205          * @param array $condition
206          * @param array $params
207          * @param bool  $user_mode true = post-user-view, false = post-view
208          * @return bool|array
209          * @throws \Exception
210          * @see   DBA::select
211          */
212         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
213         {
214                 $params['limit'] = 1;
215
216                 $result = self::select($fields, $condition, $params);
217
218                 if (is_bool($result)) {
219                         return $result;
220                 } else {
221                         $row = self::fetch($result);
222                         DBA::close($result);
223                         return $row;
224                 }
225         }
226
227         /**
228          * Retrieve a single record from the post-view view and returns it in an associative array
229          *
230          * @param array $fields
231          * @param array $condition
232          * @param array $params
233          * @return bool|array
234          * @throws \Exception
235          * @see   DBA::select
236          */
237         public static function selectFirstPost(array $fields = [], array $condition = [], $params = [])
238         {
239                 $params['limit'] = 1;
240
241                 $result = self::selectPosts($fields, $condition, $params);
242
243                 if (is_bool($result)) {
244                         return $result;
245                 } else {
246                         $row = self::fetch($result);
247                         DBA::close($result);
248                         return $row;
249                 }
250         }
251
252         /**
253          * Retrieve a single record from the post-thread-user-view view and returns it in an associative array
254          *
255          * @param array $fields
256          * @param array $condition
257          * @param array $params
258          * @return bool|array
259          * @throws \Exception
260          * @see   DBA::select
261          */
262         public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
263         {
264                 $params['limit'] = 1;
265
266                 $result = self::selectThread($fields, $condition, $params);
267
268                 if (is_bool($result)) {
269                         return $result;
270                 } else {
271                         $row = self::fetch($result);
272                         DBA::close($result);
273                         return $row;
274                 }
275         }
276
277         /**
278          * Select rows from the post-user-view view and returns them as an array
279          *
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
283          *
284          * @return array
285          * @throws \Exception
286          */
287         public static function selectToArray(array $fields = [], array $condition = [], $params = [])
288         {
289                 $result = self::select($fields, $condition, $params);
290
291                 if (is_bool($result)) {
292                         return [];
293                 }
294
295                 $data = [];
296                 while ($row = self::fetch($result)) {
297                         $data[] = $row;
298                 }
299                 DBA::close($result);
300
301                 return $data;
302         }
303
304         /**
305          * Select rows from the given view
306          *
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
311          *
312          * @return boolean|object
313          * @throws \Exception
314          */
315         private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
316         {
317                 if (empty($selected)) {
318                         $selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
319
320                         if ($view == 'post-thread-user-view') {
321                                 $selected = array_merge($selected, ['ignored']);
322                         }
323                 }
324
325                 $selected = array_unique($selected);
326
327                 return DBA::select($view, $selected, $condition, $params);
328         }
329
330         /**
331          * Select rows from the post-user-view view
332          *
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
336          *
337          * @return boolean|object
338          * @throws \Exception
339          */
340         public static function select(array $selected = [], array $condition = [], $params = [])
341         {
342                 return self::selectView('post-user-view', $selected, $condition, $params);
343         }
344
345         /**
346          * Select rows from the post-view view
347          *
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
351          *
352          * @return boolean|object
353          * @throws \Exception
354          */
355         public static function selectPosts(array $selected = [], array $condition = [], $params = [])
356         {
357                 return self::selectView('post-view', $selected, $condition, $params);
358         }
359
360         /**
361          * Select rows from the post-thread-user-view view
362          *
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
366          *
367          * @return boolean|object
368          * @throws \Exception
369          */
370         public static function selectThread(array $selected = [], array $condition = [], $params = [])
371         {
372                 return self::selectView('post-thread-user-view', $selected, $condition, $params);
373         }
374
375         /**
376          * Select rows from the given view for a given user
377          *
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
383          *
384          * @return boolean|object
385          * @throws \Exception
386          */
387         private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
388         {
389                 if (empty($selected)) {
390                         $selected = Item::DISPLAY_FIELDLIST;
391                 }
392
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]);
405
406                 $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
407
408                 $condition_string = DBA::buildCondition($condition);
409                 $param_string = DBA::buildParameter($params);
410
411                 $sql = "SELECT " . $select_string . " FROM `" . $view . "` " . $condition_string . $param_string;
412                 $sql = DBA::cleanQuery($sql);
413
414                 return DBA::p($sql, $condition);
415         }
416
417         /**
418          * Select rows from the post-user-view view for a given user
419          *
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
424          *
425          * @return boolean|object
426          * @throws \Exception
427          */
428         public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
429         {
430                 return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
431         }
432
433         /**
434          * Select rows from the post-view view for a given user
435          *
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
440          *
441          * @return boolean|object
442          * @throws \Exception
443          */
444         public static function selectPostsForUser($uid, array $selected = [], array $condition = [], $params = [])
445         {
446                 return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
447         }
448
449         /**
450          * Select rows from the post-thread-user-view view for a given user
451          *
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
456          *
457          * @return boolean|object
458          * @throws \Exception
459          */
460         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
461         {
462                 return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
463         }
464
465         /**
466          * Retrieve a single record from the post-user-view view for a given user and returns it in an associative array
467          *
468          * @param integer $uid User ID
469          * @param array   $selected
470          * @param array   $condition
471          * @param array   $params
472          * @return bool|array
473          * @throws \Exception
474          * @see   DBA::select
475          */
476         public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
477         {
478                 $params['limit'] = 1;
479
480                 $result = self::selectForUser($uid, $selected, $condition, $params);
481
482                 if (is_bool($result)) {
483                         return $result;
484                 } else {
485                         $row = self::fetch($result);
486                         DBA::close($result);
487                         return $row;
488                 }
489         }
490
491         /**
492          * Update existing post entries
493          *
494          * @param array $fields    The fields that are to be changed
495          * @param array $condition The condition for finding the item entries
496          *
497          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
498          *
499          * @return integer|boolean number of affected rows - or "false" if there was an error
500          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501          */
502         public static function update(array $fields, array $condition)
503         {
504                 $affected = 0;
505
506                 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => local_user(),'callstack' => System::callstack(10)]);
507
508                 // Don't allow changes to fields that are responsible for the relation between the records
509                 unset($fields['id']);
510                 unset($fields['parent']);
511                 unset($fields['uid']);
512                 unset($fields['uri']);
513                 unset($fields['uri-id']);
514                 unset($fields['thr-parent']);
515                 unset($fields['thr-parent-id']);
516                 unset($fields['parent-uri']);
517                 unset($fields['parent-uri-id']);
518
519                 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
520
521                 // To ensure the data integrity we do it in an transaction
522                 DBA::transaction();
523
524                 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
525                 if (!empty($update_fields)) {
526                         $affected_count = 0;
527                         $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
528                         while ($rows = DBA::toArray($posts, false, 100)) {
529                                 $puids = array_column($rows, 'post-user-id');
530                                 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
531                                         DBA::rollback();
532                                         Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
533                                         return false;
534                                 }
535                                 $affected_count += DBA::affectedRows();
536                         }
537                         DBA::close($posts);
538                         $affected = $affected_count;
539                 }
540
541                 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
542                 if (!empty($update_fields)) {
543                         $affected_count = 0;
544                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
545                         while ($rows = DBA::toArray($posts, false, 100)) {
546                                 $uriids = array_column($rows, 'uri-id');
547                                 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
548                                         DBA::rollback();
549                                         Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
550                                         return false;
551                                 }
552                                 $affected_count += DBA::affectedRows();
553                         }
554                         DBA::close($posts);
555                         $affected = max($affected, $affected_count);
556                 }
557
558                 $update_fields = DBStructure::getFieldsForTable('post', $fields);
559                 if (!empty($update_fields)) {
560                         $affected_count = 0;
561                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
562                         while ($rows = DBA::toArray($posts, false, 100)) {
563                                 $uriids = array_column($rows, 'uri-id');
564                                 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
565                                         DBA::rollback();
566                                         Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
567                                         return false;
568                                 }
569                                 $affected_count += DBA::affectedRows();
570                         }
571                         DBA::close($posts);
572                         $affected = max($affected, $affected_count);
573                 }
574
575                 $update_fields = Post\DeliveryData::extractFields($fields);
576                 if (!empty($update_fields)) {
577                         $affected_count = 0;
578                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
579                         while ($rows = DBA::toArray($posts, false, 100)) {
580                                 $uriids = array_column($rows, 'uri-id');
581                                 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
582                                         DBA::rollback();
583                                         Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
584                                         return false;
585                                 }
586                                 $affected_count += DBA::affectedRows();
587                         }
588                         DBA::close($posts);
589                         $affected = max($affected, $affected_count);
590                 }
591
592                 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
593                 if (!empty($update_fields)) {
594                         $affected_count = 0;
595                         $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
596                         while ($rows = DBA::toArray($posts, false, 100)) {
597                                 $uriids = array_column($rows, 'uri-id');
598                                 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
599                                         DBA::rollback();
600                                         Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
601                                         return false;
602                                 }
603                                 $affected_count += DBA::affectedRows();
604                         }
605                         DBA::close($posts);
606                         $affected = max($affected, $affected_count);
607                 }
608
609                 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
610                 if (!empty($update_fields)) {
611                         $affected_count = 0;
612                         $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
613                         while ($rows = DBA::toArray($posts, false, 100)) {
614                                 $thread_puids = array_column($rows, 'post-user-id');
615                                 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
616                                         DBA::rollback();
617                                         Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
618                                         return false;
619                                 }
620                                 $affected_count += DBA::affectedRows();
621                         }
622                         DBA::close($posts);
623                         $affected = max($affected, $affected_count);
624                 }
625
626                 DBA::commit();
627
628                 Logger::info('Updated posts', ['rows' => $affected]);
629                 return $affected;
630         }
631
632         /**
633          * Delete a row from the post table
634          *
635          * @param array        $conditions Field condition(s)
636          * @param array        $options
637          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
638          *                           relations (default: true)
639          *
640          * @return boolean was the delete successful?
641          * @throws \Exception
642          */
643         public static function delete(array $conditions, array $options = [])
644         {
645                 return DBA::delete('post', $conditions, $options);
646         }
647 }