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