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