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