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