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