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