]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
"item" is replaced by "post-view" / postupdate check added
[friendica.git] / src / Model / Item.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 Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
35 use Friendica\Database\DBStructure;
36 use Friendica\DI;
37 use Friendica\Model\Post;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Map;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Worker\Delivery;
46 use Friendica\Repository\PermissionSet as RepPermissionSet;
47 use LanguageDetection\Language;
48
49 class Item
50 {
51         // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
52         const PT_ARTICLE = 0;
53         const PT_NOTE = 1;
54         const PT_PAGE = 2;
55         const PT_IMAGE = 16;
56         const PT_AUDIO = 17;
57         const PT_VIDEO = 18;
58         const PT_DOCUMENT = 19;
59         const PT_EVENT = 32;
60         const PT_TAG = 64;
61         const PT_TO = 65;
62         const PT_CC = 66;
63         const PT_BTO = 67;
64         const PT_BCC = 68;
65         const PT_FOLLOWER = 69;
66         const PT_ANNOUNCEMENT = 70;
67         const PT_COMMENT = 71;
68         const PT_STORED = 72;
69         const PT_GLOBAL = 73;
70         const PT_RELAY = 74;
71         const PT_FETCHED = 75;
72         const PT_PERSONAL_NOTE = 128;
73
74         // Field list that is used to display the items
75         const DISPLAY_FIELDLIST = [
76                 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
77                 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
78                 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'language',
79                 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
80                 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
81                 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
82                 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
83                 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type',
84                 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
85                 'writable', 'self', 'cid', 'alias',
86                 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
87                 'event-summary', 'event-desc', 'event-location', 'event-type',
88                 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
89                 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
90         ];
91
92         // Field list that is used to deliver items via the protocols
93         const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
94                         'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
95                         'private', 'title', 'body', 'location', 'coord', 'app',
96                         'deleted', 'extid', 'post-type', 'gravity',
97                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
98                         'author-id', 'author-link', 'owner-link', 'contact-uid',
99                         'signed_text', 'network'];
100
101         // Field list for "item-content" table that is mixed with the item table
102         const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
103                         'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
104                         'object-type', 'object', 'target-type', 'target', 'plink'];
105
106         // Field list for "item-content" table that is not present in the "item" table
107         const CONTENT_FIELDLIST = ['language', 'raw-body'];
108
109         // All fields in the item table
110         const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
111                         'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
112                         'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
113                         'created', 'edited', 'commented', 'received', 'changed', 'verb',
114                         'postopts', 'plink', 'resource-id', 'event-id', 'inform',
115                         'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
116                         'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
117                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
118                         'title', 'content-warning', 'body', 'location', 'coord', 'app',
119                         'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
120                         'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
121                         'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
122
123         // List of all verbs that don't need additional content data.
124         // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
125         const ACTIVITIES = [
126                 Activity::LIKE, Activity::DISLIKE,
127                 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
128                 Activity::FOLLOW,
129                 Activity::ANNOUNCE];
130
131         const PUBLIC = 0;
132         const PRIVATE = 1;
133         const UNLISTED = 2;
134
135         const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction'];
136
137         private static $legacy_mode = null;
138
139         private static function getItemFields()
140         {
141                 $definition = DBStructure::definition('', false);
142
143                 $postfields = [];
144                 foreach (self::TABLES as $table) {
145                         $postfields[$table] = array_keys($definition[$table]['fields']);
146                 }
147
148                 return $postfields;
149         }
150
151         /**
152          * Set the pinned state of an item
153          *
154          * @param integer $iid    Item ID
155          * @param integer $uid    User ID
156          * @param boolean $pinned Pinned state
157          */
158         public static function setPinned(int $iid, int $uid, bool $pinned)
159         {
160                 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
161         }
162
163         /**
164          * Get the pinned state
165          *
166          * @param integer $iid Item ID
167          * @param integer $uid User ID
168          *
169          * @return boolean pinned state
170          */
171         public static function getPinned(int $iid, int $uid)
172         {
173                 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
174                 if (!DBA::isResult($useritem)) {
175                         return false;
176                 }
177                 return (bool)$useritem['pinned'];
178         }
179
180         /**
181          * Select pinned rows from the item table for a given user
182          *
183          * @param integer $uid       User ID
184          * @param array   $selected  Array of selected fields, empty for all
185          * @param array   $condition Array of fields for condition
186          * @param array   $params    Array of several parameters
187          *
188          * @return boolean|object
189          * @throws \Exception
190          */
191         public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
192         {
193                 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
194                 if (!DBA::isResult($useritems)) {
195                         return $useritems;
196                 }
197
198                 $pinned = [];
199                 while ($useritem = DBA::fetch($useritems)) {
200                         $pinned[] = $useritem['iid'];
201                 }
202                 DBA::close($useritems);
203
204                 if (empty($pinned)) {
205                         return [];
206                 }
207
208                 $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
209
210                 return self::selectThreadForUser($uid, $selected, $condition, $params);
211         }
212
213         /**
214          * Fetch a single item row
215          *
216          * @param mixed $stmt statement object
217          * @return array|false current row or false
218          * @throws \Exception
219          */
220         private static function fetch($stmt)
221         {
222                 $row = DBA::fetch($stmt);
223
224                 if (!is_array($row)) {
225                         return $row;
226                 }
227
228                 $row = DBA::castFields('item', $row);
229
230                 // ---------------------- Transform item structure data ----------------------
231
232                 // We prefer the data from the user's contact over the public one
233                 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
234                         ($row['author-link'] == $row['contact-link'])) {
235                         if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
236                                 $row['author-avatar'] = $row['contact-avatar'];
237                         }
238                         if (isset($row['author-name']) && !empty($row['contact-name'])) {
239                                 $row['author-name'] = $row['contact-name'];
240                         }
241                 }
242
243                 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
244                         ($row['owner-link'] == $row['contact-link'])) {
245                         if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
246                                 $row['owner-avatar'] = $row['contact-avatar'];
247                         }
248                         if (isset($row['owner-name']) && !empty($row['contact-name'])) {
249                                 $row['owner-name'] = $row['contact-name'];
250                         }
251                 }
252
253                 // We can always comment on posts from these networks
254                 if (array_key_exists('writable', $row) &&
255                         in_array($row['internal-network'], Protocol::FEDERATED)) {
256                         $row['writable'] = 1;
257                 }
258
259                 // ---------------------- Transform item content data ----------------------
260
261                 if (array_key_exists('verb', $row)) {
262                         if (!is_null($row['internal-verb'])) {
263                                 $row['verb'] = $row['internal-verb'];
264                         }
265
266                         if (in_array($row['verb'], self::ACTIVITIES)) {
267                                 if (array_key_exists('title', $row)) {
268                                         $row['title'] = '';
269                                 }
270                                 if (array_key_exists('body', $row)) {
271                                         $row['body'] = $row['verb'];
272                                 }
273                                 if (array_key_exists('object', $row)) {
274                                         $row['object'] = '';
275                                 }
276                                 if (array_key_exists('object-type', $row)) {
277                                         $row['object-type'] = Activity\ObjectType::NOTE;
278                                 }
279                         } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
280                                 // Posts don't have a target - but having tags or files.
281                                 if (array_key_exists('target', $row)) {
282                                         $row['target'] = '';
283                                 }
284                         }
285                 }
286
287                 if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
288                         $row['vid'] = Verb::getID($row['verb']);
289                 }
290                         
291                 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
292                         // Build the file string out of the term entries
293                         if (array_key_exists('file', $row) && empty($row['file'])) {
294                                 $row['file'] = Post\Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
295                         }
296                 }
297
298                 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
299                         if (array_key_exists('allow_cid', $row)) {
300                                 $row['allow_cid'] = '';
301                         }
302                         if (array_key_exists('allow_gid', $row)) {
303                                 $row['allow_gid'] = '';
304                         }
305                         if (array_key_exists('deny_cid', $row)) {
306                                 $row['deny_cid'] = '';
307                         }
308                         if (array_key_exists('deny_gid', $row)) {
309                                 $row['deny_gid'] = '';
310                         }
311                 }
312
313                 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
314                         $row['ignored'] = $row['internal-user-ignored'];
315                 }
316
317                 // Remove internal fields
318                 unset($row['internal-network']);
319                 unset($row['internal-uri-id']);
320                 unset($row['internal-uid']);
321                 unset($row['internal-psid']);
322                 unset($row['internal-verb']);
323                 unset($row['internal-user-ignored']);
324                 unset($row['interaction']);
325
326                 return $row;
327         }
328
329         /**
330          * Fills an array with data from an item query
331          *
332          * @param object $stmt statement object
333          * @param bool   $do_close
334          * @return array Data array
335          */
336         public static function toArray($stmt, $do_close = true) {
337                 if (is_bool($stmt)) {
338                         return $stmt;
339                 }
340
341                 $data = [];
342                 while ($row = self::fetch($stmt)) {
343                         $data[] = $row;
344                 }
345                 if ($do_close) {
346                         DBA::close($stmt);
347                 }
348                 return $data;
349         }
350
351         /**
352          * Check if item data exists
353          *
354          * @param array $condition array of fields for condition
355          *
356          * @return boolean Are there rows for that condition?
357          * @throws \Exception
358          */
359         public static function exists($condition) {
360                 $stmt = self::select(['id'], $condition, ['limit' => 1]);
361
362                 if (is_bool($stmt)) {
363                         $retval = $stmt;
364                 } else {
365                         $retval = (DBA::numRows($stmt) > 0);
366                 }
367
368                 DBA::close($stmt);
369
370                 return $retval;
371         }
372
373         /**
374          * Retrieve a single record from the item table and returns it in an associative array
375          *
376          * @param array $fields
377          * @param array $condition
378          * @param array $params
379          * @return bool|array
380          * @throws \Exception
381          * @see   DBA::select
382          */
383         public static function selectFirst(array $fields = [], array $condition = [], $params = [])
384         {
385                 $params['limit'] = 1;
386
387                 $result = self::select($fields, $condition, $params);
388
389                 if (is_bool($result)) {
390                         return $result;
391                 } else {
392                         $row = self::fetch($result);
393                         DBA::close($result);
394                         return $row;
395                 }
396         }
397
398         /**
399          * Select rows from the item table and returns them as an array
400          *
401          * @param array $selected  Array of selected fields, empty for all
402          * @param array $condition Array of fields for condition
403          * @param array $params    Array of several parameters
404          *
405          * @return array
406          * @throws \Exception
407          */
408         public static function selectToArray(array $fields = [], array $condition = [], $params = [])
409         {
410                 $result = self::select($fields, $condition, $params);
411
412                 if (is_bool($result)) {
413                         return [];
414                 }
415
416                 $data = [];
417                 while ($row = self::fetch($result)) {
418                         $data[] = $row;
419                 }
420                 DBA::close($result);
421
422                 return $data;
423         }
424
425         /**
426          * Select rows from the item table
427          *
428          * @param array $selected  Array of selected fields, empty for all
429          * @param array $condition Array of fields for condition
430          * @param array $params    Array of several parameters
431          *
432          * @return boolean|object
433          * @throws \Exception
434          */
435         public static function select(array $selected = [], array $condition = [], $params = [])
436         {
437                 $uid = 0;
438                 $usermode = false;
439
440                 if (isset($params['uid'])) {
441                         $uid = $params['uid'];
442                         $usermode = true;
443                 }
444
445                 $fields = self::fieldlist($usermode);
446
447                 $select_fields = self::constructSelectFields($fields, $selected);
448
449                 $condition_string = DBA::buildCondition($condition);
450
451                 $condition_string = self::addTablesToFields($condition_string, $fields);
452
453                 if ($usermode) {
454                         $condition_string = $condition_string . ' AND ' . self::condition(false);
455                 }
456
457                 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
458
459                 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
460
461                 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
462
463                 return DBA::p($sql, $condition);
464         }
465
466         /**
467          * Select rows from the starting post in the item table
468          *
469          * @param integer $uid       User ID
470          * @param array   $selected
471          * @param array   $condition Array of fields for condition
472          * @param array   $params    Array of several parameters
473          *
474          * @return boolean|object
475          * @throws \Exception
476          */
477         public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
478         {
479                 $params['uid'] = $uid;
480
481                 if (empty($selected)) {
482                         $selected = self::DISPLAY_FIELDLIST;
483                 }
484
485                 return self::selectThread($selected, $condition, $params);
486         }
487
488         /**
489          * Retrieve a single record from the starting post in the item table and returns it in an associative array
490          *
491          * @param integer $uid User ID
492          * @param array   $selected
493          * @param array   $condition
494          * @param array   $params
495          * @return bool|array
496          * @throws \Exception
497          * @see   DBA::select
498          */
499         public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
500         {
501                 $params['uid'] = $uid;
502
503                 if (empty($selected)) {
504                         $selected = self::DISPLAY_FIELDLIST;
505                 }
506
507                 return self::selectFirstThread($selected, $condition, $params);
508         }
509
510         /**
511          * Retrieve a single record from the starting post in the item table and returns it in an associative array
512          *
513          * @param array $fields
514          * @param array $condition
515          * @param array $params
516          * @return bool|array
517          * @throws \Exception
518          * @see   DBA::select
519          */
520         public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
521         {
522                 $params['limit'] = 1;
523                 $result = self::selectThread($fields, $condition, $params);
524
525                 if (is_bool($result)) {
526                         return $result;
527                 } else {
528                         $row = self::fetch($result);
529                         DBA::close($result);
530                         return $row;
531                 }
532         }
533
534         /**
535          * Select rows from the starting post in the item table
536          *
537          * @param array $selected  Array of selected fields, empty for all
538          * @param array $condition Array of fields for condition
539          * @param array $params    Array of several parameters
540          *
541          * @return boolean|object
542          * @throws \Exception
543          */
544         public static function selectThread(array $selected = [], array $condition = [], $params = [])
545         {
546                 $uid = 0;
547                 $usermode = false;
548
549                 if (isset($params['uid'])) {
550                         $uid = $params['uid'];
551                         $usermode = true;
552                 }
553
554                 $fields = self::fieldlist($usermode);
555
556                 $fields['thread'] = ['mention', 'ignored', 'iid'];
557
558                 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
559                         'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
560                         'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
561                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
562
563                 $select_fields = self::constructSelectFields($fields, $selected);
564
565                 $condition_string = DBA::buildCondition($condition);
566
567                 $condition_string = self::addTablesToFields($condition_string, $threadfields);
568                 $condition_string = self::addTablesToFields($condition_string, $fields);
569
570                 if ($usermode) {
571                         $condition_string = $condition_string . ' AND ' . self::condition(true);
572                 }
573
574                 $param_string = DBA::buildParameter($params);
575                 $param_string = self::addTablesToFields($param_string, $threadfields);
576                 $param_string = self::addTablesToFields($param_string, $fields);
577
578                 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
579
580                 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
581
582                 return DBA::p($sql, $condition);
583         }
584
585         /**
586          * Returns a list of fields that are associated with the item table
587          *
588          * @param $usermode
589          * @return array field list
590          */
591         private static function fieldlist($usermode)
592         {
593                 $fields = [];
594
595                 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
596                         'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid', 'causer-id',
597                         'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
598                         'created', 'edited', 'commented', 'received', 'changed', 'psid',
599                         'resource-id', 'event-id', 'post-type', 'file',
600                         'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
601                         'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
602                         'id' => 'item_id', 'network', 'icid', 'event-id',
603                         'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
604                         'network' => 'internal-network', 'psid' => 'internal-psid'];
605
606                 if ($usermode) {
607                         $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
608                 }
609
610                 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
611
612                 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
613
614                 $fields['verb'] = ['name' => 'internal-verb'];
615
616                 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
617
618                 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
619                         'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
620
621                 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
622                         'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
623
624                 $fields['causer'] = ['url' => 'causer-link', 'name' => 'causer-name', 'addr' => 'causer-addr',
625                         'thumb' => 'causer-avatar', 'nick' => 'causer-nick', 'network' => 'causer-network',
626                         'contact-type' => 'causer-contact-type'];
627
628                 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
629                         'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
630                         'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
631
632                 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
633
634                 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
635                         'network' => 'parent-author-network'];
636
637                 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
638                         'start' => 'event-start','finish' => 'event-finish',
639                         'summary' => 'event-summary','desc' => 'event-desc',
640                         'location' => 'event-location', 'type' => 'event-type',
641                         'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
642                         'ignore' => 'event-ignore'];
643
644                 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
645
646                 return $fields;
647         }
648
649         /**
650          * Returns SQL condition for the "select" functions
651          *
652          * @param boolean $thread_mode Called for the items (false) or for the threads (true)
653          *
654          * @return string SQL condition
655          */
656         private static function condition($thread_mode)
657         {
658                 if ($thread_mode) {
659                         $master_table = "`thread`";
660                 } else {
661                         $master_table = "`item`";
662                 }
663                 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
664                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
665                         AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
666                         AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
667                         AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
668                         AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
669                         GRAVITY_PARENT, GRAVITY_PARENT);
670         }
671
672         /**
673          * Returns all needed "JOIN" commands for the "select" functions
674          *
675          * @param integer $uid          User ID
676          * @param string  $sql_commands The parts of the built SQL commands in the "select" functions
677          * @param boolean $thread_mode  Called for the items (false) or for the threads (true)
678          *
679          * @param         $user_mode
680          * @return string The SQL joins for the "select" functions
681          */
682         private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
683         {
684                 if ($thread_mode) {
685                         $master_table = "`thread`";
686                         $master_table_key = "`thread`.`iid`";
687                         $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
688                 } else {
689                         $master_table = "`item`";
690                         $master_table_key = "`item`.`id`";
691                         $joins = '';
692                 }
693
694                 if ($user_mode) {
695                         $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
696                                 AND NOT `contact`.`blocked`
697                                 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
698                                 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
699                                 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
700                                 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
701                                 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
702                                 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
703                                 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
704                                 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
705                 } else {
706                         if (strpos($sql_commands, "`contact`.") !== false) {
707                                 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
708                         }
709                         if (strpos($sql_commands, "`author`.") !== false) {
710                                 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
711                         }
712                         if (strpos($sql_commands, "`owner`.") !== false) {
713                                 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
714                         }
715                 }
716                 if (strpos($sql_commands, "`causer`.") !== false) {
717                         $joins .= " LEFT JOIN `contact` AS `causer` ON `causer`.`id` = `item`.`causer-id`";
718                 }
719
720                 if (strpos($sql_commands, "`group_member`.") !== false) {
721                         $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
722                 }
723
724                 if (strpos($sql_commands, "`user`.") !== false) {
725                         $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
726                 }
727
728                 if (strpos($sql_commands, "`event`.") !== false) {
729                         $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
730                 }
731
732                 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
733                         $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
734                 }
735
736                 if (strpos($sql_commands, "`item-content`.") !== false) {
737                         $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
738                 }
739
740                 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
741                         $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
742                 }
743
744                 if (strpos($sql_commands, "`verb`.") !== false) {
745                         $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
746                 }
747
748                 if (strpos($sql_commands, "`permissionset`.") !== false) {
749                         $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
750                 }
751
752                 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
753                         $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
754
755                         if (strpos($sql_commands, "`parent-item-author`.") !== false) {
756                                 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
757                         }
758                 }
759
760                 return $joins;
761         }
762
763         /**
764          * Add the field list for the "select" functions
765          *
766          * @param array $fields The field definition array
767          * @param array $selected The array with the selected fields from the "select" functions
768          *
769          * @return string The field list
770          */
771         private static function constructSelectFields(array $fields, array $selected)
772         {
773                 if (!empty($selected)) {
774                         $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
775                 }
776
777                 if (in_array('verb', $selected)) {
778                         $selected = array_merge($selected, ['internal-verb']);
779                 }
780
781                 if (in_array('ignored', $selected)) {
782                         $selected[] = 'internal-user-ignored';
783                 }
784
785                 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
786
787                 $selection = [];
788                 foreach ($fields as $table => $table_fields) {
789                         foreach ($table_fields as $field => $select) {
790                                 if (empty($selected) || in_array($select, $selected)) {
791                                         if (is_int($field)) {
792                                                 $selection[] = "`" . $table . "`.`" . $select . "`";
793                                         } else {
794                                                 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
795                                         }
796                                 }
797                         }
798                 }
799                 return implode(", ", $selection);
800         }
801
802         /**
803          * add table definition to fields in an SQL query
804          *
805          * @param string $query SQL query
806          * @param array $fields The field definition array
807          *
808          * @return string the changed SQL query
809          */
810         private static function addTablesToFields($query, $fields)
811         {
812                 foreach ($fields as $table => $table_fields) {
813                         foreach ($table_fields as $alias => $field) {
814                                 if (is_int($alias)) {
815                                         $replace_field = $field;
816                                 } else {
817                                         $replace_field = $alias;
818                                 }
819
820                                 $search = "/([^\.])`" . $field . "`/i";
821                                 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
822                                 $query = preg_replace($search, $replace, $query);
823                         }
824                 }
825                 return $query;
826         }
827
828         /**
829          * Update existing item entries
830          *
831          * @param array $fields    The fields that are to be changed
832          * @param array $condition The condition for finding the item entries
833          *
834          * In the future we may have to change permissions as well.
835          * Then we had to add the user id as third parameter.
836          *
837          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
838          *
839          * @return integer|boolean number of affected rows - or "false" if there was an error
840          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
841          */
842         public static function update(array $fields, array $condition)
843         {
844                 if (empty($condition) || empty($fields)) {
845                         return false;
846                 }
847
848                 $data_fields = $fields;
849
850                 // To ensure the data integrity we do it in an transaction
851                 DBA::transaction();
852
853                 // We cannot simply expand the condition to check for origin entries
854                 // The condition needn't to be a simple array but could be a complex condition.
855                 // And we have to execute this query before the update to ensure to fetch the same data.
856                 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
857
858                 $content_fields = [];
859                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
860                         if (isset($fields[$field])) {
861                                 $content_fields[$field] = $fields[$field];
862                                 if (in_array($field, self::CONTENT_FIELDLIST)) {
863                                         unset($fields[$field]);
864                                 } else {
865                                         $fields[$field] = null;
866                                 }
867                         }
868                 }
869
870                 $delivery_data = Post\DeliveryData::extractFields($fields);
871
872                 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
873                 foreach ($clear_fields as $field) {
874                         if (array_key_exists($field, $fields)) {
875                                 $fields[$field] = null;
876                         }
877                 }
878
879                 if (array_key_exists('file', $fields)) {
880                         $files = $fields['file'];
881                         $fields['file'] = null;
882                 } else {
883                         $files = null;
884                 }
885
886                 if (!empty($content_fields['verb'])) {
887                         $fields['vid'] = Verb::getID($content_fields['verb']);
888                 }
889
890                 if (!empty($fields)) {
891                         $success = DBA::update('item', $fields, $condition);
892
893                         if (!$success) {
894                                 DBA::close($items);
895                                 DBA::rollback();
896                                 return false;
897                         }
898                 }
899
900                 // When there is no content for the "old" item table, this will count the fetched items
901                 $rows = DBA::affectedRows();
902
903                 $notify_items = [];
904
905                 while ($item = DBA::fetch($items)) {
906                         Post\User::update($item['uri-id'], $item['uid'], $data_fields);
907
908                         if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
909                                 if (!empty($content_fields['body'])) {
910                                         $content_fields['raw-body'] = trim($content_fields['raw-body'] ?? $content_fields['body']);
911                 
912                                         // Remove all media attachments from the body and store them in the post-media table
913                                         $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
914                                         $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
915                                 }
916                 
917                                 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
918
919                                 if (empty($item['icid'])) {
920                                         $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
921                                         if (DBA::isResult($item_content)) {
922                                                 $item_fields = ['icid' => $item_content['id']];
923                                                 DBA::update('item', $item_fields, ['id' => $item['id']]);
924                                         }
925                                 }
926                         }
927
928                         if (!is_null($files)) {
929                                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
930                                 if (!empty($item['file'])) {
931                                         DBA::update('item', ['file' => ''], ['id' => $item['id']]);
932                                 }
933                         }
934
935                         if (!empty($fields['attach'])) {
936                                 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
937                         }
938
939                         Post\DeliveryData::update($item['uri-id'], $delivery_data);
940
941                         self::updateThread($item['id']);
942
943                         // We only need to notfiy others when it is an original entry from us.
944                         // Only call the notifier when the item has some content relevant change.
945                         if ($item['origin'] && in_array('edited', array_keys($fields))) {
946                                 $notify_items[] = $item['id'];
947                         }
948                 }
949
950                 DBA::close($items);
951                 DBA::commit();
952
953                 foreach ($notify_items as $notify_item) {
954                         Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
955                 }
956
957                 return $rows;
958         }
959
960         /**
961          * Delete an item and notify others about it - if it was ours
962          *
963          * @param array   $condition The condition for finding the item entries
964          * @param integer $priority  Priority for the notification
965          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
966          */
967         public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
968         {
969                 $items = Post::select(['id'], $condition);
970                 while ($item = Post::fetch($items)) {
971                         self::markForDeletionById($item['id'], $priority);
972                 }
973                 DBA::close($items);
974         }
975
976         /**
977          * Delete an item for an user and notify others about it - if it was ours
978          *
979          * @param array   $condition The condition for finding the item entries
980          * @param integer $uid       User who wants to delete this item
981          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982          */
983         public static function deleteForUser($condition, $uid)
984         {
985                 if ($uid == 0) {
986                         return;
987                 }
988
989                 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
990                 while ($item = Post::fetch($items)) {
991                         Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
992
993                         // "Deleting" global items just means hiding them
994                         if ($item['uid'] == 0) {
995                                 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
996                         } elseif ($item['uid'] == $uid) {
997                                 self::markForDeletionById($item['id'], PRIORITY_HIGH);
998                         } else {
999                                 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1000                         }
1001                 }
1002                 DBA::close($items);
1003         }
1004
1005         /**
1006          * Mark an item for deletion, delete related data and notify others about it - if it was ours
1007          *
1008          * @param integer $item_id
1009          * @param integer $priority Priority for the notification
1010          *
1011          * @return boolean success
1012          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013          */
1014         public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1015         {
1016                 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1017                 // locate item to be deleted
1018                 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1019                         'deleted', 'file', 'resource-id', 'event-id',
1020                         'verb', 'object-type', 'object', 'target', 'contact-id',
1021                         'icid', 'psid', 'gravity'];
1022                 $item = Post::selectFirst($fields, ['id' => $item_id]);
1023                 if (!DBA::isResult($item)) {
1024                         Logger::info('Item not found.', ['id' => $item_id]);
1025                         return false;
1026                 }
1027
1028                 if ($item['deleted']) {
1029                         Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1030                         return false;
1031                 }
1032
1033                 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
1034                 if (!DBA::isResult($parent)) {
1035                         $parent = ['origin' => false];
1036                 }
1037
1038                 // clean up categories and tags so they don't end up as orphans
1039
1040                 $matches = [];
1041                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1042
1043                 if ($cnt) {
1044                         foreach ($matches as $mtch) {
1045                                 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1046                         }
1047                 }
1048
1049                 $matches = [];
1050
1051                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1052
1053                 if ($cnt) {
1054                         foreach ($matches as $mtch) {
1055                                 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1056                         }
1057                 }
1058
1059                 /*
1060                  * If item is a link to a photo resource, nuke all the associated photos
1061                  * (visitors will not have photo resources)
1062                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1063                  * generate a resource-id and therefore aren't intimately linked to the item.
1064                  */
1065                 /// @TODO: this should first check if photo is used elsewhere
1066                 if (strlen($item['resource-id'])) {
1067                         Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1068                 }
1069
1070                 // If item is a link to an event, delete the event.
1071                 if (intval($item['event-id'])) {
1072                         Event::delete($item['event-id']);
1073                 }
1074
1075                 // If item has attachments, drop them
1076                 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
1077                 foreach($attachments as $attachment) {
1078                         if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
1079                                 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1080                         }
1081                 }
1082
1083                 // Set the item to "deleted"
1084                 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1085                 DBA::update('item', $item_fields, ['id' => $item['id']]);
1086
1087                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
1088                 self::deleteThread($item['id'], $item['parent-uri']);
1089
1090                 if (!Post::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1091                         self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1092                 }
1093
1094                 Post\DeliveryData::delete($item['uri-id']);
1095
1096                 // When the permission set will be used in photo and events as well,
1097                 // this query here needs to be extended.
1098                 // @todo Currently deactivated. We need the permission set in the deletion process.
1099                 // This is a reminder to add the removal somewhere else.
1100                 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1101                 //      DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1102                 //}
1103
1104                 // If it's the parent of a comment thread, kill all the kids
1105                 if ($item['gravity'] == GRAVITY_PARENT) {
1106                         self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1107                 }
1108
1109                 // Is it our comment and/or our thread?
1110                 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
1111                         // When we delete the original post we will delete all existing copies on the server as well
1112                         self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1113
1114                         // send the notification upstream/downstream
1115                         if ($priority) {
1116                                 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1117                         }
1118                 } elseif ($item['uid'] != 0) {
1119                         Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
1120
1121                         // When we delete just our local user copy of an item, we have to set a marker to hide it
1122                         $global_item = Post::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1123                         if (DBA::isResult($global_item)) {
1124                                 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1125                         }
1126                 }
1127
1128                 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1129
1130                 return true;
1131         }
1132
1133
1134         private static function guid($item, $notify)
1135         {
1136                 if (!empty($item['guid'])) {
1137                         return Strings::escapeTags(trim($item['guid']));
1138                 }
1139
1140                 if ($notify) {
1141                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1142                         // We add the hash of our own host because our host is the original creator of the post.
1143                         $prefix_host = DI::baseUrl()->getHostname();
1144                 } else {
1145                         $prefix_host = '';
1146
1147                         // We are only storing the post so we create a GUID from the original hostname.
1148                         if (!empty($item['author-link'])) {
1149                                 $parsed = parse_url($item['author-link']);
1150                                 if (!empty($parsed['host'])) {
1151                                         $prefix_host = $parsed['host'];
1152                                 }
1153                         }
1154
1155                         if (empty($prefix_host) && !empty($item['plink'])) {
1156                                 $parsed = parse_url($item['plink']);
1157                                 if (!empty($parsed['host'])) {
1158                                         $prefix_host = $parsed['host'];
1159                                 }
1160                         }
1161
1162                         if (empty($prefix_host) && !empty($item['uri'])) {
1163                                 $parsed = parse_url($item['uri']);
1164                                 if (!empty($parsed['host'])) {
1165                                         $prefix_host = $parsed['host'];
1166                                 }
1167                         }
1168
1169                         // Is it in the format data@host.tld? - Used for mail contacts
1170                         if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1171                                 $mailparts = explode('@', $item['author-link']);
1172                                 $prefix_host = array_pop($mailparts);
1173                         }
1174                 }
1175
1176                 if (!empty($item['plink'])) {
1177                         $guid = self::guidFromUri($item['plink'], $prefix_host);
1178                 } elseif (!empty($item['uri'])) {
1179                         $guid = self::guidFromUri($item['uri'], $prefix_host);
1180                 } else {
1181                         $guid = System::createUUID(hash('crc32', $prefix_host));
1182                 }
1183
1184                 return $guid;
1185         }
1186
1187         private static function contactId($item)
1188         {
1189                 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1190                         return $item['contact-id'];
1191                 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1192                         return $item['contact-id'];
1193                 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1194                         return $item['author-id'];
1195                 } elseif (!empty($item['contact-id'])) {
1196                         return $item['contact-id'];
1197                 } else {
1198                         $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1199                         if (!empty($contact_id)) {
1200                                 return $contact_id;
1201                         }
1202                 }
1203                 return $item['author-id'];
1204         }
1205
1206         // This function will finally cover most of the preparation functionality in mod/item.php
1207         public static function prepare(&$item)
1208         {
1209                 /*
1210                  * @TODO: Unused code triggering inspection errors
1211                  *
1212                 $data = BBCode::getAttachmentData($item['body']);
1213                 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1214                         && ($posttype != self::PT_PERSONAL_NOTE)) {
1215                         $posttype = self::PT_PAGE;
1216                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
1217                 }
1218                  */
1219         }
1220
1221         /**
1222          * Write an item array into a spool file to be inserted later.
1223          * This command is called whenever there are issues storing an item.
1224          *
1225          * @param array $item The item fields that are to be inserted
1226          * @throws \Exception
1227          */
1228         private static function spool($orig_item)
1229         {
1230                 // Now we store the data in the spool directory
1231                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1232                 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1233
1234                 $spoolpath = get_spoolpath();
1235                 if ($spoolpath != "") {
1236                         $spool = $spoolpath . '/' . $file;
1237
1238                         file_put_contents($spool, json_encode($orig_item));
1239                         Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1240                 }
1241         }
1242
1243         /**
1244          * Check if the item array is a duplicate
1245          *
1246          * @param array $item
1247          * @return boolean is it a duplicate?
1248          */
1249         private static function isDuplicate(array $item)
1250         {
1251                 // Checking if there is already an item with the same guid
1252                 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1253                 if (Post::exists($condition)) {
1254                         Logger::notice('Found already existing item', [
1255                                 'guid' => $item['guid'],
1256                                 'uid' => $item['uid'],
1257                                 'network' => $item['network']
1258                         ]);
1259                         return true;
1260                 }
1261
1262                 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1263                         $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1264                 if (Post::exists($condition)) {
1265                         Logger::notice('duplicated item with the same uri found.', $item);
1266                         return true;
1267                 }
1268
1269                 // On Friendica and Diaspora the GUID is unique
1270                 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1271                         $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1272                         if (Post::exists($condition)) {
1273                                 Logger::notice('duplicated item with the same guid found.', $item);
1274                                 return true;
1275                         }
1276                 } elseif ($item['network'] == Protocol::OSTATUS) {
1277                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
1278                         $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1279                                         $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1280                         if (Post::exists($condition)) {
1281                                 Logger::notice('duplicated item with the same body found.', $item);
1282                                 return true;
1283                         }
1284                 }
1285
1286                 /*
1287                  * Check for already added items.
1288                  * There is a timing issue here that sometimes creates double postings.
1289                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1290                  */
1291                 if (($item['uid'] == 0) && Post::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1292                         Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
1293                         return true;
1294                 }
1295
1296                 return false;
1297         }
1298
1299         /**
1300          * Check if the item array is valid
1301          *
1302          * @param array $item
1303          * @return boolean item is valid
1304          */
1305         public static function isValid(array $item)
1306         {
1307                 // When there is no content then we don't post it
1308                 if ($item['body'] . $item['title'] == '') {
1309                         Logger::notice('No body, no title.');
1310                         return false;
1311                 }
1312
1313                 if (!empty($item['uid'])) {
1314                         $owner = User::getOwnerDataById($item['uid'], false);
1315                         if (!$owner) {
1316                                 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
1317                                 return false;
1318                         }
1319
1320                         if ($owner['account_expired'] || $owner['account_removed']) {
1321                                 Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
1322                                 return false;
1323                         }
1324                 }
1325
1326                 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
1327                         Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1328                         return false;
1329                 }
1330
1331                 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1332                         Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1333                         return false;
1334                 }
1335
1336                 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
1337                         Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1338                         return false;
1339                 }
1340
1341                 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1342                         Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1343                         return false;
1344                 }
1345
1346                 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
1347                         return false;
1348                 }
1349
1350                 if ($item['verb'] == Activity::FOLLOW) {
1351                         if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
1352                                 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1353                                 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
1354                                 return false;
1355                         }
1356
1357                         $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1358                                 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1359                         if (Post::exists($condition)) {
1360                                 // It happens that we receive multiple follow requests by the same author - we only store one.
1361                                 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
1362                                 return false;
1363                         }
1364                 }
1365
1366                 return true;
1367         }
1368
1369         /**
1370          * Check if the item array is too old
1371          *
1372          * @param array $item
1373          * @return boolean item is too old
1374          */
1375         public static function isTooOld(array $item)
1376         {
1377                 // check for create date and expire time
1378                 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1379
1380                 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
1381                 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1382                         $expire_interval = $user['expire'];
1383                 }
1384
1385                 if (($expire_interval > 0) && !empty($item['created'])) {
1386                         $expire_date = time() - ($expire_interval * 86400);
1387                         $created_date = strtotime($item['created']);
1388                         if ($created_date < $expire_date) {
1389                                 Logger::notice('Item created before expiration interval.', [
1390                                         'created' => date('c', $created_date),
1391                                         'expired' => date('c', $expire_date),
1392                                         '$item' => $item
1393                                 ]);
1394                                 return true;
1395                         }
1396                 }
1397
1398                 return false;
1399         }
1400
1401         /**
1402          * Return the id of the given item array if it has been stored before
1403          *
1404          * @param array $item
1405          * @return integer item id
1406          */
1407         private static function getDuplicateID(array $item)
1408         {
1409                 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1410                         $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1411                                 trim($item['uri']), $item['uid'],
1412                                 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1413                         $existing = Post::selectFirst(['id', 'network'], $condition);
1414                         if (DBA::isResult($existing)) {
1415                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1416                                 if ($item['uid'] != 0) {
1417                                         Logger::notice('Item already existed for user', [
1418                                                 'uri' => $item['uri'],
1419                                                 'uid' => $item['uid'],
1420                                                 'network' => $item['network'],
1421                                                 'existing_id' => $existing["id"],
1422                                                 'existing_network' => $existing["network"]
1423                                         ]);
1424                                 }
1425
1426                                 return $existing["id"];
1427                         }
1428                 }
1429                 return 0;
1430         }
1431
1432         /**
1433          * Fetch top-level parent data for the given item array
1434          *
1435          * @param array $item
1436          * @return array item array with parent data
1437          * @throws \Exception
1438          */
1439         private static function getTopLevelParent(array $item)
1440         {
1441                 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
1442                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1443                         'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1444                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid']];
1445                 $params = ['order' => ['id' => false]];
1446                 $parent = Post::selectFirst($fields, $condition, $params);
1447
1448                 if (!DBA::isResult($parent)) {
1449                         Logger::notice('item parent was not found - ignoring item', ['thr-parent' => $item['thr-parent'], 'uid' => $item['uid']]);
1450                         return [];
1451                 }
1452
1453                 if ($parent['uri'] == $parent['parent-uri']) {
1454                         return $parent;
1455                 }
1456
1457                 $condition = ['uri' => $parent['parent-uri'],
1458                         'parent-uri' => $parent['parent-uri'],
1459                         'uid' => $parent['uid']];
1460                 $params = ['order' => ['id' => false]];
1461                 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
1462                 if (!DBA::isResult($toplevel_parent)) {
1463                         Logger::notice('item top level parent was not found - ignoring item', ['parent-uri' => $parent['parent-uri'], 'uid' => $parent['uid']]);
1464                         return [];
1465                 }
1466
1467                 return $toplevel_parent;
1468         }
1469
1470         /**
1471          * Get the gravity for the given item array
1472          *
1473          * @param array $item
1474          * @return integer gravity
1475          */
1476         private static function getGravity(array $item)
1477         {
1478                 $activity = DI::activity();
1479
1480                 if (isset($item['gravity'])) {
1481                         return intval($item['gravity']);
1482                 } elseif ($item['parent-uri'] === $item['uri']) {
1483                         return GRAVITY_PARENT;
1484                 } elseif ($activity->match($item['verb'], Activity::POST)) {
1485                         return GRAVITY_COMMENT;
1486                 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1487                         return GRAVITY_ACTIVITY;
1488                 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
1489                         return GRAVITY_ACTIVITY;
1490                 }
1491                 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
1492                 return GRAVITY_UNKNOWN;   // Should not happen
1493         }
1494
1495         public static function insert($item, $notify = false, $dontcache = false)
1496         {
1497                 $structure = self::getItemFields();
1498
1499                 $orig_item = $item;
1500
1501                 $priority = PRIORITY_HIGH;
1502
1503                 // If it is a posting where users should get notifications, then define it as wall posting
1504                 if ($notify) {
1505                         $item['wall'] = 1;
1506                         $item['origin'] = 1;
1507                         $item['network'] = Protocol::DFRN;
1508                         $item['protocol'] = Conversation::PARCEL_DIRECT;
1509                         $item['direction'] = Conversation::PUSH;
1510
1511                         if (in_array($notify, PRIORITIES)) {
1512                                 $priority = $notify;
1513                         }
1514                 } else {
1515                         $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1516                 }
1517
1518                 $uid = intval($item['uid']);
1519
1520                 $item['guid'] = self::guid($item, $notify);
1521                 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
1522
1523                 // Store URI data
1524                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1525
1526                 // Backward compatibility: parent-uri used to be the direct parent uri.
1527                 // If it is provided without a thr-parent, it probably is the old behavior.
1528                 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
1529                 $item['parent-uri'] = $item['thr-parent'];
1530
1531                 // Store conversation data
1532                 $item = Conversation::insert($item);
1533
1534                 /*
1535                  * Do we already have this item?
1536                  * We have to check several networks since Friendica posts could be repeated
1537                  * via OStatus (maybe Diasporsa as well)
1538                  */
1539                 $duplicate = self::getDuplicateID($item);
1540                 if ($duplicate) {
1541                         return $duplicate;
1542                 }
1543
1544                 // Additional duplicate checks
1545                 /// @todo Check why the first duplication check returns the item number and the second a 0
1546                 if (self::isDuplicate($item)) {
1547                         return 0;
1548                 }
1549
1550                 $item['wall']          = intval($item['wall'] ?? 0);
1551                 $item['extid']         = trim($item['extid'] ?? '');
1552                 $item['author-name']   = trim($item['author-name'] ?? '');
1553                 $item['author-link']   = trim($item['author-link'] ?? '');
1554                 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1555                 $item['owner-name']    = trim($item['owner-name'] ?? '');
1556                 $item['owner-link']    = trim($item['owner-link'] ?? '');
1557                 $item['owner-avatar']  = trim($item['owner-avatar'] ?? '');
1558                 $item['received']      = (isset($item['received'])  ? DateTimeFormat::utc($item['received'])  : DateTimeFormat::utcNow());
1559                 $item['created']       = (isset($item['created'])   ? DateTimeFormat::utc($item['created'])   : $item['received']);
1560                 $item['edited']        = (isset($item['edited'])    ? DateTimeFormat::utc($item['edited'])    : $item['created']);
1561                 $item['changed']       = (isset($item['changed'])   ? DateTimeFormat::utc($item['changed'])   : $item['created']);
1562                 $item['commented']     = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1563                 $item['title']         = substr(trim($item['title'] ?? ''), 0, 255);
1564                 $item['location']      = trim($item['location'] ?? '');
1565                 $item['coord']         = trim($item['coord'] ?? '');
1566                 $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
1567                 $item['deleted']       = 0;
1568                 $item['post-type']     = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1569                 $item['verb']          = trim($item['verb'] ?? '');
1570                 $item['object-type']   = trim($item['object-type'] ?? '');
1571                 $item['object']        = trim($item['object'] ?? '');
1572                 $item['target-type']   = trim($item['target-type'] ?? '');
1573                 $item['target']        = trim($item['target'] ?? '');
1574                 $item['plink']         = substr(trim($item['plink'] ?? ''), 0, 255);
1575                 $item['allow_cid']     = trim($item['allow_cid'] ?? '');
1576                 $item['allow_gid']     = trim($item['allow_gid'] ?? '');
1577                 $item['deny_cid']      = trim($item['deny_cid'] ?? '');
1578                 $item['deny_gid']      = trim($item['deny_gid'] ?? '');
1579                 $item['private']       = intval($item['private'] ?? self::PUBLIC);
1580                 $item['body']          = trim($item['body'] ?? '');
1581                 $item['raw-body']      = trim($item['raw-body'] ?? $item['body']);
1582                 $item['app']           = trim($item['app'] ?? '');
1583                 $item['origin']        = intval($item['origin'] ?? 0);
1584                 $item['postopts']      = trim($item['postopts'] ?? '');
1585                 $item['resource-id']   = trim($item['resource-id'] ?? '');
1586                 $item['event-id']      = intval($item['event-id'] ?? 0);
1587                 $item['inform']        = trim($item['inform'] ?? '');
1588                 $item['file']          = trim($item['file'] ?? '');
1589
1590                 // Items cannot be stored before they happen ...
1591                 if ($item['created'] > DateTimeFormat::utcNow()) {
1592                         $item['created'] = DateTimeFormat::utcNow();
1593                 }
1594
1595                 // We haven't invented time travel by now.
1596                 if ($item['edited'] > DateTimeFormat::utcNow()) {
1597                         $item['edited'] = DateTimeFormat::utcNow();
1598                 }
1599
1600                 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1601
1602                 $item['gravity'] = self::getGravity($item);
1603
1604                 $item['language'] = self::getLanguage($item);
1605
1606                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1607                         'photo' => $item['author-avatar'], 'network' => $item['network']];
1608                 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1609
1610                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1611                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
1612                 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1613
1614                 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1615                 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1616                         $item['post-type'] = self::PT_FOLLOWER;
1617                 }
1618
1619                 // Ensure that there is an avatar cache
1620                 Contact::checkAvatarCache($item['author-id']);
1621                 Contact::checkAvatarCache($item['owner-id']);
1622
1623                 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1624                 $item["contact-id"] = self::contactId($item);
1625
1626                 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1627                         self::isTooOld($item)) {
1628                         Logger::info('Item is too old', ['item' => $item]);
1629                         return 0;
1630                 }
1631
1632                 if (!self::isValid($item)) {
1633                         return 0;
1634                 }
1635
1636                 if ($item['gravity'] !== GRAVITY_PARENT) {
1637                         $toplevel_parent = self::getTopLevelParent($item);
1638                         if (empty($toplevel_parent)) {
1639                                 return 0;
1640                         }
1641
1642                         // If the thread originated from this node, we check the permission against the thread starter
1643                         $condition = ['uri' => $toplevel_parent['uri'], 'wall' => true];
1644                         $localTopLevelParent = Post::selectFirst(['uid'], $condition);
1645                         if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
1646                                 return 0;
1647                         }
1648
1649                         $parent_id          = $toplevel_parent['id'];
1650                         $item['parent-uri'] = $toplevel_parent['uri'];
1651                         $item['deleted']    = $toplevel_parent['deleted'];
1652                         $item['allow_cid']  = $toplevel_parent['allow_cid'];
1653                         $item['allow_gid']  = $toplevel_parent['allow_gid'];
1654                         $item['deny_cid']   = $toplevel_parent['deny_cid'];
1655                         $item['deny_gid']   = $toplevel_parent['deny_gid'];
1656                         $parent_origin      = $toplevel_parent['origin'];
1657
1658                         // Don't federate received participation messages
1659                         if ($item['verb'] != Activity::FOLLOW) {
1660                                 $item['wall'] = $toplevel_parent['wall'];
1661                         } else {
1662                                 $item['wall'] = false;
1663                         }
1664
1665                         /*
1666                          * If the parent is private, force privacy for the entire conversation
1667                          * This differs from the above settings as it subtly allows comments from
1668                          * email correspondents to be private even if the overall thread is not.
1669                          */
1670                         if ($toplevel_parent['private']) {
1671                                 $item['private'] = $toplevel_parent['private'];
1672                         }
1673
1674                         /*
1675                          * Edge case. We host a public forum that was originally posted to privately.
1676                          * The original author commented, but as this is a comment, the permissions
1677                          * weren't fixed up so it will still show the comment as private unless we fix it here.
1678                          */
1679                         if ((intval($toplevel_parent['forum_mode']) == 1) && ($toplevel_parent['private'] != self::PUBLIC)) {
1680                                 $item['private'] = self::PUBLIC;
1681                         }
1682
1683                         // If its a post that originated here then tag the thread as "mention"
1684                         if ($item['origin'] && $item['uid']) {
1685                                 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1686                                 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'uid' => $item['uid']]);
1687                         }
1688
1689                         // Update the contact relations
1690                         Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1691
1692                         unset($item['parent_origin']);
1693                 } else {
1694                         $parent_id = 0;
1695                         $parent_origin = $item['origin'];
1696                 }
1697
1698                 // We don't store the causer link, only the id
1699                 unset($item['causer-link']);
1700
1701                 // We don't store these fields anymore in the item table
1702                 unset($item['author-link']);
1703                 unset($item['author-name']);
1704                 unset($item['author-avatar']);
1705                 unset($item['author-network']);
1706
1707                 unset($item['owner-link']);
1708                 unset($item['owner-name']);
1709                 unset($item['owner-avatar']);
1710
1711                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1712                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1713
1714                 // Is this item available in the global items (with uid=0)?
1715                 if ($item["uid"] == 0) {
1716                         $item["global"] = true;
1717
1718                         // Set the global flag on all items if this was a global item entry
1719                         DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1720                 } else {
1721                         $item["global"] = Post::exists(['uid' => 0, 'uri' => $item["uri"]]);
1722                 }
1723
1724                 // ACL settings
1725                 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
1726                         $item["private"] = self::PRIVATE;
1727                 }
1728
1729                 if ($notify) {
1730                         $item['edit'] = false;
1731                         $item['parent'] = $parent_id;
1732                         Hook::callAll('post_local', $item);
1733                         unset($item['edit']);
1734                 } else {
1735                         Hook::callAll('post_remote', $item);
1736                 }
1737
1738                 // Set after the insert because top-level posts are self-referencing
1739                 unset($item['parent']);
1740
1741                 if (!empty($item['cancel'])) {
1742                         Logger::log('post cancelled by addon.');
1743                         return 0;
1744                 }
1745
1746                 if (empty($item['vid']) && !empty($item['verb'])) {
1747                         $item['vid'] = Verb::getID($item['verb']);
1748                 }
1749
1750                 // Creates or assigns the permission set
1751                 $item['psid'] = PermissionSet::getIdFromACL(
1752                         $item['uid'],
1753                         $item['allow_cid'],
1754                         $item['allow_gid'],
1755                         $item['deny_cid'],
1756                         $item['deny_gid']
1757                 );
1758
1759                 unset($item['allow_cid']);
1760                 unset($item['allow_gid']);
1761                 unset($item['deny_cid']);
1762                 unset($item['deny_gid']);
1763
1764                 // This array field is used to trigger some automatic reactions
1765                 // It is mainly used in the "post_local" hook.
1766                 unset($item['api_source']);
1767
1768                 if ($item['verb'] == Activity::ANNOUNCE) {
1769                         self::setOwnerforResharedItem($item);
1770                 }
1771
1772                 // Remove all media attachments from the body and store them in the post-media table
1773                 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1774                 $item['raw-body'] = self::setHashtags($item['raw-body']);
1775
1776                 // Check for hashtags in the body and repair or add hashtag links
1777                 $item['body'] = self::setHashtags($item['body']);
1778
1779                 if (!empty($item['attach'])) {
1780                         Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1781                 }
1782
1783                 // Fill the cache field
1784                 self::putInCache($item);
1785
1786                 if (stristr($item['verb'], Activity::POKE)) {
1787                         $notify_type = Delivery::POKE;
1788                 } else {
1789                         $notify_type = Delivery::POST;
1790                 }
1791
1792                 if (!in_array($item['verb'], self::ACTIVITIES)) {
1793                         $item['icid'] = self::insertContent($item);
1794                         if (empty($item['icid'])) {
1795                                 // This shouldn't happen
1796                                 Logger::warning('No content stored, quitting', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'causer-id' => ($item['causer-id'] ?? 0), 'post-type' => $item['post-type'], 'network' => $item['network']]);
1797                                 return 0;
1798                         }
1799                 }
1800
1801                 $body = $item['body'];
1802                 $verb = $item['verb'];
1803
1804                 // We just remove everything that is content
1805                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1806                         unset($item[$field]);
1807                 }
1808
1809                 unset($item['activity']);
1810
1811                 // Filling item related side tables
1812
1813                 // Diaspora signature
1814                 if (!empty($item['diaspora_signed_text'])) {
1815                         DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1816                 }
1817
1818                 unset($item['diaspora_signed_text']);
1819
1820                 // Attached file links
1821                 if (!empty($item['file'])) {
1822                         Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1823                 }
1824
1825                 unset($item['file']);
1826
1827                 // Delivery relevant data
1828                 $delivery_data = Post\DeliveryData::extractFields($item);
1829                 unset($item['postopts']);
1830                 unset($item['inform']);
1831
1832                 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1833                         Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1834                 }
1835
1836                 // Store tags from the body if this hadn't been handled previously in the protocol classes
1837                 if (!Tag::existsForPost($item['uri-id'])) {
1838                         Tag::storeFromBody($item['uri-id'], $body);
1839                 }
1840
1841                 if (Post\User::insert($item['uri-id'], $item['uid'], $item)) {
1842                         // Remove all fields that aren't part of the item table
1843                         foreach ($item as $field => $value) {
1844                                 if (!in_array($field, $structure['item'])) {
1845                                         unset($item[$field]);
1846                                 }
1847                         }
1848
1849                         $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network']];
1850                         if (DBA::exists('item', $condition)) {
1851                                 Logger::notice('Item is already inserted - aborting', $condition);
1852                                 return 0;
1853                         }
1854
1855                         $result = DBA::insert('item', $item);
1856
1857                         // When the item was successfully stored we fetch the ID of the item.
1858                         $current_post = DBA::lastInsertId();
1859                 } else {
1860                         Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1861                         return 0;
1862                 }
1863
1864                 if (empty($current_post) || !DBA::isResult($result)) {
1865                         // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1866                         Logger::warning('Could not store item. it will be spooled', ['result' => $result, 'id' => $current_post]);
1867                         self::spool($orig_item);
1868                         return 0;
1869                 }
1870
1871                 Logger::notice('created item', ['id' => $current_post, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1872
1873                 if (!$parent_id || ($item['gravity'] === GRAVITY_PARENT)) {
1874                         $parent_id = $current_post;
1875                 }
1876
1877                 // Set parent id
1878                 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1879
1880                 $item['id'] = $current_post;
1881                 $item['parent'] = $parent_id;
1882
1883                 // update the commented timestamp on the parent
1884                 if (DI::config()->get('system', 'like_no_comment')) {
1885                         // Update when it is a comment
1886                         $update_commented = in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1887                 } else {
1888                         // Update when it isn't a follow or tag verb
1889                         $update_commented = !in_array($verb, [Activity::FOLLOW, Activity::TAG]);
1890                 }
1891
1892                 if ($update_commented) {
1893                         DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1894                 } else {
1895                         DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1896                 }
1897
1898                 if ($item['gravity'] === GRAVITY_PARENT) {
1899                         self::addThread($current_post);
1900                 } else {
1901                         self::updateThread($parent_id);
1902                 }
1903
1904                 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1905                 if (self::tagDeliver($item['uid'], $current_post)) {
1906                         // Get the user information for the logging
1907                         $user = User::getById($uid);
1908
1909                         Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1910                         return 0;
1911                 }
1912
1913                 if (!$dontcache) {
1914                         $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1915                         if (DBA::isResult($posted_item)) {
1916                                 if ($notify) {
1917                                         Hook::callAll('post_local_end', $posted_item);
1918                                 } else {
1919                                         Hook::callAll('post_remote_end', $posted_item);
1920                                 }
1921                         } else {
1922                                 Logger::log('new item not found in DB, id ' . $current_post);
1923                         }
1924                 }
1925
1926                 if ($item['gravity'] === GRAVITY_PARENT) {
1927                         self::addShadow($current_post);
1928                 } else {
1929                         self::addShadowPost($current_post);
1930                 }
1931
1932                 self::updateContact($item);
1933
1934                 UserItem::setNotification($current_post);
1935
1936                 check_user_notification($current_post);
1937
1938                 // Distribute items to users who subscribed to their tags
1939                 self::distributeByTags($item);
1940
1941                 // Automatically reshare the item if the "remote_self" option is selected
1942                 self::autoReshare($item);
1943
1944                 $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
1945
1946                 if ($transmit) {
1947                         $transmit_item = Post::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
1948                         // Don't relay participation messages
1949                         if (($transmit_item['verb'] == Activity::FOLLOW) && 
1950                                 (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1951                                 Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
1952                                 $transmit = false;
1953                         }
1954                 }
1955
1956                 if ($transmit) {
1957                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1958                 }
1959
1960                 return $current_post;
1961         }
1962
1963         /**
1964          * Change the owner of a parent item if it had been shared by a forum
1965          *
1966          * (public) forum posts in the new format consist of the regular post by the author
1967          * followed by an announce message sent from the forum account.
1968          * Changing the owner helps in grouping forum posts.
1969          *
1970          * @param array $item
1971          * @return void
1972          */
1973         private static function setOwnerforResharedItem(array $item)
1974         {
1975                 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
1976                         ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1977                 if (!DBA::isResult($parent)) {
1978                         Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1979                         return;
1980                 }
1981
1982                 $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
1983                 if (!DBA::isResult($author)) {
1984                         Logger::error('Author not found', ['id' => $item['author-id']]);
1985                         return;
1986                 }
1987
1988                 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1989                 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
1990                         Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
1991                         return;
1992                 }
1993
1994                 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1995                         if ($parent['post-type'] == self::PT_ANNOUNCEMENT) {
1996                                 Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1997                                 return;
1998                         }
1999
2000                         if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
2001                                 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2002                                 return;
2003                         }
2004                         self::update(['post-type' => self::PT_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
2005                         Logger::info('Set announcement post-type', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2006                         return;
2007                 }
2008
2009                 self::update(['owner-id' => $item['author-id'], 'contact-id' => $cid], ['id' => $parent['id']]);
2010                 Logger::info('Change owner of the parent', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'owner-id' => $item['author-id'], 'contact-id' => $cid]);
2011         }
2012
2013         /**
2014          * Distribute the given item to users who subscribed to their tags
2015          *
2016          * @param array $item     Processed item
2017          */
2018         private static function distributeByTags(array $item)
2019         {
2020                 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
2021                         return;
2022                 }
2023
2024                 $uids = Tag::getUIDListByURIId($item['uri-id']);
2025                 foreach ($uids as $uid) {
2026                         if (Contact::isSharing($item['author-id'], $uid)) {
2027                                 $fields = [];
2028                         } else {
2029                                 $fields = ['post-type' => self::PT_TAG];
2030                         }
2031
2032                         $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
2033                         Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
2034                 }
2035         }
2036
2037         /**
2038          * Insert a new item content entry
2039          *
2040          * @param array $item The item fields that are to be inserted
2041          * @throws \Exception
2042          */
2043         private static function insertContent(array $item)
2044         {
2045                 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2046
2047                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2048                         if (isset($item[$field])) {
2049                                 $fields[$field] = $item[$field];
2050                         }
2051                 }
2052
2053                 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2054                 if (DBA::isResult($item_content)) {
2055                         $icid = $item_content['id'];
2056                         Logger::info('Existing content found', ['icid' => $icid, 'uri' => $item['uri']]);
2057                         return $icid;
2058                 }
2059
2060                 DBA::replace('item-content', $fields);
2061
2062                 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2063                 if (DBA::isResult($item_content)) {
2064                         $icid = $item_content['id'];
2065                         Logger::notice('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
2066                         return $icid;
2067                 }
2068
2069                 // This shouldn't happen.
2070                 Logger::error("Content wasn't inserted", $item);
2071                 return null;
2072         }
2073
2074         /**
2075          * Update existing item content entries
2076          *
2077          * @param array $item      The item fields that are to be changed
2078          * @param array $condition The condition for finding the item content entries
2079          * @throws \Exception
2080          */
2081         private static function updateContent($item, $condition)
2082         {
2083                 // We have to select only the fields from the "item-content" table
2084                 $fields = [];
2085                 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2086                         if (isset($item[$field])) {
2087                                 $fields[$field] = $item[$field];
2088                         }
2089                 }
2090
2091                 if (empty($fields)) {
2092                         return;
2093                 }
2094
2095                 DBA::update('item-content', $fields, $condition, true);
2096                 Logger::info('Updated content', ['condition' => $condition]);
2097         }
2098
2099         /**
2100          * Distributes public items to the receivers
2101          *
2102          * @param integer $itemid      Item ID that should be added
2103          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
2104          * @throws \Exception
2105          */
2106         public static function distribute($itemid, $signed_text = '')
2107         {
2108                 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2109                 $parent = Post::selectFirst(['owner-id'], $condition);
2110                 if (!DBA::isResult($parent)) {
2111                         return;
2112                 }
2113
2114                 // Only distribute public items from native networks
2115                 $condition = ['id' => $itemid, 'uid' => 0,
2116                         'network' => array_merge(Protocol::FEDERATED ,['']),
2117                         'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2118                 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
2119                 if (!DBA::isResult($item)) {
2120                         return;
2121                 }
2122
2123                 $origin = $item['origin'];
2124
2125                 $users = [];
2126
2127                 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2128                 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2129                 if (!DBA::isResult($owner)) {
2130                         return;
2131                 }
2132
2133                 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2134                 $contacts = DBA::select('contact', ['uid'], $condition);
2135                 while ($contact = DBA::fetch($contacts)) {
2136                         if ($contact['uid'] == 0) {
2137                                 continue;
2138                         }
2139
2140                         $users[$contact['uid']] = $contact['uid'];
2141                 }
2142                 DBA::close($contacts);
2143
2144                 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2145                 $contacts = DBA::select('contact', ['uid'], $condition);
2146                 while ($contact = DBA::fetch($contacts)) {
2147                         if ($contact['uid'] == 0) {
2148                                 continue;
2149                         }
2150
2151                         $users[$contact['uid']] = $contact['uid'];
2152                 }
2153                 DBA::close($contacts);
2154
2155                 if (!empty($owner['alias'])) {
2156                         $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
2157                         $contacts = DBA::select('contact', ['uid'], $condition);
2158                         while ($contact = DBA::fetch($contacts)) {
2159                                 if ($contact['uid'] == 0) {
2160                                         continue;
2161                                 }
2162
2163                                 $users[$contact['uid']] = $contact['uid'];
2164                         }
2165                         DBA::close($contacts);
2166                 }
2167
2168                 $origin_uid = 0;
2169
2170                 if ($item['uri'] != $item['parent-uri']) {
2171                         $parents = Post::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2172                         while ($parent = Post::fetch($parents)) {
2173                                 $users[$parent['uid']] = $parent['uid'];
2174                                 if ($parent['origin'] && !$origin) {
2175                                         $origin_uid = $parent['uid'];
2176                                 }
2177                         }
2178                         DBA::close($parents);
2179                 }
2180
2181                 foreach ($users as $uid) {
2182                         if ($origin_uid == $uid) {
2183                                 $item['diaspora_signed_text'] = $signed_text;
2184                         }
2185                         self::storeForUser($item, $uid);
2186                 }
2187         }
2188
2189         /**
2190          * Store a public item defined by their URI-ID for the given users
2191          *
2192          * @param integer $uri_id URI-ID of the given item
2193          * @param integer $uid    The user that will receive the item entry
2194          * @param array   $fields Additional fields to be stored
2195          * @return integer stored item id
2196          */
2197         public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
2198         {
2199                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
2200                 if (!DBA::isResult($item)) {
2201                         return 0;
2202                 }
2203
2204                 if (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED)) {
2205                         Logger::notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]);
2206                         return 0;
2207                 }
2208
2209                 $item['post-type'] = self::PT_STORED;
2210
2211                 $item = array_merge($item, $fields);
2212
2213                 $stored = self::storeForUser($item, $uid);
2214                 Logger::info('Public item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
2215                 return $stored;
2216         }
2217
2218         /**
2219          * Store a public item array for the given users
2220          *
2221          * @param array   $item   The item entry that will be stored
2222          * @param integer $uid    The user that will receive the item entry
2223          * @return integer stored item id
2224          * @throws \Exception
2225          */
2226         private static function storeForUser(array $item, int $uid)
2227         {
2228                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
2229                         Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
2230                         return 0;
2231                 }
2232
2233                 unset($item['id']);
2234                 unset($item['parent']);
2235                 unset($item['mention']);
2236                 unset($item['starred']);
2237                 unset($item['unseen']);
2238                 unset($item['psid']);
2239
2240                 $item['uid'] = $uid;
2241                 $item['origin'] = 0;
2242                 $item['wall'] = 0;
2243
2244                 if ($item['gravity'] == GRAVITY_PARENT) {
2245                         $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
2246                 } else {
2247                         $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
2248                 }
2249
2250                 if (!empty($contact['id'])) {
2251                         $item['contact-id'] = $contact['id'];
2252                 } else {
2253                         // Shouldn't happen at all
2254                         Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
2255                         $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2256                         if (!DBA::isResult($self)) {
2257                                 // Shouldn't happen even less
2258                                 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
2259                                 return 0;
2260                         }
2261                         $item['contact-id'] = $self['id'];
2262                 }
2263
2264                 /// @todo Handling of "event-id"
2265
2266                 $notify = false;
2267                 if ($item['gravity'] == GRAVITY_PARENT) {
2268                         $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2269                         if (DBA::isResult($contact)) {
2270                                 $notify = self::isRemoteSelf($contact, $item);
2271                         }
2272                 }
2273
2274                 $distributed = self::insert($item, $notify, true);
2275
2276                 if (!$distributed) {
2277                         Logger::info("Distributed public item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
2278                 } else {
2279                         Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
2280                 }
2281                 return $distributed;
2282         }
2283
2284         /**
2285          * Add a shadow entry for a given item id that is a thread starter
2286          *
2287          * We store every public item entry additionally with the user id "0".
2288          * This is used for the community page and for the search.
2289          * It is planned that in the future we will store public item entries only once.
2290          *
2291          * @param integer $itemid Item ID that should be added
2292          * @throws \Exception
2293          */
2294         private static function addShadow($itemid)
2295         {
2296                 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2297                 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2298                 $item = Post::selectFirst($fields, $condition);
2299
2300                 if (!DBA::isResult($item)) {
2301                         return;
2302                 }
2303
2304                 // is it already a copy?
2305                 if (($itemid == 0) || ($item['uid'] == 0)) {
2306                         return;
2307                 }
2308
2309                 // Is it a visible public post?
2310                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == self::PRIVATE)) {
2311                         return;
2312                 }
2313
2314                 // is it an entry from a connector? Only add an entry for natively connected networks
2315                 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2316                         return;
2317                 }
2318
2319                 if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
2320                         return;
2321                 }
2322
2323                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2324
2325                 if (DBA::isResult($item)) {
2326                         // Preparing public shadow (removing user specific data)
2327                         $item['uid'] = 0;
2328                         unset($item['id']);
2329                         unset($item['parent']);
2330                         unset($item['wall']);
2331                         unset($item['mention']);
2332                         unset($item['origin']);
2333                         unset($item['starred']);
2334                         unset($item['postopts']);
2335                         unset($item['inform']);
2336                         unset($item['post-type']);
2337                         if ($item['uri'] == $item['parent-uri']) {
2338                                 $item['contact-id'] = $item['owner-id'];
2339                         } else {
2340                                 $item['contact-id'] = $item['author-id'];
2341                         }
2342
2343                         $public_shadow = self::insert($item, false, true);
2344
2345                         Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
2346                 }
2347         }
2348
2349         /**
2350          * Add a shadow entry for a given item id that is a comment
2351          *
2352          * This function does the same like the function above - but for comments
2353          *
2354          * @param integer $itemid Item ID that should be added
2355          * @throws \Exception
2356          */
2357         private static function addShadowPost($itemid)
2358         {
2359                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2360                 if (!DBA::isResult($item)) {
2361                         return;
2362                 }
2363
2364                 // Is it a toplevel post?
2365                 if ($item['gravity'] == GRAVITY_PARENT) {
2366                         self::addShadow($itemid);
2367                         return;
2368                 }
2369
2370                 // Is this a shadow entry?
2371                 if ($item['uid'] == 0) {
2372                         return;
2373                 }
2374
2375                 // Is there a shadow parent?
2376                 if (!Post::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2377                         return;
2378                 }
2379
2380                 // Is there already a shadow entry?
2381                 if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
2382                         return;
2383                 }
2384
2385                 // Save "origin" and "parent" state
2386                 $origin = $item['origin'];
2387                 $parent = $item['parent'];
2388
2389                 // Preparing public shadow (removing user specific data)
2390                 $item['uid'] = 0;
2391                 unset($item['id']);
2392                 unset($item['parent']);
2393                 unset($item['wall']);
2394                 unset($item['mention']);
2395                 unset($item['origin']);
2396                 unset($item['starred']);
2397                 unset($item['postopts']);
2398                 unset($item['inform']);
2399                 unset($item['post-type']);
2400                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2401
2402                 $public_shadow = self::insert($item, false, true);
2403
2404                 Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
2405
2406                 // If this was a comment to a Diaspora post we don't get our comment back.
2407                 // This means that we have to distribute the comment by ourselves.
2408                 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2409                         self::distribute($public_shadow);
2410                 }
2411         }
2412
2413         /**
2414          * Adds a language specification in a "language" element of given $arr.
2415          * Expects "body" element to exist in $arr.
2416          *
2417          * @param array $item
2418          * @return string detected language
2419          * @throws \Text_LanguageDetect_Exception
2420          */
2421         private static function getLanguage(array $item)
2422         {
2423                 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
2424                         return '';
2425                 }
2426
2427                 // Convert attachments to links
2428                 $naked_body = BBCode::removeAttachment($item['body']);
2429                 if (empty($naked_body)) {
2430                         return '';
2431                 }
2432
2433                 // Remove links and pictures
2434                 $naked_body = BBCode::removeLinks($naked_body);
2435
2436                 // Convert the title and the body to plain text
2437                 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
2438
2439                 // Remove possibly remaining links
2440                 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
2441
2442                 if (empty($naked_body)) {
2443                         return '';
2444                 }
2445
2446                 $ld = new Language(DI::l10n()->getAvailableLanguages());
2447                 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
2448                 if (is_array($languages)) {
2449                         return json_encode($languages);
2450                 }
2451
2452                 return '';
2453         }
2454
2455         public static function getLanguageMessage(array $item)
2456         {
2457                 $iso639 = new \Matriphe\ISO639\ISO639;
2458
2459                 $used_languages = '';
2460                 foreach (json_decode($item['language'], true) as $language => $reliability) {
2461                         $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2462                 }
2463                 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2464                 return $used_languages;
2465         }
2466
2467         /**
2468          * Creates an unique guid out of a given uri
2469          *
2470          * @param string $uri uri of an item entry
2471          * @param string $host hostname for the GUID prefix
2472          * @return string unique guid
2473          */
2474         public static function guidFromUri($uri, $host)
2475         {
2476                 // Our regular guid routine is using this kind of prefix as well
2477                 // We have to avoid that different routines could accidentally create the same value
2478                 $parsed = parse_url($uri);
2479
2480                 // We use a hash of the hostname as prefix for the guid
2481                 $guid_prefix = hash("crc32", $host);
2482
2483                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2484                 unset($parsed["scheme"]);
2485
2486                 // Glue it together to be able to make a hash from it
2487                 $host_id = implode("/", $parsed);
2488
2489                 // We could use any hash algorithm since it isn't a security issue
2490                 $host_hash = hash("ripemd128", $host_id);
2491
2492                 return $guid_prefix.$host_hash;
2493         }
2494
2495         /**
2496          * generate an unique URI
2497          *
2498          * @param integer $uid  User id
2499          * @param string  $guid An existing GUID (Otherwise it will be generated)
2500          *
2501          * @return string
2502          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2503          */
2504         public static function newURI($uid, $guid = "")
2505         {
2506                 if ($guid == "") {
2507                         $guid = System::createUUID();
2508                 }
2509
2510                 return DI::baseUrl()->get() . '/objects/' . $guid;
2511         }
2512
2513         /**
2514          * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2515          *
2516          * This can be used to filter for inactive contacts.
2517          * Only do this for public postings to avoid privacy problems, since poco data is public.
2518          * Don't set this value if it isn't from the owner (could be an author that we don't know)
2519          *
2520          * @param array $arr Contains the just posted item record
2521          * @throws \Exception
2522          */
2523         private static function updateContact($arr)
2524         {
2525                 // Unarchive the author
2526                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2527                 if (DBA::isResult($contact)) {
2528                         Contact::unmarkForArchival($contact);
2529                 }
2530
2531                 // Unarchive the contact if it's not our own contact
2532                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2533                 if (DBA::isResult($contact)) {
2534                         Contact::unmarkForArchival($contact);
2535                 }
2536
2537                 /// @todo On private posts we could obfuscate the date
2538                 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2539
2540                 // Is it a forum? Then we don't care about the rules from above
2541                 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2542                         if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2543                                 $update = true;
2544                         }
2545                 }
2546
2547                 if ($update) {
2548                         // The "self" contact id is used (for example in the connectors) when the contact is unknown
2549                         // So we have to ensure to only update the last item when it had been our own post,
2550                         // or it had been done by a "regular" contact.
2551                         if (!empty($arr['wall'])) {
2552                                 $condition = ['id' => $arr['contact-id']];
2553                         } else { 
2554                                 $condition = ['id' => $arr['contact-id'], 'self' => false];
2555                         }
2556                         DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2557                 }
2558                 // Now do the same for the system wide contacts with uid=0
2559                 if ($arr['private'] != self::PRIVATE) {
2560                         DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2561                                 ['id' => $arr['owner-id']]);
2562
2563                         if ($arr['owner-id'] != $arr['author-id']) {
2564                                 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2565                                         ['id' => $arr['author-id']]);
2566                         }
2567                 }
2568         }
2569
2570         public static function setHashtags($body)
2571         {
2572                 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
2573                         $tags = BBCode::getTags($body);
2574
2575                         // No hashtags?
2576                         if (!count($tags)) {
2577                                 return $body;
2578                         }
2579
2580                         // This sorting is important when there are hashtags that are part of other hashtags
2581                         // Otherwise there could be problems with hashtags like #test and #test2
2582                         // Because of this we are sorting from the longest to the shortest tag.
2583                         usort($tags, function ($a, $b) {
2584                                 return strlen($b) <=> strlen($a);
2585                         });
2586
2587                         $URLSearchString = "^\[\]";
2588
2589                         // All hashtags should point to the home server if "local_tags" is activated
2590                         if (DI::config()->get('system', 'local_tags')) {
2591                                 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2592                                         "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2593                         }
2594
2595                         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2596                         $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2597                                 function ($match) {
2598                                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
2599                                 }, $body);
2600
2601                         $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2602                                 function ($match) {
2603                                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
2604                                 }, $body);
2605
2606                         $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2607                                 function ($match) {
2608                                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
2609                                 }, $body);
2610
2611                         // Repair recursive urls
2612                         $body = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2613                                 "&num;$2", $body);
2614
2615                         foreach ($tags as $tag) {
2616                                 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2617                                         continue;
2618                                 }
2619
2620                                 $basetag = str_replace('_', ' ', substr($tag, 1));
2621                                 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2622
2623                                 $body = str_replace($tag, $newtag, $body);
2624                         }
2625
2626                         // Convert back the masked hashtags
2627                         $body = str_replace("&num;", "#", $body);
2628
2629                         return $body;
2630                 });
2631
2632                 return $body;
2633         }
2634
2635         /**
2636          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2637          *
2638          * @param int $uid
2639          * @param int $item_id
2640          * @return boolean true if item was deleted, else false
2641          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2642          * @throws \ImagickException
2643          */
2644         private static function tagDeliver($uid, $item_id)
2645         {
2646                 $mention = false;
2647
2648                 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2649                 if (!DBA::isResult($user)) {
2650                         return false;
2651                 }
2652
2653                 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2654                 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2655
2656                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2657                 if (!DBA::isResult($item)) {
2658                         return false;
2659                 }
2660
2661                 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2662
2663                 /*
2664                  * Diaspora uses their own hardwired link URL in @-tags
2665                  * instead of the one we supply with webfinger
2666                  */
2667                 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2668
2669                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2670                 if ($cnt) {
2671                         foreach ($matches as $mtch) {
2672                                 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2673                                         $mention = true;
2674                                         Logger::log('mention found: ' . $mtch[2]);
2675                                 }
2676                         }
2677                 }
2678
2679                 if (!$mention) {
2680                         $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2681                         foreach ($tags as $tag) {
2682                                 if (Strings::compareLink($link, $tag['url']) || Strings::compareLink($dlink, $tag['url'])) {
2683                                         $mention = true;
2684                                         DI::logger()->info('mention found in tag.', ['url' => $tag['url']]);
2685                                 }
2686                         }
2687                 }
2688                 
2689                 if (!$mention) {
2690                         if (($community_page || $prvgroup) &&
2691                                   !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
2692                                 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2693                                 DBA::delete('item', ['id' => $item_id]);
2694                                 return true;
2695                         }
2696                         return false;
2697                 }
2698
2699                 $arr = ['item' => $item, 'user' => $user];
2700
2701                 Hook::callAll('tagged', $arr);
2702
2703                 if (!$community_page && !$prvgroup) {
2704                         return false;
2705                 }
2706
2707                 /*
2708                  * tgroup delivery - setup a second delivery chain
2709                  * prevent delivery looping - only proceed
2710                  * if the message originated elsewhere and is a top-level post
2711                  */
2712                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2713                         return false;
2714                 }
2715
2716                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2717                 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2718                 if (!DBA::isResult($self)) {
2719                         return false;
2720                 }
2721
2722                 $owner_id = Contact::getIdForURL($self['url']);
2723
2724                 // also reset all the privacy bits to the forum default permissions
2725
2726                 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2727
2728                 $psid = PermissionSet::getIdFromACL(
2729                         $user['uid'],
2730                         $user['allow_cid'],
2731                         $user['allow_gid'],
2732                         $user['deny_cid'],
2733                         $user['deny_gid']
2734                 );
2735
2736                 $forum_mode = ($prvgroup ? 2 : 1);
2737
2738                 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2739                         'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2740                 self::update($fields, ['id' => $item_id]);
2741
2742                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2743
2744                 self::performActivity($item_id, 'announce', $uid);
2745
2746                 return false;
2747         }
2748
2749         /**
2750          * Automatically reshare the item if the "remote_self" option is selected
2751          *
2752          * @param array $item
2753          * @return void
2754          */
2755         private static function autoReshare(array $item)
2756         {
2757                 if ($item['gravity'] != GRAVITY_PARENT) {
2758                         return;
2759                 }
2760
2761                 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2762                         return;
2763                 }
2764
2765                 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2766                         return;
2767                 }
2768
2769                 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2770
2771                 self::performActivity($item['id'], 'announce', $item['uid']);
2772         }
2773
2774         public static function isRemoteSelf($contact, &$datarray)
2775         {
2776                 if (!$contact['remote_self']) {
2777                         return false;
2778                 }
2779
2780                 // Prevent the forwarding of posts that are forwarded
2781                 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2782                         Logger::info('Already forwarded');
2783                         return false;
2784                 }
2785
2786                 // Prevent to forward already forwarded posts
2787                 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2788                         Logger::info('Already forwarded (second test)');
2789                         return false;
2790                 }
2791
2792                 // Only forward posts
2793                 if ($datarray["verb"] != Activity::POST) {
2794                         Logger::info('No post');
2795                         return false;
2796                 }
2797
2798                 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2799                         Logger::info('Not public');
2800                         return false;
2801                 }
2802
2803                 $datarray2 = $datarray;
2804                 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2805                 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2806                         $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2807                                         ['uid' => $contact['uid'], 'self' => true]);
2808                         if (DBA::isResult($self)) {
2809                                 $datarray['contact-id'] = $self["id"];
2810
2811                                 $datarray['owner-name'] = $self["name"];
2812                                 $datarray['owner-link'] = $self["url"];
2813                                 $datarray['owner-avatar'] = $self["thumb"];
2814
2815                                 $datarray['author-name']   = $datarray['owner-name'];
2816                                 $datarray['author-link']   = $datarray['owner-link'];
2817                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
2818
2819                                 unset($datarray['edited']);
2820
2821                                 unset($datarray['network']);
2822                                 unset($datarray['owner-id']);
2823                                 unset($datarray['author-id']);
2824                         }
2825
2826                         if ($contact['network'] != Protocol::FEED) {
2827                                 $old_uri_id = $datarray["uri-id"] ?? 0;
2828                                 $datarray["guid"] = System::createUUID();
2829                                 unset($datarray["plink"]);
2830                                 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2831                                 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2832                                 $datarray["extid"] = Protocol::DFRN;
2833                                 $urlpart = parse_url($datarray2['author-link']);
2834                                 $datarray["app"] = $urlpart["host"];
2835                                 if (!empty($old_uri_id)) {
2836                                         Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2837                                 }
2838
2839                                 unset($datarray["parent-uri"]);
2840                                 unset($datarray["thr-parent"]);
2841                         } else {
2842                                 $datarray['private'] = self::PUBLIC;
2843                         }
2844                 }
2845
2846                 if ($contact['network'] != Protocol::FEED) {
2847                         // Store the original post
2848                         $result = self::insert($datarray2);
2849                         Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2850                 } else {
2851                         $datarray["app"] = "Feed";
2852                         $result = true;
2853                 }
2854
2855                 // Trigger automatic reactions for addons
2856                 $datarray['api_source'] = true;
2857
2858                 // We have to tell the hooks who we are - this really should be improved
2859                 $_SESSION['authenticated'] = true;
2860                 $_SESSION['uid'] = $contact['uid'];
2861
2862                 return (bool)$result;
2863         }
2864
2865         /**
2866          *
2867          * @param string $s
2868          * @param int    $uid
2869          * @param array  $item
2870          * @param int    $cid
2871          * @return string
2872          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2873          * @throws \ImagickException
2874          */
2875         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2876         {
2877                 if (DI::config()->get('system', 'disable_embedded')) {
2878                         return $s;
2879                 }
2880
2881                 Logger::info('check for photos');
2882                 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2883
2884                 $orig_body = $s;
2885                 $new_body = '';
2886
2887                 $img_start = strpos($orig_body, '[img');
2888                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2889                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2890
2891                 while (($img_st_close !== false) && ($img_len !== false)) {
2892                         $img_st_close++; // make it point to AFTER the closing bracket
2893                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2894
2895                         Logger::info('found photo', ['image' => $image]);
2896
2897                         if (stristr($image, $site . '/photo/')) {
2898                                 // Only embed locally hosted photos
2899                                 $replace = false;
2900                                 $i = basename($image);
2901                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2902                                 $x = strpos($i, '-');
2903
2904                                 if ($x) {
2905                                         $res = substr($i, $x + 1);
2906                                         $i = substr($i, 0, $x);
2907                                         $photo = Photo::getPhotoForUser($uid, $i, $res);
2908                                         if (DBA::isResult($photo)) {
2909                                                 /*
2910                                                  * Check to see if we should replace this photo link with an embedded image
2911                                                  * 1. No need to do so if the photo is public
2912                                                  * 2. If there's a contact-id provided, see if they're in the access list
2913                                                  *    for the photo. If so, embed it.
2914                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
2915                                                  *    permissions, regardless of order but first check to see if they're an exact
2916                                                  *    match to save some processing overhead.
2917                                                  */
2918                                                 if (self::hasPermissions($photo)) {
2919                                                         if ($cid) {
2920                                                                 $recips = self::enumeratePermissions($photo);
2921                                                                 if (in_array($cid, $recips)) {
2922                                                                         $replace = true;
2923                                                                 }
2924                                                         } elseif ($item) {
2925                                                                 if (self::samePermissions($uid, $item, $photo)) {
2926                                                                         $replace = true;
2927                                                                 }
2928                                                         }
2929                                                 }
2930                                                 if ($replace) {
2931                                                         $photo_img = Photo::getImageForPhoto($photo);
2932                                                         // If a custom width and height were specified, apply before embedding
2933                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2934                                                                 Logger::info('scaling photo');
2935
2936                                                                 $width = intval($match[1]);
2937                                                                 $height = intval($match[2]);
2938
2939                                                                 $photo_img->scaleDown(max($width, $height));
2940                                                         }
2941
2942                                                         $data = $photo_img->asString();
2943                                                         $type = $photo_img->getType();
2944
2945                                                         Logger::info('replacing photo');
2946                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
2947                                                         Logger::debug('replaced', ['image' => $image]);
2948                                                 }
2949                                         }
2950                                 }
2951                         }
2952
2953                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2954                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2955                         if ($orig_body === false) {
2956                                 $orig_body = '';
2957                         }
2958
2959                         $img_start = strpos($orig_body, '[img');
2960                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2961                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2962                 }
2963
2964                 $new_body = $new_body . $orig_body;
2965
2966                 return $new_body;
2967         }
2968
2969         private static function hasPermissions($obj)
2970         {
2971                 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2972                         !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2973         }
2974
2975         private static function samePermissions($uid, $obj1, $obj2)
2976         {
2977                 // first part is easy. Check that these are exactly the same.
2978                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2979                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
2980                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
2981                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2982                         return true;
2983                 }
2984
2985                 // This is harder. Parse all the permissions and compare the resulting set.
2986                 $recipients1 = self::enumeratePermissions($obj1);
2987                 $recipients2 = self::enumeratePermissions($obj2);
2988                 sort($recipients1);
2989                 sort($recipients2);
2990
2991                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2992                 return ($recipients1 == $recipients2);
2993         }
2994
2995         /**
2996          * Returns an array of contact-ids that are allowed to see this object
2997          *
2998          * @param array $obj        Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2999          * @param bool  $check_dead Prunes unavailable contacts from the result
3000          * @return array
3001          * @throws \Exception
3002          */
3003         public static function enumeratePermissions(array $obj, bool $check_dead = false)
3004         {
3005                 $aclFormater = DI::aclFormatter();
3006
3007                 $allow_people = $aclFormater->expand($obj['allow_cid']);
3008                 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
3009                 $deny_people  = $aclFormater->expand($obj['deny_cid']);
3010                 $deny_groups  = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
3011                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
3012                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
3013                 $recipients   = array_diff($recipients, $deny);
3014                 return $recipients;
3015         }
3016
3017         public static function expire(int $uid, int $days, string $network = "", bool $force = false)
3018         {
3019                 if (!$uid || ($days < 1)) {
3020                         return;
3021                 }
3022
3023                 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
3024                         $uid, GRAVITY_PARENT];
3025
3026                 /*
3027                  * $expire_network_only = save your own wall posts
3028                  * and just expire conversations started by others
3029                  */
3030                 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
3031
3032                 if ($expire_network_only) {
3033                         $condition[0] .= " AND NOT `wall`";
3034                 }
3035
3036                 if ($network != "") {
3037                         $condition[0] .= " AND `network` = ?";
3038                         $condition[] = $network;
3039                 }
3040
3041                 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3042                 $condition[] = $days;
3043
3044                 $items = Post::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3045
3046                 if (!DBA::isResult($items)) {
3047                         return;
3048                 }
3049
3050                 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
3051
3052                 // Forcing expiring of items - but not notes and marked items
3053                 if ($force) {
3054                         $expire_items = true;
3055                 }
3056
3057                 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3058                 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3059                 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3060
3061                 $expired = 0;
3062
3063                 $priority = DI::config()->get('system', 'expire-notify-priority');
3064
3065                 while ($item = Post::fetch($items)) {
3066                         // don't expire filed items
3067
3068                         if (strpos($item['file'], '[') !== false) {
3069                                 continue;
3070                         }
3071
3072                         // Only expire posts, not photos and photo comments
3073
3074                         if (!$expire_photos && strlen($item['resource-id'])) {
3075                                 continue;
3076                         } elseif (!$expire_starred && intval($item['starred'])) {
3077                                 continue;
3078                         } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == self::PT_PERSONAL_NOTE))) {
3079                                 continue;
3080                         } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
3081                                 continue;
3082                         }
3083
3084                         self::markForDeletionById($item['id'], $priority);
3085
3086                         ++$expired;
3087                 }
3088                 DBA::close($items);
3089                 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3090         }
3091
3092         public static function firstPostDate($uid, $wall = false)
3093         {
3094                 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3095                 $params = ['order' => ['received' => false]];
3096                 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3097                 if (DBA::isResult($thread)) {
3098                         return substr(DateTimeFormat::local($thread['received']), 0, 10);
3099                 }
3100                 return false;
3101         }
3102
3103         /**
3104          * add/remove activity to an item
3105          *
3106          * Toggle activities as like,dislike,attend of an item
3107          *
3108          * @param int $item_id
3109          * @param string $verb
3110          *            Activity verb. One of
3111          *            like, unlike, dislike, undislike, attendyes, unattendyes,
3112          *            attendno, unattendno, attendmaybe, unattendmaybe,
3113          *            announce, unannouce
3114          * @return bool
3115          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3116          * @throws \ImagickException
3117          * @hook  'post_local_end'
3118          *            array $arr
3119          *            'post_id' => ID of posted item
3120          */
3121         public static function performActivity(int $item_id, string $verb, int $uid)
3122         {
3123                 if (empty($uid)) {
3124                         return false;
3125                 }
3126
3127                 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
3128
3129                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
3130                 if (!DBA::isResult($item)) {
3131                         Logger::log('like: unknown item ' . $item_id);
3132                         return false;
3133                 }
3134
3135                 $item_uri = $item['uri'];
3136
3137                 if (!in_array($item['uid'], [0, $uid])) {
3138                         return false;
3139                 }
3140
3141                 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
3142                         $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
3143                         if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
3144                                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
3145                                 if (!DBA::isResult($item)) {
3146                                         Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
3147                                         return false;
3148                                 }
3149                         }
3150                 }
3151
3152                 // Retrieves the local post owner
3153                 $owner = User::getOwnerDataById($uid);
3154                 if (empty($owner)) {
3155                         Logger::info('Empty owner for user', ['uid' => $uid]);
3156                         return false;
3157                 }
3158
3159                 // Retrieve the current logged in user's public contact
3160                 $author_id = Contact::getIdForURL($owner['url']);
3161                 if (empty($author_id)) {
3162                         Logger::info('Empty public contact');
3163                         return false;
3164                 }
3165
3166                 $activity = null;
3167                 switch ($verb) {
3168                         case 'like':
3169                         case 'unlike':
3170                                 $activity = Activity::LIKE;
3171                                 break;
3172                         case 'dislike':
3173                         case 'undislike':
3174                                 $activity = Activity::DISLIKE;
3175                                 break;
3176                         case 'attendyes':
3177                         case 'unattendyes':
3178                                 $activity = Activity::ATTEND;
3179                                 break;
3180                         case 'attendno':
3181                         case 'unattendno':
3182                                 $activity = Activity::ATTENDNO;
3183                                 break;
3184                         case 'attendmaybe':
3185                         case 'unattendmaybe':
3186                                 $activity = Activity::ATTENDMAYBE;
3187                                 break;
3188                         case 'follow':
3189                         case 'unfollow':
3190                                 $activity = Activity::FOLLOW;
3191                                 break;
3192                         case 'announce':
3193                         case 'unannounce':
3194                                 $activity = Activity::ANNOUNCE;
3195                                 break;
3196                         default:
3197                                 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3198                                 return false;
3199                 }
3200
3201                 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3202
3203                 // Enable activity toggling instead of on/off
3204                 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3205
3206                 // Look for an existing verb row
3207                 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3208                 if ($event_verb_flag) {
3209                         $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3210
3211                         // Translate to the index based activity index
3212                         $vids = [];
3213                         foreach ($verbs as $verb) {
3214                                 $vids[] = Verb::getID($verb);
3215                         }
3216                 } else {
3217                         $vids = Verb::getID($activity);
3218                 }
3219
3220                 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3221                         'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3222                 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
3223
3224                 if (DBA::isResult($like_item)) {
3225                         /**
3226                          * Truth table for existing activities
3227                          *
3228                          * |          Inputs            ||      Outputs      |
3229                          * |----------------------------||-------------------|
3230                          * |  Mode  | Event | Same verb || Delete? | Return? |
3231                          * |--------|-------|-----------||---------|---------|
3232                          * | create |  Yes  |    Yes    ||   No    |   Yes   |
3233                          * | create |  Yes  |    No     ||   Yes   |   No    |
3234                          * | create |  No   |    Yes    ||   No    |   Yes   |
3235                          * | create |  No   |    No     ||        N/A†       |
3236                          * | delete |  Yes  |    Yes    ||   Yes   |   N/A‡  |
3237                          * | delete |  Yes  |    No     ||   No    |   N/A‡  |
3238                          * | delete |  No   |    Yes    ||   Yes   |   N/A‡  |
3239                          * | delete |  No   |    No     ||        N/A†       |
3240                          * |--------|-------|-----------||---------|---------|
3241                          * |   A    |   B   |     C     || A xor C | !B or C |
3242                          *
3243                          * â€  Can't happen: It's impossible to find an existing non-event activity without
3244                          *                 the same verb because we are only looking for this single verb.
3245                          *
3246                          * â€¡ The "mode = delete" is returning early whether an existing activity was found or not.
3247                          */
3248                         if ($mode == 'create' xor $like_item['verb'] == $activity) {
3249                                 self::markForDeletionById($like_item['id']);
3250                         }
3251
3252                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
3253                                 return true;
3254                         }
3255                 }
3256
3257                 // No need to go further if we aren't creating anything
3258                 if ($mode == 'delete') {
3259                         return true;
3260                 }
3261
3262                 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3263
3264                 $new_item = [
3265                         'guid'          => System::createUUID(),
3266                         'uri'           => self::newURI($item['uid']),
3267                         'uid'           => $item['uid'],
3268                         'contact-id'    => $owner['id'],
3269                         'wall'          => $item['wall'],
3270                         'origin'        => 1,
3271                         'network'       => Protocol::DFRN,
3272                         'protocol'      => Conversation::PARCEL_DIRECT,
3273                         'direction'     => Conversation::PUSH,
3274                         'gravity'       => GRAVITY_ACTIVITY,
3275                         'parent'        => $item['id'],
3276                         'thr-parent'    => $item['uri'],
3277                         'owner-id'      => $author_id,
3278                         'author-id'     => $author_id,
3279                         'body'          => $activity,
3280                         'verb'          => $activity,
3281                         'object-type'   => $objtype,
3282                         'allow_cid'     => $item['allow_cid'],
3283                         'allow_gid'     => $item['allow_gid'],
3284                         'deny_cid'      => $item['deny_cid'],
3285                         'deny_gid'      => $item['deny_gid'],
3286                         'visible'       => 1,
3287                         'unseen'        => 1,
3288                 ];
3289
3290                 $signed = Diaspora::createLikeSignature($uid, $new_item);
3291                 if (!empty($signed)) {
3292                         $new_item['diaspora_signed_text'] = json_encode($signed);
3293                 }
3294
3295                 $new_item_id = self::insert($new_item);
3296
3297                 // If the parent item isn't visible then set it to visible
3298                 if (!$item['visible']) {
3299                         self::update(['visible' => true], ['id' => $item['id']]);
3300                 }
3301
3302                 $new_item['id'] = $new_item_id;
3303
3304                 Hook::callAll('post_local_end', $new_item);
3305
3306                 return true;
3307         }
3308
3309         private static function addThread($itemid, $onlyshadow = false)
3310         {
3311                 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3312                         'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
3313                         'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3314                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3315                 $item = Post::selectFirst($fields, $condition);
3316
3317                 if (!DBA::isResult($item)) {
3318                         return;
3319                 }
3320
3321                 $item['iid'] = $itemid;
3322
3323                 if (!$onlyshadow) {
3324                         $result = DBA::replace('thread', $item);
3325
3326                         Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
3327                 }
3328         }
3329
3330         private static function updateThread($itemid, $setmention = false)
3331         {
3332                 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3333                         'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
3334                         'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3335
3336                 $item = Post::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
3337                 if (!DBA::isResult($item)) {
3338                         return;
3339                 }
3340
3341                 if ($setmention) {
3342                         $item["mention"] = 1;
3343                 }
3344
3345                 $fields = [];
3346
3347                 foreach ($item as $field => $data) {
3348                         if (!in_array($field, ["guid"])) {
3349                                 $fields[$field] = $data;
3350                         }
3351                 }
3352
3353                 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3354
3355                 Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
3356         }
3357
3358         private static function deleteThread($itemid, $itemuri = "")
3359         {
3360                 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3361                 if (!DBA::isResult($item)) {
3362                         Logger::info('No thread found', ['id' => $itemid]);
3363                         return;
3364                 }
3365
3366                 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3367
3368                 Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
3369
3370                 if ($itemuri != "") {
3371                         $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3372                         if (!Post::exists($condition)) {
3373                                 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3374                                 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3375                         }
3376                 }
3377         }
3378
3379         /**
3380          * Fetch the SQL condition for the given user id
3381          *
3382          * @param integer $owner_id User ID for which the permissions should be fetched
3383          * @return array condition
3384          */
3385         public static function getPermissionsConditionArrayByUserId(int $owner_id)
3386         {
3387                 $local_user = local_user();
3388                 $remote_user = Session::getRemoteContactID($owner_id);
3389
3390                 // default permissions - anonymous user
3391                 $condition = ["`private` != ?", self::PRIVATE];
3392
3393                 if ($local_user && ($local_user == $owner_id)) {
3394                         // Profile owner - everything is visible
3395                         $condition = [];
3396                 } elseif ($remote_user) {
3397                          // Authenticated visitor - fetch the matching permissionsets
3398                         $set = PermissionSet::get($owner_id, $remote_user);
3399                         if (!empty($set)) {
3400                                 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
3401                                         AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
3402                                         self::PRIVATE, self::PRIVATE];
3403                                 $condition = array_merge($condition, $set);
3404                         }
3405                 }
3406
3407                 return $condition;
3408         }
3409
3410         public static function getPermissionsSQLByUserId($owner_id)
3411         {
3412                 $local_user = local_user();
3413                 $remote_user = Session::getRemoteContactID($owner_id);
3414
3415                 /*
3416                  * Construct permissions
3417                  *
3418                  * default permissions - anonymous user
3419                  */
3420                 $sql = sprintf(" AND `private` != %d", self::PRIVATE);
3421
3422                 // Profile owner - everything is visible
3423                 if ($local_user && ($local_user == $owner_id)) {
3424                         $sql = '';
3425                 } elseif ($remote_user) {
3426                         /*
3427                          * Authenticated visitor. Unless pre-verified,
3428                          * check that the contact belongs to this $owner_id
3429                          * and load the groups the visitor belongs to.
3430                          * If pre-verified, the caller is expected to have already
3431                          * done this and passed the groups into this function.
3432                          */
3433                         $set = PermissionSet::get($owner_id, $remote_user);
3434
3435                         if (!empty($set)) {
3436                                 $sql_set = sprintf(" OR (`private` = %d AND `wall` AND `psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3437                         } else {
3438                                 $sql_set = '';
3439                         }
3440
3441                         $sql = sprintf(" AND (`private` != %d", self::PRIVATE) . $sql_set . ")";
3442                 }
3443
3444                 return $sql;
3445         }
3446
3447         /**
3448          * get translated item type
3449          *
3450          * @param $item
3451          * @return string
3452          */
3453         public static function postType($item)
3454         {
3455                 if (!empty($item['event-id'])) {
3456                         return DI::l10n()->t('event');
3457                 } elseif (!empty($item['resource-id'])) {
3458                         return DI::l10n()->t('photo');
3459                 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
3460                         return DI::l10n()->t('activity');
3461                 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
3462                         return DI::l10n()->t('comment');
3463                 }
3464
3465                 return DI::l10n()->t('post');
3466         }
3467
3468         /**
3469          * Sets the "rendered-html" field of the provided item
3470          *
3471          * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3472          *
3473          * @param array $item
3474          * @param bool  $update
3475          *
3476          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3477          * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3478          */
3479         public static function putInCache(&$item, $update = false)
3480         {
3481                 // Save original body to prevent addons to modify it
3482                 $body = $item['body'];
3483
3484                 $rendered_hash = $item['rendered-hash'] ?? '';
3485                 $rendered_html = $item['rendered-html'] ?? '';
3486
3487                 if ($rendered_hash == ''
3488                         || $rendered_html == ''
3489                         || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3490                         || DI::config()->get('system', 'ignore_cache')
3491                 ) {
3492                         self::addRedirToImageTags($item);
3493
3494                         $item['rendered-html'] = BBCode::convert($item['body']);
3495                         $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3496
3497                         $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3498                         Hook::callAll('put_item_in_cache', $hook_data);
3499                         $item['rendered-html'] = $hook_data['rendered-html'];
3500                         $item['rendered-hash'] = $hook_data['rendered-hash'];
3501                         unset($hook_data);
3502
3503                         // Force an update if the generated values differ from the existing ones
3504                         if ($rendered_hash != $item['rendered-hash']) {
3505                                 $update = true;
3506                         }
3507
3508                         // Only compare the HTML when we forcefully ignore the cache
3509                         if (DI::config()->get('system', 'ignore_cache') && ($rendered_html != $item['rendered-html'])) {
3510                                 $update = true;
3511                         }
3512
3513                         if ($update && !empty($item['id'])) {
3514                                 self::update(
3515                                         [
3516                                                 'rendered-html' => $item['rendered-html'],
3517                                                 'rendered-hash' => $item['rendered-hash']
3518                                         ],
3519                                         ['id' => $item['id']]
3520                                 );
3521                         }
3522                 }
3523
3524                 $item['body'] = $body;
3525         }
3526
3527         /**
3528          * Find any non-embedded images in private items and add redir links to them
3529          *
3530          * @param array &$item The field array of an item row
3531          */
3532         private static function addRedirToImageTags(array &$item)
3533         {
3534                 $app = DI::app();
3535
3536                 $matches = [];
3537                 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3538                 if ($cnt) {
3539                         foreach ($matches as $mtch) {
3540                                 if (strpos($mtch[1], '/redir') !== false) {
3541                                         continue;
3542                                 }
3543
3544                                 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3545                                         $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3546                                         $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3547                                 }
3548                         }
3549                 }
3550         }
3551
3552         /**
3553          * Given an item array, convert the body element from bbcode to html and add smilie icons.
3554          * If attach is true, also add icons for item attachments.
3555          *
3556          * @param array   $item
3557          * @param boolean $attach
3558          * @param boolean $is_preview
3559          * @return string item body html
3560          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3561          * @throws \ImagickException
3562          * @hook  prepare_body_init item array before any work
3563          * @hook  prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3564          * @hook  prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3565          * @hook  prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3566          */
3567         public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3568         {
3569                 $a = DI::app();
3570                 Hook::callAll('prepare_body_init', $item);
3571
3572                 // In order to provide theme developers more possibilities, event items
3573                 // are treated differently.
3574                 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3575                         $ev = Event::getItemHTML($item);
3576                         return $ev;
3577                 }
3578
3579                 $tags = Tag::populateFromItem($item);
3580
3581                 $item['tags'] = $tags['tags'];
3582                 $item['hashtags'] = $tags['hashtags'];
3583                 $item['mentions'] = $tags['mentions'];
3584
3585                 // Compile eventual content filter reasons
3586                 $filter_reasons = [];
3587                 if (!$is_preview && public_contact() != $item['author-id']) {
3588                         if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3589                                 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3590                         }
3591
3592                         $hook_data = [
3593                                 'item' => $item,
3594                                 'filter_reasons' => $filter_reasons
3595                         ];
3596                         Hook::callAll('prepare_body_content_filter', $hook_data);
3597                         $filter_reasons = $hook_data['filter_reasons'];
3598                         unset($hook_data);
3599                 }
3600
3601                 // Update the cached values if there is no "zrl=..." on the links.
3602                 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3603
3604                 // Or update it if the current viewer is the intented viewer.
3605                 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3606                         $update = true;
3607                 }
3608
3609                 self::putInCache($item, $update);
3610                 $s = $item["rendered-html"];
3611
3612                 $hook_data = [
3613                         'item' => $item,
3614                         'html' => $s,
3615                         'preview' => $is_preview,
3616                         'filter_reasons' => $filter_reasons
3617                 ];
3618                 Hook::callAll('prepare_body', $hook_data);
3619                 $s = $hook_data['html'];
3620                 unset($hook_data);
3621
3622                 if (!$attach) {
3623                         // Replace the blockquotes with quotes that are used in mails.
3624                         $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3625                         $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3626                         return $s;
3627                 }
3628
3629                 $as = '';
3630                 $vhead = false;
3631                 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
3632                         $mime = $attachment['mimetype'];
3633
3634                         $the_url = Contact::magicLinkById($item['author-id'], $attachment['url']);
3635
3636                         if (strpos($mime, 'video') !== false) {
3637                                 if (!$vhead) {
3638                                         $vhead = true;
3639                                         DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3640                                 }
3641
3642                                 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3643                                         '$video' => [
3644                                                 'id'     => $item['author-id'],
3645                                                 'title'  => DI::l10n()->t('View Video'),
3646                                                 'src'    => $the_url,
3647                                                 'mime'   => $mime,
3648                                         ],
3649                                 ]);
3650                         }
3651
3652                         $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3653                         if ($filetype) {
3654                                 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3655                                 $filesubtype = str_replace('.', '-', $filesubtype);
3656                         } else {
3657                                 $filetype = 'unkn';
3658                                 $filesubtype = 'unkn';
3659                         }
3660
3661                         $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3662                         $title .= ' ' . ($attachment['size'] ?? 0) . ' ' . DI::l10n()->t('bytes');
3663
3664                         $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3665                         $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3666                 }
3667
3668                 if ($as != '') {
3669                         $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3670                 }
3671
3672                 // Map.
3673                 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3674                         $x = Map::byCoordinates(trim($item['coord']));
3675                         if ($x) {
3676                                 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3677                         }
3678                 }
3679
3680                 // Replace friendica image url size with theme preference.
3681                 if (!empty($a->theme_info['item_image_size'])) {
3682                         $ps = $a->theme_info['item_image_size'];
3683                         $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3684                 }
3685
3686                 $s = HTML::applyContentFilter($s, $filter_reasons);
3687
3688                 $hook_data = ['item' => $item, 'html' => $s];
3689                 Hook::callAll('prepare_body_final', $hook_data);
3690
3691                 return $hook_data['html'];
3692         }
3693
3694         /**
3695          * get private link for item
3696          *
3697          * @param array $item
3698          * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3699          * @throws \Exception
3700          */
3701         public static function getPlink($item)
3702         {
3703                 if (local_user()) {
3704                         $ret = [
3705                                 'href' => "display/" . $item['guid'],
3706                                 'orig' => "display/" . $item['guid'],
3707                                 'title' => DI::l10n()->t('View on separate page'),
3708                                 'orig_title' => DI::l10n()->t('view on separate page'),
3709                         ];
3710
3711                         if (!empty($item['plink'])) {
3712                                 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3713                                 $ret["title"] = DI::l10n()->t('link to source');
3714                         }
3715                 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3716                         $ret = [
3717                                 'href' => $item['plink'],
3718                                 'orig' => $item['plink'],
3719                                 'title' => DI::l10n()->t('link to source'),
3720                         ];
3721                 } else {
3722                         $ret = [];
3723                 }
3724
3725                 return $ret;
3726         }
3727
3728         /**
3729          * Is the given item array a post that is sent as starting post to a forum?
3730          *
3731          * @param array $item
3732          * @param array $owner
3733          *
3734          * @return boolean "true" when it is a forum post
3735          */
3736         public static function isForumPost(array $item, array $owner = [])
3737         {
3738                 if (empty($owner)) {
3739                         $owner = User::getOwnerDataById($item['uid']);
3740                         if (empty($owner)) {
3741                                 return false;
3742                         }
3743                 }
3744
3745                 if (($item['author-id'] == $item['owner-id']) ||
3746                         ($owner['id'] == $item['contact-id']) ||
3747                         ($item['uri'] != $item['parent-uri']) ||
3748                         $item['origin']) {
3749                         return false;
3750                 }
3751
3752                 return Contact::isForum($item['contact-id']);
3753         }
3754
3755         /**
3756          * Search item id for given URI or plink
3757          *
3758          * @param string $uri
3759          * @param integer $uid
3760          *
3761          * @return integer item id
3762          */
3763         public static function searchByLink($uri, $uid = 0)
3764         {
3765                 $ssl_uri = str_replace('http://', 'https://', $uri);
3766                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3767
3768                 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3769                 if (DBA::isResult($item)) {
3770                         return $item['id'];
3771                 }
3772
3773                 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3774                 if (!DBA::isResult($itemcontent)) {
3775                         return 0;
3776                 }
3777
3778                 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3779                 if (!DBA::isResult($itemuri)) {
3780                         return 0;
3781                 }
3782
3783                 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3784                 if (DBA::isResult($item)) {
3785                         return $item['id'];
3786                 }
3787
3788                 return 0;
3789         }
3790
3791         /**
3792          * Return the URI for a link to the post 
3793          * 
3794          * @param string $uri URI or link to post
3795          *
3796          * @return string URI
3797          */
3798         public static function getURIByLink(string $uri)
3799         {
3800                 $ssl_uri = str_replace('http://', 'https://', $uri);
3801                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3802
3803                 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3804                 if (DBA::isResult($item)) {
3805                         return $item['uri'];
3806                 }
3807
3808                 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3809                 if (!DBA::isResult($itemcontent)) {
3810                         return '';
3811                 }
3812
3813                 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3814                 if (DBA::isResult($itemuri)) {
3815                         return $itemuri['uri'];
3816                 }
3817
3818                 return '';
3819         }
3820
3821         /**
3822          * Fetches item for given URI or plink
3823          *
3824          * @param string $uri
3825          * @param integer $uid
3826          *
3827          * @return integer item id
3828          */
3829         public static function fetchByLink(string $uri, int $uid = 0)
3830         {
3831                 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3832                 $item_id = self::searchByLink($uri, $uid);
3833                 if (!empty($item_id)) {
3834                         Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3835                         return $item_id;
3836                 }
3837
3838                 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3839                         $item_id = self::searchByLink($fetched_uri, $uid);
3840                 } else {
3841                         $item_id = Diaspora::fetchByURL($uri);
3842                 }
3843
3844                 if (!empty($item_id)) {
3845                         Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3846                         return $item_id;
3847                 }
3848
3849                 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3850                 return 0;
3851         }
3852
3853         /**
3854          * Return share data from an item array (if the item is shared item)
3855          * We are providing the complete Item array, because at some time in the future
3856          * we hopefully will define these values not in the body anymore but in some item fields.
3857          * This function is meant to replace all similar functions in the system.
3858          *
3859          * @param array $item
3860          *
3861          * @return array with share information
3862          */
3863         public static function getShareArray($item)
3864         {
3865                 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3866                         return [];
3867                 }
3868
3869                 $attribute_string = $matches[2];
3870                 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3871                 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3872                         if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3873                                 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3874                         }
3875                 }
3876                 return $attributes;
3877         }
3878
3879         /**
3880          * Fetch item information for shared items from the original items and adds it.
3881          *
3882          * @param array $item
3883          *
3884          * @return array item array with data from the original item
3885          */
3886         public static function addShareDataFromOriginal(array $item)
3887         {
3888                 $shared = self::getShareArray($item);
3889                 if (empty($shared)) {
3890                         return $item;
3891                 }
3892
3893                 // Real reshares always have got a GUID.
3894                 if (empty($shared['guid'])) {
3895                         return $item;
3896                 }
3897
3898                 $uid = $item['uid'] ?? 0;
3899
3900                 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3901                 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3902                 if (!DBA::isResult($shared_item)) {
3903                         if (empty($shared['link'])) {
3904                                 return $item;
3905                         }
3906
3907                         // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3908                         $id = self::fetchByLink($shared['link'] ?? '', $uid);
3909                         if (empty($id)) {
3910                                 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3911                                 return $item;
3912                         }
3913
3914                         $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3915                         if (!DBA::isResult($shared_item)) {
3916                                 return $item;
3917                         }
3918                         Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3919                 } else {
3920                         Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3921                 }
3922
3923                 if (!empty($shared_item['title'])) {
3924                         $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3925                         unset($shared_item['title']);
3926                 } else {
3927                         $body = $shared_item['body'];
3928                 }
3929
3930                 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3931                 unset($shared_item['body']);
3932
3933                 return array_merge($item, $shared_item);
3934         }
3935
3936         /**
3937          * Check a prospective item array against user-level permissions
3938          *
3939          * @param array $item Expected keys: uri, gravity, and
3940          *                    author-link if is author-id is set,
3941          *                    owner-link if is owner-id is set,
3942          *                    causer-link if is causer-id is set.
3943          * @param int   $user_id Local user ID
3944          * @return bool
3945          * @throws \Exception
3946          */
3947         protected static function isAllowedByUser(array $item, int $user_id)
3948         {
3949                 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3950                         Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3951                         return false;
3952                 }
3953
3954                 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3955                         Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3956                         return false;
3957                 }
3958
3959                 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3960                 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3961                         Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3962                         return false;
3963                 }
3964
3965                 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3966                         Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3967                         return false;
3968                 }
3969
3970                 return true;
3971         }
3972 }