3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model;
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;
36 use Friendica\Model\Post;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Map;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Worker\Delivery;
47 use GuzzleHttp\Psr7\Uri;
48 use LanguageDetection\Language;
52 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
59 const PT_DOCUMENT = 19;
62 const PT_PERSONAL_NOTE = 128;
64 // Posting reasons (Why had a post been stored for a user?)
71 const PR_FOLLOWER = 69;
72 const PR_ANNOUNCEMENT = 70;
73 const PR_COMMENT = 71;
77 const PR_FETCHED = 75;
78 const PR_COMPLETION = 76;
80 const PR_ACTIVITY = 78;
81 const PR_DISTRIBUTE = 79;
85 // system.accept_only_sharer setting values
86 const COMPLETION_NONE = 1;
87 const COMPLETION_COMMENT = 0;
88 const COMPLETION_LIKE = 2;
90 // Field list that is used to display the items
91 const DISPLAY_FIELDLIST = [
92 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
93 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
94 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
95 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
96 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
97 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
98 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
99 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
100 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
101 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
102 'writable', 'self', 'cid', 'alias',
103 'event-created', 'event-edited', 'event-start', 'event-finish',
104 'event-summary', 'event-desc', 'event-location', 'event-type',
105 'event-nofinish', 'event-ignore', 'event-id',
106 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
107 'has-categories', 'has-media',
108 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
111 // Field list that is used to deliver items via the protocols
112 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
113 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
114 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
115 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
116 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
117 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
118 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
119 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
120 'event-created', 'event-edited', 'event-start', 'event-finish',
121 'event-summary', 'event-desc', 'event-location', 'event-type',
122 'event-nofinish', 'event-ignore', 'event-id'];
124 // All fields in the item table
125 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
126 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
127 'contact-id', 'wall', 'gravity', 'extid', 'psid',
128 'created', 'edited', 'commented', 'received', 'changed', 'verb',
129 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
130 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
131 'private', 'pubmail', 'visible', 'starred',
132 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
133 'title', 'content-warning', 'body', 'location', 'coord', 'app',
134 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
135 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
136 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
138 // List of all verbs that don't need additional content data.
139 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
141 Activity::LIKE, Activity::DISLIKE,
142 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
151 * Update existing item entries
153 * @param array $fields The fields that are to be changed
154 * @param array $condition The condition for finding the item entries
156 * In the future we may have to change permissions as well.
157 * Then we had to add the user id as third parameter.
159 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
161 * @return integer|boolean number of affected rows - or "false" if there was an error
162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
164 public static function update(array $fields, array $condition)
166 if (empty($condition) || empty($fields)) {
170 if (isset($fields['extid'])) {
171 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
174 if (!empty($fields['verb'])) {
175 $fields['vid'] = Verb::getID($fields['verb']);
178 if (!empty($fields['edited'])) {
179 $previous = Post::selectFirst(['edited'], $condition);
182 $rows = Post::update($fields, $condition);
183 if (is_bool($rows)) {
187 // We only need to call the line by line update for specific fields
188 if (empty($fields['body']) && empty($fields['file']) &&
189 empty($fields['attach']) && empty($fields['edited'])) {
193 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
195 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
199 while ($item = DBA::fetch($items)) {
200 if (!empty($fields['body'])) {
201 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
203 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
205 // Remove all media attachments from the body and store them in the post-media table
206 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
207 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
208 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
210 if ($item['author-network'] != Protocol::DFRN) {
211 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
214 Post\Content::update($item['uri-id'], $content_fields);
217 if (!empty($fields['file'])) {
218 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
221 if (!empty($fields['attach'])) {
222 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
225 // We only need to notfiy others when it is an original entry from us.
226 // Only call the notifier when the item had been edited and records had been changed.
227 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
228 $notify_items[] = $item['id'];
234 foreach ($notify_items as $notify_item) {
235 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
236 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
243 * Delete an item and notify others about it - if it was ours
245 * @param array $condition The condition for finding the item entries
246 * @param integer $priority Priority for the notification
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
252 $items = Post::select(['id'], $condition);
253 while ($item = Post::fetch($items)) {
254 self::markForDeletionById($item['id'], $priority);
260 * Delete an item for an user and notify others about it - if it was ours
262 * @param array $condition The condition for finding the item entries
263 * @param integer $uid User who wants to delete this item
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 public static function deleteForUser(array $condition, int $uid)
273 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
274 while ($item = Post::fetch($items)) {
275 if (in_array($item['uid'], [$uid, 0])) {
276 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
277 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
280 if ($item['uid'] == $uid) {
281 self::markForDeletionById($item['id'], PRIORITY_HIGH);
282 } elseif ($item['uid'] != 0) {
283 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
290 * Mark an item for deletion, delete related data and notify others about it - if it was ours
292 * @param integer $item_id
293 * @param integer $priority Priority for the notification
294 * @return boolean success
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
299 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
300 // locate item to be deleted
301 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
302 'deleted', 'resource-id', 'event-id',
303 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
304 $item = Post::selectFirst($fields, ['id' => $item_id]);
305 if (!DBA::isResult($item)) {
306 Logger::info('Item not found.', ['id' => $item_id]);
310 if ($item['deleted']) {
311 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
315 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
316 if (!DBA::isResult($parent)) {
317 $parent = ['origin' => false];
320 // clean up categories and tags so they don't end up as orphans
321 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
324 * If item is a link to a photo resource, nuke all the associated photos
325 * (visitors will not have photo resources)
326 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
327 * generate a resource-id and therefore aren't intimately linked to the item.
329 /// @TODO: this should first check if photo is used elsewhere
330 if (strlen($item['resource-id'])) {
331 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
334 // If item is a link to an event, delete the event.
335 if (intval($item['event-id'])) {
336 Event::delete($item['event-id']);
339 // If item has attachments, drop them
340 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
341 foreach($attachments as $attachment) {
342 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
343 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
347 // Set the item to "deleted"
348 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
349 Post::update($item_fields, ['id' => $item['id']]);
351 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
353 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
354 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
357 Post\DeliveryData::delete($item['uri-id']);
359 // If it's the parent of a comment thread, kill all the kids
360 if ($item['gravity'] == GRAVITY_PARENT) {
361 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
364 // Is it our comment and/or our thread?
365 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
366 // When we delete the original post we will delete all existing copies on the server as well
367 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
369 // send the notification upstream/downstream
371 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
373 } elseif ($item['uid'] != 0) {
374 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
375 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
378 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
384 * Get guid from given item record
386 * @param array $item Item record
387 * @param bool Whether to notify (?)
388 * @return string Guid
390 public static function guid(array $item, bool $notify): string
392 if (!empty($item['guid'])) {
393 return trim($item['guid']);
397 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
398 // We add the hash of our own host because our host is the original creator of the post.
399 $prefix_host = DI::baseUrl()->getHostname();
403 // We are only storing the post so we create a GUID from the original hostname.
404 if (!empty($item['author-link'])) {
405 $parsed = parse_url($item['author-link']);
406 if (!empty($parsed['host'])) {
407 $prefix_host = $parsed['host'];
411 if (empty($prefix_host) && !empty($item['plink'])) {
412 $parsed = parse_url($item['plink']);
413 if (!empty($parsed['host'])) {
414 $prefix_host = $parsed['host'];
418 if (empty($prefix_host) && !empty($item['uri'])) {
419 $parsed = parse_url($item['uri']);
420 if (!empty($parsed['host'])) {
421 $prefix_host = $parsed['host'];
425 // Is it in the format data@host.tld? - Used for mail contacts
426 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
427 $mailparts = explode('@', $item['author-link']);
428 $prefix_host = array_pop($mailparts);
432 if (!empty($item['plink'])) {
433 $guid = self::guidFromUri($item['plink'], $prefix_host);
434 } elseif (!empty($item['uri'])) {
435 $guid = self::guidFromUri($item['uri'], $prefix_host);
437 $guid = System::createUUID(hash('crc32', $prefix_host));
444 * Returns contact id from given item record
446 * @param array $item Item record
447 * @return int Contact id
449 private static function contactId(array $item): int
451 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
452 return $item['contact-id'];
453 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
454 return $item['contact-id'];
455 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
456 return $item['author-id'];
457 } elseif (!empty($item['contact-id'])) {
458 return $item['contact-id'];
460 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
461 if (!empty($contact_id)) {
465 return $item['author-id'];
469 * Write an item array into a spool file to be inserted later.
470 * This command is called whenever there are issues storing an item.
472 * @param array $item The item fields that are to be inserted
475 private static function spool(array $item)
477 // Now we store the data in the spool directory
478 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
479 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
481 $spoolpath = System::getSpoolPath();
482 if ($spoolpath != '') {
483 $spool = $spoolpath . '/' . $file;
485 file_put_contents($spool, json_encode($item));
486 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
491 * Check if the item array is a duplicate
493 * @param array $item Item record
494 * @return boolean is it a duplicate?
496 private static function isDuplicate(array $item): bool
498 // Checking if there is already an item with the same guid
499 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
500 if (Post::exists($condition)) {
501 Logger::notice('Found already existing item', $condition);
505 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
506 'network' => [$item['network'], Protocol::DFRN]];
507 if (Post::exists($condition)) {
508 Logger::notice('duplicated item with the same uri found.', $condition);
512 // On Friendica and Diaspora the GUID is unique
513 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
514 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
515 if (Post::exists($condition)) {
516 Logger::notice('duplicated item with the same guid found.', $condition);
519 } elseif ($item['network'] == Protocol::OSTATUS) {
520 // Check for an existing post with the same content. There seems to be a problem with OStatus.
521 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
522 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
523 if (Post::exists($condition)) {
524 Logger::notice('duplicated item with the same body found.', $item);
530 * Check for already added items.
531 * There is a timing issue here that sometimes creates double postings.
532 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
534 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
535 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
543 * Check if the item array is valid
545 * @param array $item Item record
546 * @return boolean item is valid
548 public static function isValid(array $item): bool
550 // When there is no content then we don't post it
551 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
552 Logger::notice('No body, no title.');
556 if (!empty($item['uid'])) {
557 $owner = User::getOwnerDataById($item['uid'], false);
559 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
563 if ($owner['account_expired'] || $owner['account_removed']) {
564 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']]);
569 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
570 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
574 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
575 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
579 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
580 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
584 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
585 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
589 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
593 if ($item['verb'] == Activity::FOLLOW) {
594 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
595 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
596 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
600 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
601 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
602 if (Post::exists($condition)) {
603 // It happens that we receive multiple follow requests by the same author - we only store one.
604 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
613 * Check if the item array is too old
615 * @param array $item Item record
616 * @return boolean item is too old
618 public static function isTooOld(array $item): bool
620 // check for create date and expire time
621 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
623 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
624 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
625 $expire_interval = $user['expire'];
628 if (($expire_interval > 0) && !empty($item['created'])) {
629 $expire_date = time() - ($expire_interval * 86400);
630 $created_date = strtotime($item['created']);
631 if ($created_date < $expire_date) {
632 Logger::notice('Item created before expiration interval.', [
633 'created' => date('c', $created_date),
634 'expired' => date('c', $expire_date),
645 * Return the id of the given item array if it has been stored before
647 * @param array $item Item record
648 * @return integer Item id or zero on error
650 private static function getDuplicateID(array $item): int
652 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
653 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
656 Protocol::ACTIVITYPUB,
661 $existing = Post::selectFirst(['id', 'network'], $condition);
662 if (DBA::isResult($existing)) {
663 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
664 if ($item['uid'] != 0) {
665 Logger::notice('Item already existed for user', [
666 'uri-id' => $item['uri-id'],
667 'uid' => $item['uid'],
668 'network' => $item['network'],
669 'existing_id' => $existing['id'],
670 'existing_network' => $existing['network']
674 return $existing['id'];
681 * Fetch top-level parent data for the given item array
684 * @return array item array with parent data
687 private static function getTopLevelParent(array $item): array
689 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
690 'uri-id', 'parent-uri-id',
691 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
692 'wall', 'private', 'origin', 'author-id'];
693 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
694 $params = ['order' => ['id' => false]];
695 $parent = Post::selectFirst($fields, $condition, $params);
697 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
698 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
699 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
700 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
703 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
704 $parent = Post::selectFirst($fields, $condition, $params);
708 if (!DBA::isResult($parent)) {
709 Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
713 if ($parent['uri-id'] == $parent['parent-uri-id']) {
717 $condition = ['uri-id' => $parent['parent-uri-id'],
718 'parent-uri-id' => $parent['parent-uri-id'],
719 'uid' => $parent['uid']];
720 $params = ['order' => ['id' => false]];
721 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
723 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
724 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
725 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
726 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
729 if (!DBA::isResult($toplevel_parent)) {
730 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
734 return $toplevel_parent;
738 * Get the gravity for the given item array
741 * @return integer gravity
743 private static function getGravity(array $item): int
745 $activity = DI::activity();
747 if (isset($item['gravity'])) {
748 return intval($item['gravity']);
749 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
750 return GRAVITY_PARENT;
751 } elseif ($activity->match($item['verb'], Activity::POST)) {
752 return GRAVITY_COMMENT;
753 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
754 return GRAVITY_ACTIVITY;
755 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
756 return GRAVITY_ACTIVITY;
759 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
760 return GRAVITY_UNKNOWN; // Should not happen
764 * Inserts item record
766 * @param array $item Item array to be inserted
767 * @param int $notify Notification (type?)
768 * @param bool $post_local (???)
769 * @return int Zero means error, otherwise primary key (id) is being returned
771 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
775 $priority = PRIORITY_HIGH;
777 // If it is a posting where users should get notifications, then define it as wall posting
781 $item['network'] = Protocol::DFRN;
782 $item['protocol'] = Conversation::PARCEL_DIRECT;
783 $item['direction'] = Conversation::PUSH;
785 if (is_int($notify) && in_array($notify, PRIORITIES)) {
789 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
792 $uid = intval($item['uid']);
794 $item['guid'] = self::guid($item, $notify);
795 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
798 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
800 // Backward compatibility: parent-uri used to be the direct parent uri.
801 // If it is provided without a thr-parent, it probably is the old behavior.
802 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
803 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
804 $item['parent-uri'] = $item['thr-parent'];
807 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
808 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
810 // Store conversation data
811 $source = $item['source'] ?? '';
812 unset($item['conversation-uri']);
813 unset($item['conversation-href']);
814 unset($item['source']);
817 * Do we already have this item?
818 * We have to check several networks since Friendica posts could be repeated
819 * via OStatus (maybe Diasporsa as well)
821 $duplicate = self::getDuplicateID($item);
826 // Additional duplicate checks
827 /// @todo Check why the first duplication check returns the item number and the second a 0
828 if (self::isDuplicate($item)) {
832 if (!isset($item['post-type'])) {
833 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
836 $item['wall'] = intval($item['wall'] ?? 0);
837 $item['extid'] = trim($item['extid'] ?? '');
838 $item['author-name'] = trim($item['author-name'] ?? '');
839 $item['author-link'] = trim($item['author-link'] ?? '');
840 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
841 $item['owner-name'] = trim($item['owner-name'] ?? '');
842 $item['owner-link'] = trim($item['owner-link'] ?? '');
843 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
844 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
845 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
846 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
847 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
848 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
849 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
850 $item['location'] = trim($item['location'] ?? '');
851 $item['coord'] = trim($item['coord'] ?? '');
852 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
853 $item['deleted'] = 0;
854 $item['verb'] = trim($item['verb'] ?? '');
855 $item['object-type'] = trim($item['object-type'] ?? '');
856 $item['object'] = trim($item['object'] ?? '');
857 $item['target-type'] = trim($item['target-type'] ?? '');
858 $item['target'] = trim($item['target'] ?? '');
859 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
860 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
861 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
862 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
863 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
864 $item['private'] = intval($item['private'] ?? self::PUBLIC);
865 $item['body'] = trim($item['body'] ?? '');
866 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
867 $item['app'] = trim($item['app'] ?? '');
868 $item['origin'] = intval($item['origin'] ?? 0);
869 $item['postopts'] = trim($item['postopts'] ?? '');
870 $item['resource-id'] = trim($item['resource-id'] ?? '');
871 $item['event-id'] = intval($item['event-id'] ?? 0);
872 $item['inform'] = trim($item['inform'] ?? '');
873 $item['file'] = trim($item['file'] ?? '');
875 // Communities aren't working with the Diaspora protoccol
876 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
877 $user = User::getById($uid, ['account-type']);
878 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
879 Logger::info('Community posts are not supported via Diaspora');
884 // Items cannot be stored before they happen ...
885 if ($item['created'] > DateTimeFormat::utcNow()) {
886 $item['created'] = DateTimeFormat::utcNow();
889 // We haven't invented time travel by now.
890 if ($item['edited'] > DateTimeFormat::utcNow()) {
891 $item['edited'] = DateTimeFormat::utcNow();
894 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
896 $item['gravity'] = self::getGravity($item);
898 $item['language'] = self::getLanguage($item);
900 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
901 'photo' => $item['author-avatar'], 'network' => $item['network']];
902 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
904 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
905 'photo' => $item['owner-avatar'], 'network' => $item['network']];
906 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
908 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
909 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
910 $item['post-reason'] = self::PR_FOLLOWER;
913 if ($item['origin'] && empty($item['post-reason'])) {
914 $item['post-reason'] = self::PR_LOCAL;
917 // Ensure that there is an avatar cache
918 Contact::checkAvatarCache($item['author-id']);
919 Contact::checkAvatarCache($item['owner-id']);
921 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
922 $item['contact-id'] = self::contactId($item);
924 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
925 empty($item['origin']) && self::isTooOld($item)) {
926 Logger::info('Item is too old', ['item' => $item]);
930 if (!self::isValid($item)) {
934 if ($item['gravity'] !== GRAVITY_PARENT) {
935 $toplevel_parent = self::getTopLevelParent($item);
936 if (empty($toplevel_parent)) {
940 // If the thread originated from this node, we check the permission against the thread starter
941 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
942 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
943 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
947 $parent_id = $toplevel_parent['id'];
948 $item['parent-uri'] = $toplevel_parent['uri'];
949 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
950 $item['deleted'] = $toplevel_parent['deleted'];
952 // Reshares have to keep their permissions to allow forums to work
953 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
954 $item['allow_cid'] = $toplevel_parent['allow_cid'];
955 $item['allow_gid'] = $toplevel_parent['allow_gid'];
956 $item['deny_cid'] = $toplevel_parent['deny_cid'];
957 $item['deny_gid'] = $toplevel_parent['deny_gid'];
960 $parent_origin = $toplevel_parent['origin'];
962 // Don't federate received participation messages
963 if ($item['verb'] != Activity::FOLLOW) {
964 $item['wall'] = $toplevel_parent['wall'];
966 $item['wall'] = false;
967 // Participations are technical messages, so they are set to "seen" automatically
968 $item['unseen'] = false;
972 * If the parent is private, force privacy for the entire conversation
973 * This differs from the above settings as it subtly allows comments from
974 * email correspondents to be private even if the overall thread is not.
976 if ($toplevel_parent['private']) {
977 $item['private'] = $toplevel_parent['private'];
980 // If its a post that originated here then tag the thread as "mention"
981 if ($item['origin'] && $item['uid']) {
982 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
983 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
986 // Update the contact relations
987 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
990 $parent_origin = $item['origin'];
992 if ($item['wall'] && empty($item['conversation'])) {
993 $item['conversation'] = $item['parent-uri'] . '#context';
997 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
998 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1000 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1001 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1004 // Is this item available in the global items (with uid=0)?
1005 if ($item['uid'] == 0) {
1006 $item['global'] = true;
1008 // Set the global flag on all items if this was a global item entry
1009 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1011 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1015 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1016 $item['private'] = self::PRIVATE;
1019 if ($notify && $post_local) {
1020 $item['edit'] = false;
1021 $item['parent'] = $parent_id;
1023 // Trigger automatic reactions for addons
1024 if (!isset($item['api_source'])) {
1025 $item['api_source'] = true;
1028 // We have to tell the hooks who we are - this really should be improved
1029 if (!local_user()) {
1030 $_SESSION['authenticated'] = true;
1031 $_SESSION['uid'] = $uid;
1032 $dummy_session = true;
1034 $dummy_session = false;
1037 Hook::callAll('post_local', $item);
1039 if ($dummy_session) {
1040 unset($_SESSION['authenticated']);
1041 unset($_SESSION['uid']);
1043 } elseif (!$notify) {
1044 Hook::callAll('post_remote', $item);
1047 if (!empty($item['cancel'])) {
1048 Logger::notice('post cancelled by addon.');
1052 if (empty($item['vid']) && !empty($item['verb'])) {
1053 $item['vid'] = Verb::getID($item['verb']);
1056 // Creates or assigns the permission set
1057 $item['psid'] = DI::permissionSet()->selectOrCreate(
1058 DI::permissionSetFactory()->createFromString(
1066 if (!empty($item['extid'])) {
1067 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1070 if ($item['verb'] == Activity::ANNOUNCE) {
1071 self::setOwnerforResharedItem($item);
1074 if (isset($item['attachments'])) {
1075 foreach ($item['attachments'] as $attachment) {
1076 $attachment['uri-id'] = $item['uri-id'];
1077 Post\Media::insert($attachment);
1079 unset($item['attachments']);
1082 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1084 // Remove all media attachments from the body and store them in the post-media table
1085 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1086 $item['raw-body'] = self::setHashtags($item['raw-body']);
1088 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1089 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1092 // Check for hashtags in the body and repair or add hashtag links
1093 $item['body'] = self::setHashtags($item['body']);
1095 if (stristr($item['verb'], Activity::POKE)) {
1096 $notify_type = Delivery::POKE;
1098 $notify_type = Delivery::POST;
1101 // Filling item related side tables
1102 if (!empty($item['attach'])) {
1103 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1106 if (empty($item['event-id'])) {
1107 unset($item['event-id']);
1109 $ev = Event::fromBBCode($item['body']);
1110 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1111 Logger::info('Event found.');
1112 $ev['cid'] = $item['contact-id'];
1113 $ev['uid'] = $item['uid'];
1114 $ev['uri'] = $item['uri'];
1115 $ev['edited'] = $item['edited'];
1116 $ev['private'] = $item['private'];
1117 $ev['guid'] = $item['guid'];
1118 $ev['plink'] = $item['plink'];
1119 $ev['network'] = $item['network'];
1120 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1121 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1122 $ev['source'] = $item['source'] ?? '';
1124 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1125 if (DBA::isResult($event)) {
1126 $ev['id'] = $event['id'];
1129 $event_id = Event::store($ev);
1130 $item = Event::getItemArrayForImportedId($event_id, $item);
1132 Logger::info('Event was stored', ['id' => $event_id]);
1136 if (empty($item['causer-id'])) {
1137 unset($item['causer-id']);
1140 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1141 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1142 if (!empty($content_warning) && empty($item['content-warning'])) {
1143 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1147 Post::insert($item['uri-id'], $item);
1149 if ($item['gravity'] == GRAVITY_PARENT) {
1150 Post\Thread::insert($item['uri-id'], $item);
1153 if (!in_array($item['verb'], self::ACTIVITIES)) {
1154 Post\Content::insert($item['uri-id'], $item);
1157 // Create Diaspora signature
1158 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1159 $signed = Diaspora::createCommentSignature($item);
1160 if (!empty($signed)) {
1161 $item['diaspora_signed_text'] = json_encode($signed);
1165 if (!empty($item['diaspora_signed_text'])) {
1166 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1169 // Attached file links
1170 if (!empty($item['file'])) {
1171 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1174 // Delivery relevant data
1175 $delivery_data = Post\DeliveryData::extractFields($item);
1177 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1178 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1181 // Store tags from the body if this hadn't been handled previously in the protocol classes
1182 if (!Tag::existsForPost($item['uri-id'])) {
1183 Tag::storeFromBody($item['uri-id'], $item['body']);
1186 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1187 if (Post::exists($condition)) {
1188 Logger::notice('Item is already inserted - aborting', $condition);
1192 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1193 if (!$post_user_id) {
1194 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1198 if ($item['gravity'] == GRAVITY_PARENT) {
1199 $item['post-user-id'] = $post_user_id;
1200 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1203 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1205 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1206 if (!DBA::isResult($posted_item)) {
1207 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1208 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1209 self::spool($orig_item);
1213 // update the commented timestamp on the parent
1214 if (DI::config()->get('system', 'like_no_comment')) {
1215 // Update when it is a comment
1216 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1218 // Update when it isn't a follow or tag verb
1219 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1222 if ($update_commented) {
1223 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1225 $fields = ['changed' => DateTimeFormat::utcNow()];
1228 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1230 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1231 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1232 // Get the user information for the logging
1233 $user = User::getById($uid);
1235 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1240 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1241 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1243 Hook::callAll('post_local_end', $posted_item);
1245 Hook::callAll('post_remote_end', $posted_item);
1248 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1249 self::addShadow($post_user_id);
1251 self::addShadowPost($post_user_id);
1254 self::updateContact($posted_item);
1256 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1258 // Distribute items to users who subscribed to their tags
1259 self::distributeByTags($posted_item);
1261 // Automatically reshare the item if the "remote_self" option is selected
1262 self::autoReshare($posted_item);
1264 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1267 // Don't relay participation messages
1268 if (($posted_item['verb'] == Activity::FOLLOW) &&
1269 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1270 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1276 if (!empty($source)) {
1277 Post\Activity::insert($item['uri-id'], $source);
1279 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1282 // Fill the cache with the rendered content.
1283 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1284 self::updateDisplayCache($posted_item['uri-id']);
1287 if ($posted_item['origin'] && ($posted_item['uid'] != 0) && in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
1288 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_OUTBOX . $posted_item['uid']);
1291 return $post_user_id;
1295 * Update the display cache
1297 * @param integer $uri_id
1300 public static function updateDisplayCache(int $uri_id)
1302 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1303 self::prepareBody($item, false, false, true);
1307 * Change the owner of a parent item if it had been shared by a forum
1309 * (public) forum posts in the new format consist of the regular post by the author
1310 * followed by an announce message sent from the forum account.
1311 * Changing the owner helps in grouping forum posts.
1313 * @param array $item
1316 private static function setOwnerforResharedItem(array $item)
1318 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1319 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1320 if (!DBA::isResult($parent)) {
1321 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1325 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1326 if (!DBA::isResult($author)) {
1327 Logger::error('Author not found', ['id' => $item['author-id']]);
1331 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1332 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1334 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1335 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1336 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1340 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1341 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1342 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']]);
1346 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1347 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1352 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1353 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1357 * Distribute the given item to users who subscribed to their tags
1359 * @param array $item Processed item
1361 private static function distributeByTags(array $item)
1363 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1367 $uids = Tag::getUIDListByURIId($item['uri-id']);
1368 foreach ($uids as $uid) {
1369 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1370 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1375 * Distributes public items to the receivers
1377 * @param integer $itemid Item ID that should be added
1378 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1379 * @throws \Exception
1381 public static function distribute(int $itemid, string $signed_text = '')
1383 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1384 $parent = Post::selectFirst(['owner-id'], $condition);
1385 if (!DBA::isResult($parent)) {
1386 Logger::warning('Item not found', ['condition' => $condition]);
1390 // Only distribute public items from native networks
1391 $condition = ['id' => $itemid, 'uid' => 0,
1392 'network' => array_merge(Protocol::FEDERATED ,['']),
1393 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1394 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1395 if (!DBA::isResult($item)) {
1396 Logger::warning('Item not found', ['condition' => $condition]);
1400 $origin = $item['origin'];
1404 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1405 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1406 if (!DBA::isResult($owner)) {
1410 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1411 $contacts = DBA::select('contact', ['uid'], $condition);
1412 while ($contact = DBA::fetch($contacts)) {
1413 if ($contact['uid'] == 0) {
1417 $users[$contact['uid']] = $contact['uid'];
1419 DBA::close($contacts);
1421 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1422 $contacts = DBA::select('contact', ['uid'], $condition);
1423 while ($contact = DBA::fetch($contacts)) {
1424 if ($contact['uid'] == 0) {
1428 $users[$contact['uid']] = $contact['uid'];
1430 DBA::close($contacts);
1432 if (!empty($owner['alias'])) {
1433 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1434 $contacts = DBA::select('contact', ['uid'], $condition);
1435 while ($contact = DBA::fetch($contacts)) {
1436 if ($contact['uid'] == 0) {
1440 $users[$contact['uid']] = $contact['uid'];
1442 DBA::close($contacts);
1447 if ($item['uri-id'] != $item['parent-uri-id']) {
1448 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1449 while ($parent = Post::fetch($parents)) {
1450 $users[$parent['uid']] = $parent['uid'];
1451 if ($parent['origin'] && !$origin) {
1452 $origin_uid = $parent['uid'];
1455 DBA::close($parents);
1458 foreach ($users as $uid) {
1459 if ($origin_uid == $uid) {
1460 $item['diaspora_signed_text'] = $signed_text;
1462 $item['post-reason'] = self::PR_DISTRIBUTE;
1463 self::storeForUser($item, $uid);
1468 * Store a public item defined by their URI-ID for the given users
1470 * @param integer $uri_id URI-ID of the given item
1471 * @param integer $uid The user that will receive the item entry
1472 * @param array $fields Additional fields to be stored
1473 * @param integer $source_uid User id of the source post
1474 * @return integer stored item id
1476 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1478 if ($uid == $source_uid) {
1479 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1483 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1484 if (!DBA::isResult($item)) {
1485 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1489 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1490 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']]);
1494 $item['post-reason'] = self::PR_STORED;
1496 $item = array_merge($item, $fields);
1498 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1500 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1501 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1502 !Contact::isSharingByURL($item['author-link'], $uid) &&
1503 !Contact::isSharingByURL($item['owner-link'], $uid)) {
1504 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1508 if (($uri_id != $item['thr-parent-id']) && (($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1509 // Fetch the origin user for the post
1510 $origin_uid = self::GetOriginUidForUriId($item['thr-parent-id'], $uid);
1511 if (is_null($origin_uid)) {
1512 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $item['thr-parent-id']]);
1516 $causer = $item['causer-id'] ?: $item['author-id'];
1517 $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1518 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1521 $stored = self::storeForUser($item, $uid);
1522 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1527 * Returns the origin uid of a post if the given user is allowed to see it.
1533 private static function GetOriginUidForUriId(int $uriid, int $uid)
1535 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1539 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1540 if (!empty($post)) {
1541 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1542 return $post['uid'];
1545 $pcid = Contact::getPublicIdByUserId($uid);
1550 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1551 if ($receiver == $pcid) {
1552 return $post['uid'];
1559 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1563 // When the post belongs to a a forum then all forum users are allowed to access it
1564 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1565 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1566 $target_uid = User::getIdForURL($tag['url']);
1567 if (!empty($target_uid)) {
1577 * Store a public item array for the given users
1579 * @param array $item The item entry that will be stored
1580 * @param integer $uid The user that will receive the item entry
1581 * @return integer stored item id
1582 * @throws \Exception
1584 private static function storeForUser(array $item, int $uid): int
1586 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1587 if (!empty($item['event-id'])) {
1588 $post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1589 if (!empty($post['event-id'])) {
1590 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1591 if (!empty($event)) {
1592 // We aren't using "Event::store" here, since we don't want to trigger any further action
1593 $ret = DBA::update('event', $event, ['id' => $post['event-id']]);
1594 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $post['event-id'], 'ret' => $ret]);
1598 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1602 // Data from the "post-user" table
1604 unset($item['mention']);
1605 unset($item['starred']);
1606 unset($item['unseen']);
1607 unset($item['psid']);
1608 unset($item['pinned']);
1609 unset($item['ignored']);
1610 unset($item['pubmail']);
1611 unset($item['event-id']);
1612 unset($item['hidden']);
1613 unset($item['notification-type']);
1615 // Data from the "post-delivery-data" table
1616 unset($item['postopts']);
1617 unset($item['inform']);
1619 $item['uid'] = $uid;
1620 $item['origin'] = 0;
1623 if ($item['gravity'] == GRAVITY_PARENT) {
1624 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1626 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1629 if (!empty($contact['id'])) {
1630 $item['contact-id'] = $contact['id'];
1632 // Shouldn't happen at all
1633 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1634 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1635 if (!DBA::isResult($self)) {
1636 // Shouldn't happen even less
1637 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1640 $item['contact-id'] = $self['id'];
1644 if ($item['gravity'] == GRAVITY_PARENT) {
1645 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1646 if (DBA::isResult($contact)) {
1647 $notify = self::isRemoteSelf($contact, $item);
1651 $distributed = self::insert($item, $notify);
1653 if (!$distributed) {
1654 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1656 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1658 return $distributed;
1662 * Add a shadow entry for a given item id that is a thread starter
1664 * We store every public item entry additionally with the user id "0".
1665 * This is used for the community page and for the search.
1666 * It is planned that in the future we will store public item entries only once.
1668 * @param integer $itemid Item ID that should be added
1669 * @throws \Exception
1671 private static function addShadow(int $itemid)
1673 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1674 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1675 $item = Post::selectFirst($fields, $condition);
1677 if (!DBA::isResult($item)) {
1681 // is it already a copy?
1682 if (($itemid == 0) || ($item['uid'] == 0)) {
1686 // Is it a visible public post?
1687 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1691 // is it an entry from a connector? Only add an entry for natively connected networks
1692 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1696 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1700 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1702 if (DBA::isResult($item)) {
1703 // Preparing public shadow (removing user specific data)
1706 unset($item['parent']);
1707 unset($item['wall']);
1708 unset($item['mention']);
1709 unset($item['origin']);
1710 unset($item['starred']);
1711 unset($item['postopts']);
1712 unset($item['inform']);
1713 unset($item['post-reason']);
1714 if ($item['uri-id'] == $item['parent-uri-id']) {
1715 $item['contact-id'] = $item['owner-id'];
1717 $item['contact-id'] = $item['author-id'];
1720 $public_shadow = self::insert($item);
1722 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1727 * Add a shadow entry for a given item id that is a comment
1729 * This function does the same like the function above - but for comments
1731 * @param integer $itemid Item ID that should be added
1732 * @throws \Exception
1734 private static function addShadowPost(int $itemid)
1736 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1737 if (!DBA::isResult($item)) {
1741 // Is it a toplevel post?
1742 if ($item['gravity'] == GRAVITY_PARENT) {
1743 self::addShadow($itemid);
1747 // Is this a shadow entry?
1748 if ($item['uid'] == 0) {
1752 // Is there a shadow parent?
1753 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1757 // Is there already a shadow entry?
1758 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1762 // Save "origin" and "parent" state
1763 $origin = $item['origin'];
1764 $parent = $item['parent'];
1766 // Preparing public shadow (removing user specific data)
1769 unset($item['parent']);
1770 unset($item['wall']);
1771 unset($item['mention']);
1772 unset($item['origin']);
1773 unset($item['starred']);
1774 unset($item['postopts']);
1775 unset($item['inform']);
1776 unset($item['post-reason']);
1777 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1779 $public_shadow = self::insert($item);
1781 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1783 // If this was a comment to a Diaspora post we don't get our comment back.
1784 // This means that we have to distribute the comment by ourselves.
1785 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1786 self::distribute($public_shadow);
1791 * Adds a language specification in a "language" element of given $arr.
1792 * Expects "body" element to exist in $arr.
1794 * @param array $item
1795 * @return string detected language
1796 * @throws \Text_LanguageDetect_Exception
1798 private static function getLanguage(array $item): string
1800 if (!empty($item['language'])) {
1801 return $item['language'];
1804 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1808 // Convert attachments to links
1809 $naked_body = BBCode::removeAttachment($item['body']);
1810 if (empty($naked_body)) {
1814 // Remove links and pictures
1815 $naked_body = BBCode::removeLinks($naked_body);
1817 // Convert the title and the body to plain text
1818 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1820 // Remove possibly remaining links
1821 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1823 if (empty($naked_body)) {
1827 $availableLanguages = DI::l10n()->getAvailableLanguages();
1828 // See https://github.com/friendica/friendica/issues/10511
1829 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1830 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1831 $availableLanguages['fa'] = 'fa';
1833 $ld = new Language(array_keys($availableLanguages));
1834 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1835 if (is_array($languages)) {
1836 return json_encode($languages);
1842 public static function getLanguageMessage(array $item): string
1844 $iso639 = new \Matriphe\ISO639\ISO639;
1846 $used_languages = '';
1847 foreach (json_decode($item['language'], true) as $language => $reliability) {
1848 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1850 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1851 return $used_languages;
1855 * Creates an unique guid out of a given uri.
1856 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1857 * Posts that are created on this system are using System::createUUID.
1858 * Received ActivityPub posts are using Processor::getGUIDByURL.
1860 * @param string $uri uri of an item entry
1861 * @param string|null $host hostname for the GUID prefix
1862 * @return string Unique guid
1864 public static function guidFromUri(string $uri, string $host = null): string
1866 // Our regular guid routine is using this kind of prefix as well
1867 // We have to avoid that different routines could accidentally create the same value
1868 $parsed = parse_url($uri);
1870 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1871 unset($parsed['scheme']);
1873 // Glue it together to be able to make a hash from it
1874 $host_id = implode('/', $parsed);
1876 // Use a mixture of several hashes to provide some GUID like experience
1877 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1881 * generate an unique URI
1883 * @param string $guid An existing GUID (Otherwise it will be generated)
1886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1888 public static function newURI(string $guid = ''): string
1891 $guid = System::createUUID();
1894 return DI::baseUrl()->get() . '/objects/' . $guid;
1898 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1900 * This can be used to filter for inactive contacts.
1901 * Only do this for public postings to avoid privacy problems, since poco data is public.
1902 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1904 * @param array $arr Contains the just posted item record
1905 * @throws \Exception
1907 private static function updateContact(array $arr)
1909 // Unarchive the author
1910 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1911 if (DBA::isResult($contact)) {
1912 Contact::unmarkForArchival($contact);
1915 // Unarchive the contact if it's not our own contact
1916 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1917 if (DBA::isResult($contact)) {
1918 Contact::unmarkForArchival($contact);
1921 /// @todo On private posts we could obfuscate the date
1922 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1924 // Is it a forum? Then we don't care about the rules from above
1925 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1926 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1932 // The "self" contact id is used (for example in the connectors) when the contact is unknown
1933 // So we have to ensure to only update the last item when it had been our own post,
1934 // or it had been done by a "regular" contact.
1935 if (!empty($arr['wall'])) {
1936 $condition = ['id' => $arr['contact-id']];
1938 $condition = ['id' => $arr['contact-id'], 'self' => false];
1940 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1942 // Now do the same for the system wide contacts with uid=0
1943 if ($arr['private'] != self::PRIVATE) {
1944 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1945 ['id' => $arr['owner-id']]);
1947 if ($arr['owner-id'] != $arr['author-id']) {
1948 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1949 ['id' => $arr['author-id']]);
1954 public static function setHashtags(string $body): string
1956 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1957 $tags = BBCode::getTags($body);
1960 if (!count($tags)) {
1964 // This sorting is important when there are hashtags that are part of other hashtags
1965 // Otherwise there could be problems with hashtags like #test and #test2
1966 // Because of this we are sorting from the longest to the shortest tag.
1967 usort($tags, function ($a, $b) {
1968 return strlen($b) <=> strlen($a);
1971 $URLSearchString = "^\[\]";
1973 // All hashtags should point to the home server if "local_tags" is activated
1974 if (DI::config()->get('system', 'local_tags')) {
1975 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1976 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1979 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1980 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1982 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1985 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1987 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1990 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1992 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1995 // Repair recursive urls
1996 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1999 foreach ($tags as $tag) {
2000 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2004 $basetag = str_replace('_', ' ', substr($tag, 1));
2005 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2007 $body = str_replace($tag, $newtag, $body);
2010 // Convert back the masked hashtags
2011 $body = str_replace("#", "#", $body);
2020 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2023 * @param int $item_id
2024 * @return boolean true if item was deleted, else false
2025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2026 * @throws \ImagickException
2028 private static function tagDeliver(int $uid, int $item_id): bool
2032 $owner = User::getOwnerDataById($uid);
2033 if (!DBA::isResult($owner)) {
2034 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2038 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2039 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2043 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
2044 if (!DBA::isResult($item)) {
2045 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2049 if ($item['gravity'] == GRAVITY_PARENT) {
2050 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2051 foreach ($tags as $tag) {
2052 if (Strings::compareLink($owner['url'], $tag['url'])) {
2054 Logger::info('Mention found in tag.', ['url' => $tag['url'], 'uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2059 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2060 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2064 $arr = ['item' => $item, 'user' => $owner];
2066 Hook::callAll('tagged', $arr);
2068 $tags = Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2069 foreach ($tags as $tag) {
2070 if (Strings::compareLink($owner['url'], $tag['url'])) {
2072 Logger::info('Mention found in parent tag.', ['url' => $tag['url'], 'uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2077 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2082 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2084 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2086 $allow_gid = '<' . Group::FOLLOWERS . '>';
2089 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2091 self::performActivity($item['id'], 'announce', $uid);
2094 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2099 * Automatically reshare the item if the "remote_self" option is selected
2101 * @param array $item
2104 private static function autoReshare(array $item)
2106 if ($item['gravity'] != GRAVITY_PARENT) {
2110 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2114 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2118 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2120 self::performActivity($item['id'], 'announce', $item['uid']);
2123 public static function isRemoteSelf(array $contact, array &$datarray): bool
2125 if (!$contact['remote_self']) {
2129 // Prevent the forwarding of posts that are forwarded
2130 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2131 Logger::info('Already forwarded');
2135 // Prevent to forward already forwarded posts
2136 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2137 Logger::info('Already forwarded (second test)');
2141 // Only forward posts
2142 if ($datarray["verb"] != Activity::POST) {
2143 Logger::info('No post');
2147 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2148 Logger::info('Not public');
2152 $datarray2 = $datarray;
2153 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2154 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2155 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2156 ['uid' => $contact['uid'], 'self' => true]);
2157 if (DBA::isResult($self)) {
2158 $datarray['contact-id'] = $self["id"];
2160 $datarray['owner-name'] = $self["name"];
2161 $datarray['owner-link'] = $self["url"];
2162 $datarray['owner-avatar'] = $self["thumb"];
2164 $datarray['author-name'] = $datarray['owner-name'];
2165 $datarray['author-link'] = $datarray['owner-link'];
2166 $datarray['author-avatar'] = $datarray['owner-avatar'];
2168 unset($datarray['edited']);
2170 unset($datarray['network']);
2171 unset($datarray['owner-id']);
2172 unset($datarray['author-id']);
2175 if ($contact['network'] != Protocol::FEED) {
2176 $old_uri_id = $datarray["uri-id"] ?? 0;
2177 $datarray["guid"] = System::createUUID();
2178 unset($datarray["plink"]);
2179 $datarray["uri"] = self::newURI($datarray["guid"]);
2180 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2181 $datarray["extid"] = Protocol::DFRN;
2182 $urlpart = parse_url($datarray2['author-link']);
2183 $datarray["app"] = $urlpart["host"];
2184 if (!empty($old_uri_id)) {
2185 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2188 unset($datarray["parent-uri"]);
2189 unset($datarray["thr-parent"]);
2191 $datarray['private'] = self::PUBLIC;
2195 if ($contact['network'] != Protocol::FEED) {
2196 // Store the original post
2197 $result = self::insert($datarray2);
2198 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2200 $datarray["app"] = "Feed";
2204 return (bool)$result;
2211 * @param array $item
2214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2215 * @throws \ImagickException
2217 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2219 if (DI::config()->get('system', 'disable_embedded')) {
2223 Logger::info('check for photos');
2224 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2229 $img_start = strpos($orig_body, '[img');
2230 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2231 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2233 while (($img_st_close !== false) && ($img_len !== false)) {
2234 $img_st_close++; // make it point to AFTER the closing bracket
2235 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2237 Logger::info('found photo', ['image' => $image]);
2239 if (stristr($image, $site . '/photo/')) {
2240 // Only embed locally hosted photos
2242 $i = basename($image);
2243 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2244 $x = strpos($i, '-');
2247 $res = substr($i, $x + 1);
2248 $i = substr($i, 0, $x);
2249 $photo = Photo::getPhotoForUser($uid, $i, $res);
2250 if (DBA::isResult($photo)) {
2252 * Check to see if we should replace this photo link with an embedded image
2253 * 1. No need to do so if the photo is public
2254 * 2. If there's a contact-id provided, see if they're in the access list
2255 * for the photo. If so, embed it.
2256 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2257 * permissions, regardless of order but first check to see if they're an exact
2258 * match to save some processing overhead.
2260 if (self::hasPermissions($photo)) {
2262 $recips = self::enumeratePermissions($photo);
2263 if (in_array($cid, $recips)) {
2267 if (self::samePermissions($uid, $item, $photo)) {
2273 $photo_img = Photo::getImageForPhoto($photo);
2274 // If a custom width and height were specified, apply before embedding
2275 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2276 Logger::info('scaling photo');
2278 $width = intval($match[1]);
2279 $height = intval($match[2]);
2281 $photo_img->scaleDown(max($width, $height));
2284 $data = $photo_img->asString();
2285 $type = $photo_img->getType();
2287 Logger::info('replacing photo');
2288 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2289 Logger::debug('replaced', ['image' => $image]);
2295 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2296 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2297 if ($orig_body === false) {
2301 $img_start = strpos($orig_body, '[img');
2302 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2303 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2306 $new_body = $new_body . $orig_body;
2311 private static function hasPermissions(array $obj)
2313 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2314 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2317 // @TODO $uid is unused parameter
2318 private static function samePermissions($uid, array $obj1, array $obj2): bool
2320 // first part is easy. Check that these are exactly the same.
2321 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2322 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2323 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2324 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2328 // This is harder. Parse all the permissions and compare the resulting set.
2329 $recipients1 = self::enumeratePermissions($obj1);
2330 $recipients2 = self::enumeratePermissions($obj2);
2334 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2335 return ($recipients1 == $recipients2);
2339 * Returns an array of contact-ids that are allowed to see this object
2341 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2342 * @param bool $check_dead Prunes unavailable contacts from the result
2344 * @throws \Exception
2346 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2348 $aclFormater = DI::aclFormatter();
2350 $allow_people = $aclFormater->expand($obj['allow_cid']);
2351 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2352 $deny_people = $aclFormater->expand($obj['deny_cid']);
2353 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2354 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2355 $deny = array_unique(array_merge($deny_people, $deny_groups));
2356 $recipients = array_diff($recipients, $deny);
2360 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2362 if (!$uid || ($days < 1)) {
2366 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2367 $uid, GRAVITY_PARENT];
2370 * $expire_network_only = save your own wall posts
2371 * and just expire conversations started by others
2373 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2375 if ($expire_network_only) {
2376 $condition[0] .= " AND NOT `wall`";
2379 if ($network != "") {
2380 $condition[0] .= " AND `network` = ?";
2381 $condition[] = $network;
2384 $condition[0] .= " AND `received` < ?";
2385 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2387 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2389 if (!DBA::isResult($items)) {
2393 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2395 // Forcing expiring of items - but not notes and marked items
2397 $expire_items = true;
2400 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2401 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2402 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2406 $priority = DI::config()->get('system', 'expire-notify-priority');
2408 while ($item = Post::fetch($items)) {
2409 // don't expire filed items
2410 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2414 // Only expire posts, not photos and photo comments
2416 if (!$expire_photos && !empty($item['resource-id'])) {
2418 } elseif (!$expire_starred && intval($item['starred'])) {
2420 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2422 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2426 self::markForDeletionById($item['id'], $priority);
2431 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2434 public static function firstPostDate(int $uid, bool $wall = false)
2436 $user = User::getById($uid, ['register_date']);
2441 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2442 $uid, $wall, $user['register_date']];
2443 $params = ['order' => ['received' => false]];
2444 $thread = Post::selectFirstThread(['received'], $condition, $params);
2445 if (DBA::isResult($thread)) {
2446 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2453 * add/remove activity to an item
2455 * Toggle activities as like,dislike,attend of an item
2457 * @param int $item_id
2458 * @param string $verb
2459 * Activity verb. One of
2460 * like, unlike, dislike, undislike, attendyes, unattendyes,
2461 * attendno, unattendno, attendmaybe, unattendmaybe,
2462 * announce, unannouce
2464 * @param string $allow_cid
2465 * @param string $allow_gid
2466 * @param string $deny_cid
2467 * @param string $deny_gid
2469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2470 * @throws \ImagickException
2471 * @hook 'post_local_end'
2473 * 'post_id' => ID of posted item
2475 public static function performActivity(int $item_id, string $verb, int $uid, string $allow_cid = null, string $allow_gid = null, string $deny_cid = null, string $deny_gid = null): bool
2481 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2483 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2484 if (!DBA::isResult($item)) {
2485 Logger::notice('like: unknown item', ['id' => $item_id]);
2489 $uri_id = $item['uri-id'];
2491 if (!in_array($item['uid'], [0, $uid])) {
2495 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2496 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2497 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2498 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2499 if (!DBA::isResult($item)) {
2500 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2506 // Retrieves the local post owner
2507 $owner = User::getOwnerDataById($uid);
2508 if (empty($owner)) {
2509 Logger::info('Empty owner for user', ['uid' => $uid]);
2513 // Retrieve the current logged in user's public contact
2514 $author_id = Contact::getIdForURL($owner['url']);
2515 if (empty($author_id)) {
2516 Logger::info('Empty public contact');
2524 $activity = Activity::LIKE;
2528 $activity = Activity::DISLIKE;
2532 $activity = Activity::ATTEND;
2536 $activity = Activity::ATTENDNO;
2539 case 'unattendmaybe':
2540 $activity = Activity::ATTENDMAYBE;
2544 $activity = Activity::FOLLOW;
2548 $activity = Activity::ANNOUNCE;
2551 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2555 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2557 // Enable activity toggling instead of on/off
2558 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2560 // Look for an existing verb row
2561 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2562 if ($event_verb_flag) {
2563 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2565 // Translate to the index based activity index
2567 foreach ($verbs as $verb) {
2568 $vids[] = Verb::getID($verb);
2571 $vids = Verb::getID($activity);
2574 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2575 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2576 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2578 if (DBA::isResult($like_item)) {
2580 * Truth table for existing activities
2582 * | Inputs || Outputs |
2583 * |----------------------------||-------------------|
2584 * | Mode | Event | Same verb || Delete? | Return? |
2585 * |--------|-------|-----------||---------|---------|
2586 * | create | Yes | Yes || No | Yes |
2587 * | create | Yes | No || Yes | No |
2588 * | create | No | Yes || No | Yes |
2589 * | create | No | No || N/A†|
2590 * | delete | Yes | Yes || Yes | N/A‡ |
2591 * | delete | Yes | No || No | N/A‡ |
2592 * | delete | No | Yes || Yes | N/A‡ |
2593 * | delete | No | No || N/A†|
2594 * |--------|-------|-----------||---------|---------|
2595 * | A | B | C || A xor C | !B or C |
2597 * †Can't happen: It's impossible to find an existing non-event activity without
2598 * the same verb because we are only looking for this single verb.
2600 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2602 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2603 self::markForDeletionById($like_item['id']);
2606 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2611 // No need to go further if we aren't creating anything
2612 if ($mode == 'delete') {
2616 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2619 'guid' => System::createUUID(),
2620 'uri' => self::newURI(),
2621 'uid' => $item['uid'],
2622 'contact-id' => $owner['id'],
2623 'wall' => $item['wall'],
2625 'network' => Protocol::DFRN,
2626 'protocol' => Conversation::PARCEL_DIRECT,
2627 'direction' => Conversation::PUSH,
2628 'gravity' => GRAVITY_ACTIVITY,
2629 'parent' => $item['id'],
2630 'thr-parent' => $item['uri'],
2631 'owner-id' => $author_id,
2632 'author-id' => $author_id,
2633 'body' => $activity,
2634 'verb' => $activity,
2635 'object-type' => $objtype,
2636 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2637 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2638 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2639 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2644 $signed = Diaspora::createLikeSignature($uid, $new_item);
2645 if (!empty($signed)) {
2646 $new_item['diaspora_signed_text'] = json_encode($signed);
2649 $new_item_id = self::insert($new_item);
2651 // If the parent item isn't visible then set it to visible
2652 if (!$item['visible']) {
2653 self::update(['visible' => true], ['id' => $item['id']]);
2656 $new_item['id'] = $new_item_id;
2658 Hook::callAll('post_local_end', $new_item);
2664 * Fetch the SQL condition for the given user id
2666 * @param integer $owner_id User ID for which the permissions should be fetched
2667 * @return array condition
2669 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2671 $local_user = local_user();
2672 $remote_user = Session::getRemoteContactID($owner_id);
2674 // default permissions - anonymous user
2675 $condition = ["`private` != ?", self::PRIVATE];
2677 if ($local_user && ($local_user == $owner_id)) {
2678 // Profile owner - everything is visible
2680 } elseif ($remote_user) {
2681 // Authenticated visitor - fetch the matching permissionsets
2682 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2684 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2685 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2686 self::PRIVATE, self::PRIVATE];
2687 $condition = array_merge($condition, $permissionSets->column('id'));
2695 * Get a permission SQL string for the given user
2697 * @param int $owner_id
2698 * @param string $table
2701 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2703 $local_user = local_user();
2704 $remote_user = Session::getRemoteContactID($owner_id);
2706 if (!empty($table)) {
2707 $table = DBA::quoteIdentifier($table) . '.';
2711 * Construct permissions
2713 * default permissions - anonymous user
2715 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2717 // Profile owner - everything is visible
2718 if ($local_user && ($local_user == $owner_id)) {
2720 } elseif ($remote_user) {
2722 * Authenticated visitor. Unless pre-verified,
2723 * check that the contact belongs to this $owner_id
2724 * and load the groups the visitor belongs to.
2725 * If pre-verified, the caller is expected to have already
2726 * done this and passed the groups into this function.
2728 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2731 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2736 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2743 * get translated item type
2745 * @param array $item
2746 * @param \Friendica\Core\L10n $l10n
2749 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2751 if (!empty($item['event-id'])) {
2752 return $l10n->t('event');
2753 } elseif (!empty($item['resource-id'])) {
2754 return $l10n->t('photo');
2755 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2756 return $l10n->t('activity');
2757 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2758 return $l10n->t('comment');
2761 return $l10n->t('post');
2765 * Sets the "rendered-html" field of the provided item
2767 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2769 * @param array $item
2771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2772 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2774 private static function putInCache(&$item)
2776 // Save original body to prevent addons to modify it
2777 $body = $item['body'];
2779 $rendered_hash = $item['rendered-hash'] ?? '';
2780 $rendered_html = $item['rendered-html'] ?? '';
2782 if ($rendered_hash == ''
2783 || $rendered_html == ''
2784 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2785 || DI::config()->get('system', 'ignore_cache')
2787 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2788 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2790 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2791 Hook::callAll('put_item_in_cache', $hook_data);
2792 $item['rendered-html'] = $hook_data['rendered-html'];
2793 $item['rendered-hash'] = $hook_data['rendered-hash'];
2796 // Update if the generated values differ from the existing ones
2797 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2800 'rendered-html' => $item['rendered-html'],
2801 'rendered-hash' => $item['rendered-hash']
2803 ['id' => $item['id']]
2808 $item['body'] = $body;
2812 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2813 * If attach is true, also add icons for item attachments.
2815 * @param array $item Record from item table
2816 * @param boolean $attach If true, add icons for item attachments as well
2817 * @param boolean $is_preview Whether this is a preview
2818 * @param boolean $only_cache Whether only cached HTML should be updated
2819 * @return string item body html
2820 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2821 * @throws \ImagickException
2822 * @hook prepare_body_init item array before any work
2823 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2824 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2825 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2827 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2830 Hook::callAll('prepare_body_init', $item);
2832 // In order to provide theme developers more possibilities, event items
2833 // are treated differently.
2834 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2835 $ev = Event::getItemHTML($item);
2839 $tags = Tag::populateFromItem($item);
2841 $item['tags'] = $tags['tags'];
2842 $item['hashtags'] = $tags['hashtags'];
2843 $item['mentions'] = $tags['mentions'];
2845 $body = $item['body'] ?? '';
2846 $shared = BBCode::fetchShareAttributes($body);
2847 if (!empty($shared['guid'])) {
2848 $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2849 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2850 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2851 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2852 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2853 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2854 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2855 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2861 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2862 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2864 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2865 self::putInCache($item);
2866 $item['body'] = $body;
2867 $s = $item["rendered-html"];
2873 // Compile eventual content filter reasons
2874 $filter_reasons = [];
2875 if (!$is_preview && public_contact() != $item['author-id']) {
2876 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2877 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2880 $item['attachments'] = $attachments;
2884 'filter_reasons' => $filter_reasons
2886 Hook::callAll('prepare_body_content_filter', $hook_data);
2887 $filter_reasons = $hook_data['filter_reasons'];
2894 'preview' => $is_preview,
2895 'filter_reasons' => $filter_reasons
2897 Hook::callAll('prepare_body', $hook_data);
2898 $s = $hook_data['html'];
2902 // Replace the blockquotes with quotes that are used in mails.
2903 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2904 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2908 if (!empty($shared_attachments)) {
2909 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2910 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2911 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2912 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2915 $s = self::addVisualAttachments($attachments, $item, $s, false);
2916 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2917 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2918 $s = self::addQuestions($item, $s);
2921 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2922 $x = Map::byCoordinates(trim($item['coord']));
2924 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2928 // Replace friendica image url size with theme preference.
2929 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2930 $ps = $a->getThemeInfoValue('item_image_size');
2931 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2934 $s = HTML::applyContentFilter($s, $filter_reasons);
2936 $hook_data = ['item' => $item, 'html' => $s];
2937 Hook::callAll('prepare_body_final', $hook_data);
2939 return $hook_data['html'];
2943 * Check if the body contains a link
2945 * @param string $body
2946 * @param string $url
2950 public static function containsLink(string $body, string $url, int $type = 0): bool
2952 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2953 $urlparts = parse_url($url);
2954 if (!empty($urlparts)) {
2955 unset($urlparts['query']);
2956 unset($urlparts['fragment']);
2957 $url = (string)Uri::fromParts($urlparts);
2962 // Remove media links to only search in embedded content
2963 // @todo Check images for image link, audio for audio links, ...
2964 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2965 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2968 if (strpos($body, $url)) {
2971 foreach ([0, 1, 2] as $size) {
2972 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2973 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2981 * Replace visual attachments in the body
2983 * @param array $attachments
2984 * @param string $body
2985 * @return string modified body
2987 private static function replaceVisualAttachments(array $attachments, string $body): string
2989 DI::profiler()->startRecording('rendering');
2991 foreach ($attachments['visual'] as $attachment) {
2992 if (!empty($attachment['preview'])) {
2993 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2994 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
2995 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
2997 $body = str_replace($search, $replace, $body);
2998 } elseif ($attachment['filetype'] == 'image') {
2999 $proxy = Post\Media::getUrlForId($attachment['id']);
3000 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3001 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3003 $body = str_replace($search, $replace, $body);
3006 DI::profiler()->stopRecording();
3011 * Add visual attachments to the content
3013 * @param array $attachments
3014 * @param array $item
3015 * @param string $content
3016 * @return string modified content
3018 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3020 DI::profiler()->startRecording('rendering');
3024 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3025 foreach ($attachments['visual'] as $attachment) {
3026 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3030 if (!empty($attachment['preview'])) {
3031 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3036 if (($attachment['filetype'] == 'video')) {
3037 /// @todo Move the template to /content as well
3038 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3040 'id' => $attachment['id'],
3041 'src' => $attachment['url'],
3042 'name' => $attachment['name'] ?: $attachment['url'],
3043 'preview' => $preview_url,
3044 'mime' => $attachment['mimetype'],
3047 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3050 $trailing .= $media;
3052 } elseif ($attachment['filetype'] == 'audio') {
3053 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3055 'id' => $attachment['id'],
3056 'src' => $attachment['url'],
3057 'name' => $attachment['name'] ?: $attachment['url'],
3058 'mime' => $attachment['mimetype'],
3061 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3064 $trailing .= $media;
3066 } elseif ($attachment['filetype'] == 'image') {
3067 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3069 'src' => Post\Media::getUrlForId($attachment['id']),
3070 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3071 'attachment' => $attachment,
3074 // On Diaspora posts the attached pictures are leading
3075 if ($item['network'] == Protocol::DIASPORA) {
3078 $trailing .= $media;
3084 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3085 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3087 if ($leading != '') {
3088 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3091 if ($trailing != '') {
3092 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3096 DI::profiler()->stopRecording();
3101 * Add link attachment to the content
3103 * @param array $attachments
3104 * @param string $body
3105 * @param string $content
3106 * @param bool $shared
3107 * @param array $ignore_links A list of URLs to ignore
3108 * @return string modified content
3110 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3112 DI::profiler()->startRecording('rendering');
3113 // Don't show a preview when there is a visual attachment (audio or video)
3114 $types = array_column($attachments['visual'], 'type');
3115 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3117 if (!empty($attachments['link'])) {
3118 foreach ($attachments['link'] as $link) {
3120 foreach ($ignore_links as $ignore_link) {
3121 if (Strings::compareLink($link['url'], $ignore_link)) {
3125 // @todo Judge between the links to use the one with most information
3126 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3127 (empty($attachment['name']) && !empty($link['name'])) ||
3128 (empty($attachment['description']) && !empty($link['description'])) ||
3129 (empty($attachment['preview']) && !empty($link['preview'])))) {
3130 $attachment = $link;
3135 if (!empty($attachment)) {
3138 'author_name' => $attachment['author-name'] ?? '',
3139 'author_url' => $attachment['author-url'] ?? '',
3140 'description' => $attachment['description'] ?? '',
3143 'provider_name' => $attachment['publisher-name'] ?? '',
3144 'provider_url' => $attachment['publisher-url'] ?? '',
3146 'title' => $attachment['name'] ?? '',
3148 'url' => $attachment['url']];
3150 if ($preview && !empty($attachment['preview'])) {
3151 if ($attachment['preview-width'] >= 500) {
3152 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3154 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3158 if (!empty($data['description']) && !empty($content)) {
3159 similar_text($data['description'], $content, $percent);
3164 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3165 $data['description'] = '';
3168 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3169 $data['author_name'] = '';
3172 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3173 $data['author_url'] = '';
3175 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3176 $data = BBCode::getAttachmentData($match[1]);
3178 DI::profiler()->stopRecording();
3180 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3181 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3182 $parts = parse_url($data['url']);
3183 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3184 if (empty($data['provider_name'])) {
3185 $data['provider_name'] = $parts['host'];
3187 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3188 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3190 if (!empty($parts['port'])) {
3191 $data['provider_url'] .= ':' . $parts['port'];
3196 // @todo Use a template
3197 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3198 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3199 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3200 '$url' => $data['url'],
3201 '$title' => $data['title'],
3208 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3210 return $content . $rendered;
3217 * Add non visual attachments to the content
3219 * @param array $attachments
3220 * @param array $item
3221 * @param string $content
3222 * @return string modified content
3224 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3226 DI::profiler()->startRecording('rendering');
3228 foreach ($attachments['additional'] as $attachment) {
3229 if (strpos($item['body'], $attachment['url'])) {
3233 $author = ['uid' => 0, 'id' => $item['author-id'],
3234 'network' => $item['author-network'], 'url' => $item['author-link']];
3235 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3237 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3239 if (!empty($attachment['size'])) {
3240 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3243 /// @todo Use a template
3244 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3245 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3248 if ($trailing != '') {
3249 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3252 DI::profiler()->stopRecording();
3256 private static function addQuestions(array $item, string $content): string
3258 DI::profiler()->startRecording('rendering');
3259 if (!empty($item['question-id'])) {
3261 'id' => $item['question-id'],
3262 'multiple' => $item['question-multiple'],
3263 'voters' => $item['question-voters'],
3264 'endtime' => $item['question-end-time']
3267 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3268 foreach ($options as $key => $option) {
3269 $percent = $question['voters'] ? ($option['replies'] / $question['voters'] * 100) : 0;
3271 $options[$key]['percent'] = $percent;
3273 if ($question['voters'] > 0) {
3274 $options[$key]['vote'] = DI::l10n()->t('%s (%d%s, %d votes)', $option['name'], round($percent, 1), '%', $option['replies']);
3276 $options[$key]['vote'] = DI::l10n()->t('%s (%d votes)', $option['name'], $option['replies']);
3280 if (!empty($question['voters']) && !empty($question['endtime'])) {
3281 $summary = DI::l10n()->t('%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3282 } elseif (!empty($question['voters'])) {
3283 $summary = DI::l10n()->t('%d voters.', $question['voters']);
3284 } elseif (!empty($question['endtime'])) {
3285 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3290 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3291 '$question' => $question,
3292 '$options' => $options,
3293 '$summary' => $summary,
3296 DI::profiler()->stopRecording();
3301 * get private link for item
3303 * @param array $item
3304 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3305 * @throws \Exception
3307 public static function getPlink(array $item)
3309 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3310 $plink = $item['plink'];
3311 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3312 $plink = $item['uri'];
3317 'href' => "display/" . $item['guid'],
3318 'orig' => "display/" . $item['guid'],
3319 'title' => DI::l10n()->t('View on separate page'),
3320 'orig_title' => DI::l10n()->t('View on separate page'),
3323 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3324 $author = ['uid' => 0, 'id' => $item['author-id'],
3325 'network' => $item['author-network'], 'url' => $item['author-link']];
3326 $plink = Contact::magicLinkByContact($author, $plink);
3329 if (!empty($plink)) {
3330 $ret['href'] = DI::baseUrl()->remove($plink);
3331 $ret['title'] = DI::l10n()->t('Link to source');
3333 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3337 'title' => DI::l10n()->t('Link to source'),
3338 'orig_title' => DI::l10n()->t('Link to source'),
3348 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3350 * @param int $uri_id
3352 * @return boolean "true" when it is a forum post
3354 public static function isForumPost(int $uri_id): bool
3356 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3357 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3365 * Search item id for given URI or plink
3367 * @param string $uri
3368 * @param integer $uid
3370 * @return integer item id
3372 public static function searchByLink(string $uri, int $uid = 0): int
3374 $ssl_uri = str_replace('http://', 'https://', $uri);
3375 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3377 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3378 if (DBA::isResult($item)) {
3382 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3383 if (DBA::isResult($item)) {
3391 * Return the URI for a link to the post
3393 * @param string $uri URI or link to post
3395 * @return string URI
3397 public static function getURIByLink(string $uri): string
3399 $ssl_uri = str_replace('http://', 'https://', $uri);
3400 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3402 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3403 if (DBA::isResult($item)) {
3404 return $item['uri'];
3407 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3408 if (DBA::isResult($item)) {
3409 return $item['uri'];
3416 * Fetches item for given URI or plink
3418 * @param string $uri
3419 * @param integer $uid
3421 * @return integer item id
3423 public static function fetchByLink(string $uri, int $uid = 0): int
3425 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3426 $item_id = self::searchByLink($uri, $uid);
3427 if (!empty($item_id)) {
3428 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3438 Hook::callAll('item_by_link', $hookData);
3440 if (isset($hookData['item_id'])) {
3441 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3444 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3447 $item_id = self::searchByLink($fetched_uri, $uid);
3449 $item_id = Diaspora::fetchByURL($uri);
3452 if (!empty($item_id)) {
3453 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3457 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3462 * Return share data from an item array (if the item is shared item)
3463 * We are providing the complete Item array, because at some time in the future
3464 * we hopefully will define these values not in the body anymore but in some item fields.
3465 * This function is meant to replace all similar functions in the system.
3467 * @param array $item
3469 * @return array with share information
3471 public static function getShareArray(array $item): array
3473 return BBCode::fetchShareAttributes($item['body']);
3477 * Fetch item information for shared items from the original items and adds it.
3479 * @param array $item
3481 * @return array item array with data from the original item
3483 public static function addShareDataFromOriginal(array $item): array
3485 $shared = self::getShareArray($item);
3486 if (empty($shared)) {
3490 // Real reshares always have got a GUID.
3491 if (empty($shared['guid'])) {
3495 $uid = $item['uid'] ?? 0;
3497 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3498 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3499 if (!DBA::isResult($shared_item)) {
3500 if (empty($shared['link'])) {
3504 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3505 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3507 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3511 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3512 if (!DBA::isResult($shared_item)) {
3515 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3517 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3520 if (!empty($shared_item['title'])) {
3521 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3522 unset($shared_item['title']);
3524 $body = $shared_item['body'];
3527 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3528 unset($shared_item['body']);
3530 return array_merge($item, $shared_item);
3534 * Check a prospective item array against user-level permissions
3536 * @param array $item Expected keys: uri, gravity, and
3537 * author-link if is author-id is set,
3538 * owner-link if is owner-id is set,
3539 * causer-link if is causer-id is set.
3540 * @param int $user_id Local user ID
3542 * @throws \Exception
3544 protected static function isAllowedByUser(array $item, int $user_id): bool
3546 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3547 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3551 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3552 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3556 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3557 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3558 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3562 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3563 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3571 * Improve the data in shared posts
3573 * @param array $item
3574 * @return string body
3576 public static function improveSharedDataInBody(array $item): string
3578 $shared = BBCode::fetchShareAttributes($item['body']);
3579 if (empty($shared['link'])) {
3580 return $item['body'];
3583 $id = self::fetchByLink($shared['link']);
3584 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3586 return $item['body'];
3589 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3590 if (!DBA::isResult($shared_item)) {
3591 return $item['body'];
3594 $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']);
3596 if (!empty($shared_item['title'])) {
3597 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3600 $shared_content .= $shared_item['body'];
3602 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3603 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3604 return $item['body'];