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