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