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