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