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