]> git.mxchange.org Git - friendica.git/blob - src/Model/Post.php
Merge pull request #10969 from MrPetovan/task/remove-private-contacts
[friendica.git] / src / Model / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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          * Select pinned rows from the post-thread-user table for a given user
493          *
494          * @param integer $uid       User ID
495          * @param array   $selected  Array of selected fields, empty for all
496          * @param array   $condition Array of fields for condition
497          * @param array   $params    Array of several parameters
498          *
499          * @return boolean|object
500          * @throws \Exception
501          */
502         public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
503         {
504                 $postthreaduser = DBA::select('post-thread-user', ['uri-id'], ['uid' => $uid, 'pinned' => true]);
505                 if (!DBA::isResult($postthreaduser)) {
506                         return $postthreaduser;
507                 }
508
509                 $pinned = [];
510                 while ($useritem = DBA::fetch($postthreaduser)) {
511                         $pinned[] = $useritem['uri-id'];
512                 }
513                 DBA::close($postthreaduser);
514
515                 if (empty($pinned)) {
516                         return [];
517                 }
518
519                 $condition = DBA::mergeConditions(['uri-id' => $pinned, 'uid' => $uid, 'gravity' => GRAVITY_PARENT], $condition);
520
521                 return self::selectForUser($uid, $selected, $condition, $params);
522         }
523
524         /**
525          * Update existing post entries
526          *
527          * @param array $fields    The fields that are to be changed
528          * @param array $condition The condition for finding the item entries
529          *
530          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
531          *
532          * @return integer|boolean number of affected rows - or "false" if there was an error
533          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
534          */
535         public static function update(array $fields, array $condition)
536         {
537                 $affected = 0;
538
539                 Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => local_user(),'callstack' => System::callstack(10)]);
540
541                 // Don't allow changes to fields that are responsible for the relation between the records
542                 unset($fields['id']);
543                 unset($fields['parent']);
544                 unset($fields['uid']);
545                 unset($fields['uri']);
546                 unset($fields['uri-id']);
547                 unset($fields['thr-parent']);
548                 unset($fields['thr-parent-id']);
549                 unset($fields['parent-uri']);
550                 unset($fields['parent-uri-id']);
551
552                 $thread_condition = DBA::mergeConditions($condition, ['gravity' => GRAVITY_PARENT]);
553
554                 // To ensure the data integrity we do it in an transaction
555                 DBA::transaction();
556
557                 $update_fields = DBStructure::getFieldsForTable('post-user', $fields);
558                 if (!empty($update_fields)) {
559                         $affected_count = 0;
560                         $posts = DBA::select('post-user-view', ['post-user-id'], $condition);
561                         while ($rows = DBA::toArray($posts, false, 100)) {
562                                 $puids = array_column($rows, 'post-user-id');
563                                 if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
564                                         DBA::rollback();
565                                         Logger::notice('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
566                                         return false;
567                                 }
568                                 $affected_count += DBA::affectedRows();
569                         }
570                         DBA::close($posts);
571                         $affected = $affected_count;
572                 }
573
574                 $update_fields = DBStructure::getFieldsForTable('post-content', $fields);
575                 if (!empty($update_fields)) {
576                         $affected_count = 0;
577                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
578                         while ($rows = DBA::toArray($posts, false, 100)) {
579                                 $uriids = array_column($rows, 'uri-id');
580                                 if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
581                                         DBA::rollback();
582                                         Logger::notice('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
583                                         return false;
584                                 }
585                                 $affected_count += DBA::affectedRows();
586                         }
587                         DBA::close($posts);
588                         $affected = max($affected, $affected_count);
589                 }
590
591                 $update_fields = DBStructure::getFieldsForTable('post', $fields);
592                 if (!empty($update_fields)) {
593                         $affected_count = 0;
594                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
595                         while ($rows = DBA::toArray($posts, false, 100)) {
596                                 $uriids = array_column($rows, 'uri-id');
597                                 if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
598                                         DBA::rollback();
599                                         Logger::notice('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
600                                         return false;
601                                 }
602                                 $affected_count += DBA::affectedRows();
603                         }
604                         DBA::close($posts);
605                         $affected = max($affected, $affected_count);
606                 }
607
608                 $update_fields = Post\DeliveryData::extractFields($fields);
609                 if (!empty($update_fields)) {
610                         $affected_count = 0;
611                         $posts = DBA::select('post-user-view', ['uri-id'], $condition, ['group_by' => ['uri-id']]);
612                         while ($rows = DBA::toArray($posts, false, 100)) {
613                                 $uriids = array_column($rows, 'uri-id');
614                                 if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
615                                         DBA::rollback();
616                                         Logger::notice('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
617                                         return false;
618                                 }
619                                 $affected_count += DBA::affectedRows();
620                         }
621                         DBA::close($posts);
622                         $affected = max($affected, $affected_count);
623                 }
624
625                 $update_fields = DBStructure::getFieldsForTable('post-thread', $fields);
626                 if (!empty($update_fields)) {
627                         $affected_count = 0;
628                         $posts = DBA::select('post-user-view', ['uri-id'], $thread_condition, ['group_by' => ['uri-id']]);
629                         while ($rows = DBA::toArray($posts, false, 100)) {
630                                 $uriids = array_column($rows, 'uri-id');
631                                 if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
632                                         DBA::rollback();
633                                         Logger::notice('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
634                                         return false;
635                                 }
636                                 $affected_count += DBA::affectedRows();
637                         }
638                         DBA::close($posts);
639                         $affected = max($affected, $affected_count);
640                 }
641
642                 $update_fields = DBStructure::getFieldsForTable('post-thread-user', $fields);
643                 if (!empty($update_fields)) {
644                         $affected_count = 0;
645                         $posts = DBA::select('post-user-view', ['post-user-id'], $thread_condition);
646                         while ($rows = DBA::toArray($posts, false, 100)) {
647                                 $thread_puids = array_column($rows, 'post-user-id');
648                                 if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
649                                         DBA::rollback();
650                                         Logger::notice('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
651                                         return false;
652                                 }
653                                 $affected_count += DBA::affectedRows();
654                         }
655                         DBA::close($posts);
656                         $affected = max($affected, $affected_count);
657                 }
658
659                 DBA::commit();
660
661                 Logger::info('Updated posts', ['rows' => $affected]);
662                 return $affected;
663         }
664
665         /**
666          * Delete a row from the post table
667          *
668          * @param array        $conditions Field condition(s)
669          * @param array        $options
670          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
671          *                           relations (default: true)
672          *
673          * @return boolean was the delete successful?
674          * @throws \Exception
675          */
676         public static function delete(array $conditions, array $options = [])
677         {
678                 return DBA::delete('post', $conditions, $options);
679         }
680 }