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 LanguageDetection\Language;
51 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
58 const PT_DOCUMENT = 19;
61 const PT_PERSONAL_NOTE = 128;
63 // Posting reasons (Why had a post been stored for a user?)
70 const PR_FOLLOWER = 69;
71 const PR_ANNOUNCEMENT = 70;
72 const PR_COMMENT = 71;
76 const PR_FETCHED = 75;
78 // system.accept_only_sharer setting values
79 const COMPLETION_NONE = 1;
80 const COMPLETION_COMMENT = 0;
81 const COMPLETION_LIKE = 2;
83 // Field list that is used to display the items
84 const DISPLAY_FIELDLIST = [
85 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
86 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri',
87 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
88 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
89 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
90 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
91 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
92 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
93 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
94 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
95 'writable', 'self', 'cid', 'alias',
96 'event-created', 'event-edited', 'event-start', 'event-finish',
97 'event-summary', 'event-desc', 'event-location', 'event-type',
98 'event-nofinish', 'event-ignore', 'event-id',
99 "question-id", "question-multiple", "question-voters", "question-end-time",
100 "has-categories", "has-media",
101 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
104 // Field list that is used to deliver items via the protocols
105 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
106 'parent-guid', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
107 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
108 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
109 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
110 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
111 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
112 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
113 'event-created', 'event-edited', 'event-start', 'event-finish',
114 'event-summary', 'event-desc', 'event-location', 'event-type',
115 'event-nofinish', 'event-ignore', 'event-id'];
117 // All fields in the item table
118 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
119 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
120 'contact-id', 'wall', 'gravity', 'extid', 'psid',
121 'created', 'edited', 'commented', 'received', 'changed', 'verb',
122 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
123 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
124 'private', 'pubmail', 'visible', 'starred',
125 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
126 'title', 'content-warning', 'body', 'location', 'coord', 'app',
127 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
128 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
129 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
131 // List of all verbs that don't need additional content data.
132 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
134 Activity::LIKE, Activity::DISLIKE,
135 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
144 * Update existing item entries
146 * @param array $fields The fields that are to be changed
147 * @param array $condition The condition for finding the item entries
149 * In the future we may have to change permissions as well.
150 * Then we had to add the user id as third parameter.
152 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
154 * @return integer|boolean number of affected rows - or "false" if there was an error
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157 public static function update(array $fields, array $condition)
159 if (empty($condition) || empty($fields)) {
163 if (isset($fields['extid'])) {
164 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
167 if (!empty($fields['verb'])) {
168 $fields['vid'] = Verb::getID($fields['verb']);
171 if (!empty($fields['edited'])) {
172 $previous = Post::selectFirst(['edited'], $condition);
175 $rows = Post::update($fields, $condition);
176 if (is_bool($rows)) {
180 // We only need to call the line by line update for specific fields
181 if (empty($fields['body']) && empty($fields['file']) &&
182 empty($fields['attach']) && empty($fields['edited'])) {
186 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
188 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
192 while ($item = DBA::fetch($items)) {
193 if (!empty($fields['body'])) {
194 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
196 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
198 // Remove all media attachments from the body and store them in the post-media table
199 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
200 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
201 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
203 if ($item['author-network'] != Protocol::DFRN) {
204 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
207 Post\Content::update($item['uri-id'], $content_fields);
210 if (!empty($fields['file'])) {
211 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
214 if (!empty($fields['attach'])) {
215 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
218 // We only need to notfiy others when it is an original entry from us.
219 // Only call the notifier when the item had been edited and records had been changed.
220 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
221 $notify_items[] = $item['id'];
227 foreach ($notify_items as $notify_item) {
228 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
229 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
236 * Delete an item and notify others about it - if it was ours
238 * @param array $condition The condition for finding the item entries
239 * @param integer $priority Priority for the notification
240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
242 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
244 $items = Post::select(['id'], $condition);
245 while ($item = Post::fetch($items)) {
246 self::markForDeletionById($item['id'], $priority);
252 * Delete an item for an user and notify others about it - if it was ours
254 * @param array $condition The condition for finding the item entries
255 * @param integer $uid User who wants to delete this item
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 public static function deleteForUser(array $condition, int $uid)
264 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
265 while ($item = Post::fetch($items)) {
266 if (in_array($item['uid'], [$uid, 0])) {
267 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
268 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
271 if ($item['uid'] == $uid) {
272 self::markForDeletionById($item['id'], PRIORITY_HIGH);
273 } elseif ($item['uid'] != 0) {
274 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
281 * Mark an item for deletion, delete related data and notify others about it - if it was ours
283 * @param integer $item_id
284 * @param integer $priority Priority for the notification
286 * @return boolean success
287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
291 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
292 // locate item to be deleted
293 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
294 'deleted', 'resource-id', 'event-id',
295 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
296 $item = Post::selectFirst($fields, ['id' => $item_id]);
297 if (!DBA::isResult($item)) {
298 Logger::info('Item not found.', ['id' => $item_id]);
302 if ($item['deleted']) {
303 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
307 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
308 if (!DBA::isResult($parent)) {
309 $parent = ['origin' => false];
312 // clean up categories and tags so they don't end up as orphans
313 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
316 * If item is a link to a photo resource, nuke all the associated photos
317 * (visitors will not have photo resources)
318 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
319 * generate a resource-id and therefore aren't intimately linked to the item.
321 /// @TODO: this should first check if photo is used elsewhere
322 if (strlen($item['resource-id'])) {
323 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
326 // If item is a link to an event, delete the event.
327 if (intval($item['event-id'])) {
328 Event::delete($item['event-id']);
331 // If item has attachments, drop them
332 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
333 foreach($attachments as $attachment) {
334 if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
335 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
339 // Set the item to "deleted"
340 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
341 Post::update($item_fields, ['id' => $item['id']]);
343 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
345 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
346 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
349 Post\DeliveryData::delete($item['uri-id']);
351 // If it's the parent of a comment thread, kill all the kids
352 if ($item['gravity'] == GRAVITY_PARENT) {
353 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
356 // Is it our comment and/or our thread?
357 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
358 // When we delete the original post we will delete all existing copies on the server as well
359 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
361 // send the notification upstream/downstream
363 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
365 } elseif ($item['uid'] != 0) {
366 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
367 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
370 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
375 public static function guid($item, $notify)
377 if (!empty($item['guid'])) {
378 return trim($item['guid']);
382 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
383 // We add the hash of our own host because our host is the original creator of the post.
384 $prefix_host = DI::baseUrl()->getHostname();
388 // We are only storing the post so we create a GUID from the original hostname.
389 if (!empty($item['author-link'])) {
390 $parsed = parse_url($item['author-link']);
391 if (!empty($parsed['host'])) {
392 $prefix_host = $parsed['host'];
396 if (empty($prefix_host) && !empty($item['plink'])) {
397 $parsed = parse_url($item['plink']);
398 if (!empty($parsed['host'])) {
399 $prefix_host = $parsed['host'];
403 if (empty($prefix_host) && !empty($item['uri'])) {
404 $parsed = parse_url($item['uri']);
405 if (!empty($parsed['host'])) {
406 $prefix_host = $parsed['host'];
410 // Is it in the format data@host.tld? - Used for mail contacts
411 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
412 $mailparts = explode('@', $item['author-link']);
413 $prefix_host = array_pop($mailparts);
417 if (!empty($item['plink'])) {
418 $guid = self::guidFromUri($item['plink'], $prefix_host);
419 } elseif (!empty($item['uri'])) {
420 $guid = self::guidFromUri($item['uri'], $prefix_host);
422 $guid = System::createUUID(hash('crc32', $prefix_host));
428 private static function contactId($item)
430 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
431 return $item['contact-id'];
432 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
433 return $item['contact-id'];
434 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
435 return $item['author-id'];
436 } elseif (!empty($item['contact-id'])) {
437 return $item['contact-id'];
439 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
440 if (!empty($contact_id)) {
444 return $item['author-id'];
448 * Write an item array into a spool file to be inserted later.
449 * This command is called whenever there are issues storing an item.
451 * @param array $item The item fields that are to be inserted
454 private static function spool($orig_item)
456 // Now we store the data in the spool directory
457 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
458 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
460 $spoolpath = System::getSpoolPath();
461 if ($spoolpath != "") {
462 $spool = $spoolpath . '/' . $file;
464 file_put_contents($spool, json_encode($orig_item));
465 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
470 * Check if the item array is a duplicate
473 * @return boolean is it a duplicate?
475 private static function isDuplicate(array $item)
477 // Checking if there is already an item with the same guid
478 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
479 if (Post::exists($condition)) {
480 Logger::notice('Found already existing item', $condition);
484 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
485 'network' => [$item['network'], Protocol::DFRN]];
486 if (Post::exists($condition)) {
487 Logger::notice('duplicated item with the same uri found.', $condition);
491 // On Friendica and Diaspora the GUID is unique
492 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
493 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
494 if (Post::exists($condition)) {
495 Logger::notice('duplicated item with the same guid found.', $condition);
498 } elseif ($item['network'] == Protocol::OSTATUS) {
499 // Check for an existing post with the same content. There seems to be a problem with OStatus.
500 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
501 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
502 if (Post::exists($condition)) {
503 Logger::notice('duplicated item with the same body found.', $item);
509 * Check for already added items.
510 * There is a timing issue here that sometimes creates double postings.
511 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
513 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
514 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
522 * Check if the item array is valid
525 * @return boolean item is valid
527 public static function isValid(array $item)
529 // When there is no content then we don't post it
530 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
531 Logger::notice('No body, no title.');
535 if (!empty($item['uid'])) {
536 $owner = User::getOwnerDataById($item['uid'], false);
538 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
542 if ($owner['account_expired'] || $owner['account_removed']) {
543 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']]);
548 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
549 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
553 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
554 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
558 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
559 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
563 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
564 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
568 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
572 if ($item['verb'] == Activity::FOLLOW) {
573 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
574 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
575 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
579 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
580 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
581 if (Post::exists($condition)) {
582 // It happens that we receive multiple follow requests by the same author - we only store one.
583 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
592 * Check if the item array is too old
595 * @return boolean item is too old
597 public static function isTooOld(array $item)
599 // check for create date and expire time
600 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
602 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
603 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
604 $expire_interval = $user['expire'];
607 if (($expire_interval > 0) && !empty($item['created'])) {
608 $expire_date = time() - ($expire_interval * 86400);
609 $created_date = strtotime($item['created']);
610 if ($created_date < $expire_date) {
611 Logger::notice('Item created before expiration interval.', [
612 'created' => date('c', $created_date),
613 'expired' => date('c', $expire_date),
624 * Return the id of the given item array if it has been stored before
627 * @return integer item id
629 private static function getDuplicateID(array $item)
631 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
632 $condition = ["`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
633 $item['uri-id'], $item['uid'],
634 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
635 $existing = Post::selectFirst(['id', 'network'], $condition);
636 if (DBA::isResult($existing)) {
637 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
638 if ($item['uid'] != 0) {
639 Logger::notice('Item already existed for user', [
640 'uri-id' => $item['uri-id'],
641 'uid' => $item['uid'],
642 'network' => $item['network'],
643 'existing_id' => $existing["id"],
644 'existing_network' => $existing["network"]
648 return $existing["id"];
655 * Fetch top-level parent data for the given item array
658 * @return array item array with parent data
661 private static function getTopLevelParent(array $item)
663 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
664 'uri-id', 'parent-uri-id',
665 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
666 'wall', 'private', 'origin', 'author-id'];
667 $condition = ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']];
668 $params = ['order' => ['id' => false]];
669 $parent = Post::selectFirst($fields, $condition, $params);
671 if (!DBA::isResult($parent) && $item['origin']) {
672 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid']);
673 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
674 $parent = Post::selectFirst($fields, $condition, $params);
677 if (!DBA::isResult($parent)) {
678 Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
682 if ($parent['uri-id'] == $parent['parent-uri-id']) {
686 $condition = ['uri-id' => $parent['parent-uri-id'],
687 'parent-uri-id' => $parent['parent-uri-id'],
688 'uid' => $parent['uid']];
689 $params = ['order' => ['id' => false]];
690 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
692 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
693 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid']);
694 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
695 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
698 if (!DBA::isResult($toplevel_parent)) {
699 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
703 return $toplevel_parent;
707 * Get the gravity for the given item array
710 * @return integer gravity
712 private static function getGravity(array $item): int
714 $activity = DI::activity();
716 if (isset($item['gravity'])) {
717 return intval($item['gravity']);
718 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
719 return GRAVITY_PARENT;
720 } elseif ($activity->match($item['verb'], Activity::POST)) {
721 return GRAVITY_COMMENT;
722 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
723 return GRAVITY_ACTIVITY;
724 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
725 return GRAVITY_ACTIVITY;
727 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
728 return GRAVITY_UNKNOWN; // Should not happen
731 public static function insert(array $item, int $notify = 0, bool $post_local = true)
735 $priority = PRIORITY_HIGH;
737 // If it is a posting where users should get notifications, then define it as wall posting
741 $item['network'] = Protocol::DFRN;
742 $item['protocol'] = Conversation::PARCEL_DIRECT;
743 $item['direction'] = Conversation::PUSH;
745 if (is_int($notify) && in_array($notify, PRIORITIES)) {
749 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
752 $uid = intval($item['uid']);
754 $item['guid'] = self::guid($item, $notify);
755 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
758 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
760 // Backward compatibility: parent-uri used to be the direct parent uri.
761 // If it is provided without a thr-parent, it probably is the old behavior.
762 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
763 $item['parent-uri'] = $item['thr-parent'];
765 $item['thr-parent-id'] = $item['parent-uri-id'] = ItemURI::getIdByURI($item['thr-parent']);
767 // Store conversation data
768 $item = Conversation::insert($item);
771 * Do we already have this item?
772 * We have to check several networks since Friendica posts could be repeated
773 * via OStatus (maybe Diasporsa as well)
775 $duplicate = self::getDuplicateID($item);
780 // Additional duplicate checks
781 /// @todo Check why the first duplication check returns the item number and the second a 0
782 if (self::isDuplicate($item)) {
786 if (!isset($item['post-type'])) {
787 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
790 $item['wall'] = intval($item['wall'] ?? 0);
791 $item['extid'] = trim($item['extid'] ?? '');
792 $item['author-name'] = trim($item['author-name'] ?? '');
793 $item['author-link'] = trim($item['author-link'] ?? '');
794 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
795 $item['owner-name'] = trim($item['owner-name'] ?? '');
796 $item['owner-link'] = trim($item['owner-link'] ?? '');
797 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
798 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
799 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
800 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
801 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
802 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
803 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
804 $item['location'] = trim($item['location'] ?? '');
805 $item['coord'] = trim($item['coord'] ?? '');
806 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
807 $item['deleted'] = 0;
808 $item['verb'] = trim($item['verb'] ?? '');
809 $item['object-type'] = trim($item['object-type'] ?? '');
810 $item['object'] = trim($item['object'] ?? '');
811 $item['target-type'] = trim($item['target-type'] ?? '');
812 $item['target'] = trim($item['target'] ?? '');
813 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
814 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
815 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
816 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
817 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
818 $item['private'] = intval($item['private'] ?? self::PUBLIC);
819 $item['body'] = trim($item['body'] ?? '');
820 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
821 $item['app'] = trim($item['app'] ?? '');
822 $item['origin'] = intval($item['origin'] ?? 0);
823 $item['postopts'] = trim($item['postopts'] ?? '');
824 $item['resource-id'] = trim($item['resource-id'] ?? '');
825 $item['event-id'] = intval($item['event-id'] ?? 0);
826 $item['inform'] = trim($item['inform'] ?? '');
827 $item['file'] = trim($item['file'] ?? '');
829 // Communities aren't working with the Diaspora protoccol
830 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
831 $user = User::getById($uid, ['account-type']);
832 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
833 Logger::info('Community posts are not supported via Diaspora');
838 // Items cannot be stored before they happen ...
839 if ($item['created'] > DateTimeFormat::utcNow()) {
840 $item['created'] = DateTimeFormat::utcNow();
843 // We haven't invented time travel by now.
844 if ($item['edited'] > DateTimeFormat::utcNow()) {
845 $item['edited'] = DateTimeFormat::utcNow();
848 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
850 $item['gravity'] = self::getGravity($item);
852 $item['language'] = self::getLanguage($item);
854 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
855 'photo' => $item['author-avatar'], 'network' => $item['network']];
856 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
858 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
859 'photo' => $item['owner-avatar'], 'network' => $item['network']];
860 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
862 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
863 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
864 $item['post-reason'] = self::PR_FOLLOWER;
867 // Ensure that there is an avatar cache
868 Contact::checkAvatarCache($item['author-id']);
869 Contact::checkAvatarCache($item['owner-id']);
871 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
872 $item["contact-id"] = self::contactId($item);
874 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
875 empty($item['origin']) &&self::isTooOld($item)) {
876 Logger::info('Item is too old', ['item' => $item]);
880 if (!self::isValid($item)) {
884 if ($item['gravity'] !== GRAVITY_PARENT) {
885 $toplevel_parent = self::getTopLevelParent($item);
886 if (empty($toplevel_parent)) {
890 // If the thread originated from this node, we check the permission against the thread starter
891 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
892 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
893 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
897 $parent_id = $toplevel_parent['id'];
898 $item['parent-uri'] = $toplevel_parent['uri'];
899 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
900 $item['deleted'] = $toplevel_parent['deleted'];
902 // Reshares have to keep their permissions to allow forums to work
903 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
904 $item['allow_cid'] = $toplevel_parent['allow_cid'];
905 $item['allow_gid'] = $toplevel_parent['allow_gid'];
906 $item['deny_cid'] = $toplevel_parent['deny_cid'];
907 $item['deny_gid'] = $toplevel_parent['deny_gid'];
910 $parent_origin = $toplevel_parent['origin'];
912 // Don't federate received participation messages
913 if ($item['verb'] != Activity::FOLLOW) {
914 $item['wall'] = $toplevel_parent['wall'];
916 $item['wall'] = false;
917 // Participations are technical messages, so they are set to "seen" automatically
918 $item['unseen'] = false;
922 * If the parent is private, force privacy for the entire conversation
923 * This differs from the above settings as it subtly allows comments from
924 * email correspondents to be private even if the overall thread is not.
926 if ($toplevel_parent['private']) {
927 $item['private'] = $toplevel_parent['private'];
930 // If its a post that originated here then tag the thread as "mention"
931 if ($item['origin'] && $item['uid']) {
932 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
933 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
936 // Update the contact relations
937 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
940 $parent_origin = $item['origin'];
943 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
944 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
946 // Is this item available in the global items (with uid=0)?
947 if ($item["uid"] == 0) {
948 $item["global"] = true;
950 // Set the global flag on all items if this was a global item entry
951 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
953 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
957 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
958 $item["private"] = self::PRIVATE;
961 if ($notify && $post_local) {
962 $item['edit'] = false;
963 $item['parent'] = $parent_id;
965 // Trigger automatic reactions for addons
966 if (!isset($item['api_source'])) {
967 $item['api_source'] = true;
970 // We have to tell the hooks who we are - this really should be improved
972 $_SESSION['authenticated'] = true;
973 $_SESSION['uid'] = $uid;
974 $dummy_session = true;
976 $dummy_session = false;
979 Hook::callAll('post_local', $item);
981 if ($dummy_session) {
982 unset($_SESSION['authenticated']);
983 unset($_SESSION['uid']);
985 } elseif (!$notify) {
986 Hook::callAll('post_remote', $item);
989 if (!empty($item['cancel'])) {
990 Logger::notice('post cancelled by addon.');
994 if (empty($item['vid']) && !empty($item['verb'])) {
995 $item['vid'] = Verb::getID($item['verb']);
998 // Creates or assigns the permission set
999 $item['psid'] = DI::permissionSet()->selectOrCreate(
1000 DI::permissionSetFactory()->createFromString(
1008 if (!empty($item['extid'])) {
1009 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1012 if ($item['verb'] == Activity::ANNOUNCE) {
1013 self::setOwnerforResharedItem($item);
1016 if (isset($item['attachments'])) {
1017 foreach ($item['attachments'] as $attachment) {
1018 $attachment['uri-id'] = $item['uri-id'];
1019 Post\Media::insert($attachment);
1021 unset($item['attachments']);
1024 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1026 // Remove all media attachments from the body and store them in the post-media table
1027 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1028 $item['raw-body'] = self::setHashtags($item['raw-body']);
1030 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1031 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1034 // Check for hashtags in the body and repair or add hashtag links
1035 $item['body'] = self::setHashtags($item['body']);
1037 if (stristr($item['verb'], Activity::POKE)) {
1038 $notify_type = Delivery::POKE;
1040 $notify_type = Delivery::POST;
1043 // Filling item related side tables
1044 if (!empty($item['attach'])) {
1045 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1048 if (empty($item['event-id'])) {
1049 unset($item['event-id']);
1051 $ev = Event::fromBBCode($item['body']);
1052 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1053 Logger::info('Event found.');
1054 $ev['cid'] = $item['contact-id'];
1055 $ev['uid'] = $item['uid'];
1056 $ev['uri'] = $item['uri'];
1057 $ev['edited'] = $item['edited'];
1058 $ev['private'] = $item['private'];
1059 $ev['guid'] = $item['guid'];
1060 $ev['plink'] = $item['plink'];
1061 $ev['network'] = $item['network'];
1062 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1063 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1064 $ev['source'] = $item['source'] ?? '';
1066 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1067 if (DBA::isResult($event)) {
1068 $ev['id'] = $event['id'];
1071 $event_id = Event::store($ev);
1072 $item = Event::getItemArrayForImportedId($event_id, $item);
1074 Logger::info('Event was stored', ['id' => $event_id]);
1078 if (empty($item['causer-id'])) {
1079 unset($item['causer-id']);
1082 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1083 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1084 if (!empty($content_warning) && empty($item['content-warning'])) {
1085 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1089 Post::insert($item['uri-id'], $item);
1091 if ($item['gravity'] == GRAVITY_PARENT) {
1092 Post\Thread::insert($item['uri-id'], $item);
1095 if (!in_array($item['verb'], self::ACTIVITIES)) {
1096 Post\Content::insert($item['uri-id'], $item);
1099 // Create Diaspora signature
1100 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1101 $signed = Diaspora::createCommentSignature($item);
1102 if (!empty($signed)) {
1103 $item['diaspora_signed_text'] = json_encode($signed);
1107 if (!empty($item['diaspora_signed_text'])) {
1108 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1111 // Attached file links
1112 if (!empty($item['file'])) {
1113 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1116 // Delivery relevant data
1117 $delivery_data = Post\DeliveryData::extractFields($item);
1119 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1120 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1123 // Store tags from the body if this hadn't been handled previously in the protocol classes
1124 if (!Tag::existsForPost($item['uri-id'])) {
1125 Tag::storeFromBody($item['uri-id'], $item['body']);
1128 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1129 if (Post::exists($condition)) {
1130 Logger::notice('Item is already inserted - aborting', $condition);
1134 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1135 if (!$post_user_id) {
1136 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1140 if ($item['gravity'] == GRAVITY_PARENT) {
1141 $item['post-user-id'] = $post_user_id;
1142 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1145 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1147 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1148 if (!DBA::isResult($posted_item)) {
1149 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1150 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1151 self::spool($orig_item);
1155 // update the commented timestamp on the parent
1156 if (DI::config()->get('system', 'like_no_comment')) {
1157 // Update when it is a comment
1158 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1160 // Update when it isn't a follow or tag verb
1161 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1164 if ($update_commented) {
1165 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1167 $fields = ['changed' => DateTimeFormat::utcNow()];
1170 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1172 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1173 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1174 // Get the user information for the logging
1175 $user = User::getById($uid);
1177 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1182 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1183 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1185 Hook::callAll('post_local_end', $posted_item);
1187 Hook::callAll('post_remote_end', $posted_item);
1190 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1191 self::addShadow($post_user_id);
1193 self::addShadowPost($post_user_id);
1196 self::updateContact($posted_item);
1198 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1200 // Distribute items to users who subscribed to their tags
1201 self::distributeByTags($posted_item);
1203 // Automatically reshare the item if the "remote_self" option is selected
1204 self::autoReshare($posted_item);
1206 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1209 // Don't relay participation messages
1210 if (($posted_item['verb'] == Activity::FOLLOW) &&
1211 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1212 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1218 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1221 // Fill the cache with the rendered content.
1222 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1223 self::updateDisplayCache($posted_item['uri-id']);
1226 if ($posted_item['origin'] && ($posted_item['uid'] != 0) && in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
1227 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_OUTBOX . $posted_item['uid']);
1230 return $post_user_id;
1234 * Update the display cache
1236 * @param integer $uri_id
1239 public static function updateDisplayCache(int $uri_id)
1241 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1242 self::prepareBody($item, false, false, true);
1246 * Change the owner of a parent item if it had been shared by a forum
1248 * (public) forum posts in the new format consist of the regular post by the author
1249 * followed by an announce message sent from the forum account.
1250 * Changing the owner helps in grouping forum posts.
1252 * @param array $item
1255 private static function setOwnerforResharedItem(array $item)
1257 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1258 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1259 if (!DBA::isResult($parent)) {
1260 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1264 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1265 if (!DBA::isResult($author)) {
1266 Logger::error('Author not found', ['id' => $item['author-id']]);
1270 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1271 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1273 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1274 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1275 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1279 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1280 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1281 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']]);
1285 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1286 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1291 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1292 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1296 * Distribute the given item to users who subscribed to their tags
1298 * @param array $item Processed item
1300 private static function distributeByTags(array $item)
1302 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1306 $uids = Tag::getUIDListByURIId($item['uri-id']);
1307 foreach ($uids as $uid) {
1308 if (Contact::isSharing($item['author-id'], $uid)) {
1311 $fields = ['post-reason' => self::PR_TAG];
1314 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
1315 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
1320 * Distributes public items to the receivers
1322 * @param integer $itemid Item ID that should be added
1323 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1324 * @throws \Exception
1326 public static function distribute(int $itemid, string $signed_text = '')
1328 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1329 $parent = Post::selectFirst(['owner-id'], $condition);
1330 if (!DBA::isResult($parent)) {
1331 Logger::warning('Item not found', ['condition' => $condition]);
1335 // Only distribute public items from native networks
1336 $condition = ['id' => $itemid, 'uid' => 0,
1337 'network' => array_merge(Protocol::FEDERATED ,['']),
1338 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1339 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
1340 if (!DBA::isResult($item)) {
1341 Logger::warning('Item not found', ['condition' => $condition]);
1345 $origin = $item['origin'];
1349 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1350 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1351 if (!DBA::isResult($owner)) {
1355 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1356 $contacts = DBA::select('contact', ['uid'], $condition);
1357 while ($contact = DBA::fetch($contacts)) {
1358 if ($contact['uid'] == 0) {
1362 $users[$contact['uid']] = $contact['uid'];
1364 DBA::close($contacts);
1366 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1367 $contacts = DBA::select('contact', ['uid'], $condition);
1368 while ($contact = DBA::fetch($contacts)) {
1369 if ($contact['uid'] == 0) {
1373 $users[$contact['uid']] = $contact['uid'];
1375 DBA::close($contacts);
1377 if (!empty($owner['alias'])) {
1378 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1379 $contacts = DBA::select('contact', ['uid'], $condition);
1380 while ($contact = DBA::fetch($contacts)) {
1381 if ($contact['uid'] == 0) {
1385 $users[$contact['uid']] = $contact['uid'];
1387 DBA::close($contacts);
1392 if ($item['uri-id'] != $item['parent-uri-id']) {
1393 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1394 while ($parent = Post::fetch($parents)) {
1395 $users[$parent['uid']] = $parent['uid'];
1396 if ($parent['origin'] && !$origin) {
1397 $origin_uid = $parent['uid'];
1400 DBA::close($parents);
1403 foreach ($users as $uid) {
1404 if ($origin_uid == $uid) {
1405 $item['diaspora_signed_text'] = $signed_text;
1407 self::storeForUser($item, $uid);
1412 * Store a public item defined by their URI-ID for the given users
1414 * @param integer $uri_id URI-ID of the given item
1415 * @param integer $uid The user that will receive the item entry
1416 * @param array $fields Additional fields to be stored
1417 * @param integer $source_uid User id of the source post
1418 * @return integer stored item id
1420 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1422 if ($uid == $source_uid) {
1423 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1427 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => $source_uid]);
1428 if (!DBA::isResult($item)) {
1429 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1433 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1434 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']]);
1438 $item['post-reason'] = self::PR_STORED;
1440 $item = array_merge($item, $fields);
1442 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1444 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1445 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1446 !Contact::isSharingByURL($item['author-link'], $uid) &&
1447 !Contact::isSharingByURL($item['owner-link'], $uid)) {
1448 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1452 if (($uri_id != $item['thr-parent-id']) && (($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1453 // Fetch the origin user for the post
1454 $origin_uid = self::GetOriginUidForUriId($item['thr-parent-id'], $uid);
1455 if (is_null($origin_uid)) {
1456 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $item['thr-parent-id']]);
1460 $causer = $item['causer-id'] ?: $item['author-id'];
1461 $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1462 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1465 $stored = self::storeForUser($item, $uid);
1466 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1471 * Returns the origin uid of a post if the given user is allowed to see it.
1477 private static function GetOriginUidForUriId(int $uriid, int $uid)
1479 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1483 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1484 if (!empty($post)) {
1485 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1486 return $post['uid'];
1489 $pcid = Contact::getPublicIdByUserId($uid);
1494 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1495 if ($receiver == $pcid) {
1496 return $post['uid'];
1503 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1507 // When the post belongs to a a forum then all forum users are allowed to access it
1508 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1509 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1510 $target_uid = User::getIdForURL($tag['url']);
1511 if (!empty($target_uid)) {
1521 * Store a public item array for the given users
1523 * @param array $item The item entry that will be stored
1524 * @param integer $uid The user that will receive the item entry
1525 * @return integer stored item id
1526 * @throws \Exception
1528 private static function storeForUser(array $item, int $uid): int
1530 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1531 if (!empty($item['event-id'])) {
1532 $post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1533 if (!empty($post['event-id'])) {
1534 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1535 if (!empty($event)) {
1536 // We aren't using "Event::store" here, since we don't want to trigger any further action
1537 $ret = DBA::update('event', $event, ['id' => $post['event-id']]);
1538 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $post['event-id'], 'ret' => $ret]);
1542 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1546 // Data from the "post-user" table
1548 unset($item['mention']);
1549 unset($item['starred']);
1550 unset($item['unseen']);
1551 unset($item['psid']);
1552 unset($item['pinned']);
1553 unset($item['ignored']);
1554 unset($item['pubmail']);
1555 unset($item['event-id']);
1556 unset($item['hidden']);
1557 unset($item['notification-type']);
1558 unset($item['post-reason']);
1560 // Data from the "post-delivery-data" table
1561 unset($item['postopts']);
1562 unset($item['inform']);
1564 $item['uid'] = $uid;
1565 $item['origin'] = 0;
1568 if ($item['gravity'] == GRAVITY_PARENT) {
1569 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1571 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1574 if (!empty($contact['id'])) {
1575 $item['contact-id'] = $contact['id'];
1577 // Shouldn't happen at all
1578 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1579 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1580 if (!DBA::isResult($self)) {
1581 // Shouldn't happen even less
1582 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1585 $item['contact-id'] = $self['id'];
1589 if ($item['gravity'] == GRAVITY_PARENT) {
1590 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1591 if (DBA::isResult($contact)) {
1592 $notify = self::isRemoteSelf($contact, $item);
1596 $distributed = self::insert($item, $notify);
1598 if (!$distributed) {
1599 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1601 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1603 return $distributed;
1607 * Add a shadow entry for a given item id that is a thread starter
1609 * We store every public item entry additionally with the user id "0".
1610 * This is used for the community page and for the search.
1611 * It is planned that in the future we will store public item entries only once.
1613 * @param integer $itemid Item ID that should be added
1614 * @throws \Exception
1616 private static function addShadow(int $itemid)
1618 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1619 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1620 $item = Post::selectFirst($fields, $condition);
1622 if (!DBA::isResult($item)) {
1626 // is it already a copy?
1627 if (($itemid == 0) || ($item['uid'] == 0)) {
1631 // Is it a visible public post?
1632 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1636 // is it an entry from a connector? Only add an entry for natively connected networks
1637 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1641 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1645 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1647 if (DBA::isResult($item)) {
1648 // Preparing public shadow (removing user specific data)
1651 unset($item['parent']);
1652 unset($item['wall']);
1653 unset($item['mention']);
1654 unset($item['origin']);
1655 unset($item['starred']);
1656 unset($item['postopts']);
1657 unset($item['inform']);
1658 unset($item['post-reason']);
1659 if ($item['uri-id'] == $item['parent-uri-id']) {
1660 $item['contact-id'] = $item['owner-id'];
1662 $item['contact-id'] = $item['author-id'];
1665 $public_shadow = self::insert($item);
1667 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1672 * Add a shadow entry for a given item id that is a comment
1674 * This function does the same like the function above - but for comments
1676 * @param integer $itemid Item ID that should be added
1677 * @throws \Exception
1679 private static function addShadowPost(int $itemid)
1681 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1682 if (!DBA::isResult($item)) {
1686 // Is it a toplevel post?
1687 if ($item['gravity'] == GRAVITY_PARENT) {
1688 self::addShadow($itemid);
1692 // Is this a shadow entry?
1693 if ($item['uid'] == 0) {
1697 // Is there a shadow parent?
1698 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1702 // Is there already a shadow entry?
1703 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1707 // Save "origin" and "parent" state
1708 $origin = $item['origin'];
1709 $parent = $item['parent'];
1711 // Preparing public shadow (removing user specific data)
1714 unset($item['parent']);
1715 unset($item['wall']);
1716 unset($item['mention']);
1717 unset($item['origin']);
1718 unset($item['starred']);
1719 unset($item['postopts']);
1720 unset($item['inform']);
1721 unset($item['post-reason']);
1722 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1724 $public_shadow = self::insert($item);
1726 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1728 // If this was a comment to a Diaspora post we don't get our comment back.
1729 // This means that we have to distribute the comment by ourselves.
1730 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1731 self::distribute($public_shadow);
1736 * Adds a language specification in a "language" element of given $arr.
1737 * Expects "body" element to exist in $arr.
1739 * @param array $item
1740 * @return string detected language
1741 * @throws \Text_LanguageDetect_Exception
1743 private static function getLanguage(array $item): string
1745 if (!empty($item['language'])) {
1746 return $item['language'];
1749 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1753 // Convert attachments to links
1754 $naked_body = BBCode::removeAttachment($item['body']);
1755 if (empty($naked_body)) {
1759 // Remove links and pictures
1760 $naked_body = BBCode::removeLinks($naked_body);
1762 // Convert the title and the body to plain text
1763 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1765 // Remove possibly remaining links
1766 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1768 if (empty($naked_body)) {
1772 $availableLanguages = DI::l10n()->getAvailableLanguages();
1773 // See https://github.com/friendica/friendica/issues/10511
1774 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1775 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1776 $availableLanguages['fa'] = 'fa';
1778 $ld = new Language(array_keys($availableLanguages));
1779 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1780 if (is_array($languages)) {
1781 return json_encode($languages);
1787 public static function getLanguageMessage(array $item): string
1789 $iso639 = new \Matriphe\ISO639\ISO639;
1791 $used_languages = '';
1792 foreach (json_decode($item['language'], true) as $language => $reliability) {
1793 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1795 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1796 return $used_languages;
1800 * Creates an unique guid out of a given uri.
1801 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1802 * Posts that are created on this system are using System::createUUID.
1803 * Received ActivityPub posts are using Processor::getGUIDByURL.
1805 * @param string $uri uri of an item entry
1806 * @param string $host hostname for the GUID prefix
1807 * @return string unique guid
1809 public static function guidFromUri(string $uri, string $host): string
1811 // Our regular guid routine is using this kind of prefix as well
1812 // We have to avoid that different routines could accidentally create the same value
1813 $parsed = parse_url($uri);
1815 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1816 unset($parsed["scheme"]);
1818 // Glue it together to be able to make a hash from it
1819 $host_id = implode("/", $parsed);
1821 // Use a mixture of several hashes to provide some GUID like experience
1822 return hash("crc32", $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1826 * generate an unique URI
1828 * @param integer $uid User id
1829 * @param string $guid An existing GUID (Otherwise it will be generated)
1832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1834 public static function newURI($uid, $guid = "")
1837 $guid = System::createUUID();
1840 return DI::baseUrl()->get() . '/objects/' . $guid;
1844 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1846 * This can be used to filter for inactive contacts.
1847 * Only do this for public postings to avoid privacy problems, since poco data is public.
1848 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1850 * @param array $arr Contains the just posted item record
1851 * @throws \Exception
1853 private static function updateContact(array $arr)
1855 // Unarchive the author
1856 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1857 if (DBA::isResult($contact)) {
1858 Contact::unmarkForArchival($contact);
1861 // Unarchive the contact if it's not our own contact
1862 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1863 if (DBA::isResult($contact)) {
1864 Contact::unmarkForArchival($contact);
1867 /// @todo On private posts we could obfuscate the date
1868 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1870 // Is it a forum? Then we don't care about the rules from above
1871 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1872 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1878 // The "self" contact id is used (for example in the connectors) when the contact is unknown
1879 // So we have to ensure to only update the last item when it had been our own post,
1880 // or it had been done by a "regular" contact.
1881 if (!empty($arr['wall'])) {
1882 $condition = ['id' => $arr['contact-id']];
1884 $condition = ['id' => $arr['contact-id'], 'self' => false];
1886 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1888 // Now do the same for the system wide contacts with uid=0
1889 if ($arr['private'] != self::PRIVATE) {
1890 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1891 ['id' => $arr['owner-id']]);
1893 if ($arr['owner-id'] != $arr['author-id']) {
1894 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1895 ['id' => $arr['author-id']]);
1900 public static function setHashtags(string $body): string
1902 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1903 $tags = BBCode::getTags($body);
1906 if (!count($tags)) {
1910 // This sorting is important when there are hashtags that are part of other hashtags
1911 // Otherwise there could be problems with hashtags like #test and #test2
1912 // Because of this we are sorting from the longest to the shortest tag.
1913 usort($tags, function ($a, $b) {
1914 return strlen($b) <=> strlen($a);
1917 $URLSearchString = "^\[\]";
1919 // All hashtags should point to the home server if "local_tags" is activated
1920 if (DI::config()->get('system', 'local_tags')) {
1921 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1922 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1925 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1926 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1928 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1931 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1933 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1936 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1938 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1941 // Repair recursive urls
1942 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1945 foreach ($tags as $tag) {
1946 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
1950 $basetag = str_replace('_', ' ', substr($tag, 1));
1951 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1953 $body = str_replace($tag, $newtag, $body);
1956 // Convert back the masked hashtags
1957 $body = str_replace("#", "#", $body);
1966 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1969 * @param int $item_id
1970 * @return boolean true if item was deleted, else false
1971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1972 * @throws \ImagickException
1974 private static function tagDeliver(int $uid, int $item_id): bool
1978 $owner = User::getOwnerDataById($uid);
1979 if (!DBA::isResult($owner)) {
1980 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
1984 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1985 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
1989 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
1990 if (!DBA::isResult($item)) {
1991 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
1995 if ($item['gravity'] == GRAVITY_PARENT) {
1996 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
1997 foreach ($tags as $tag) {
1998 if (Strings::compareLink($owner['url'], $tag['url'])) {
2000 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']]);
2005 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2006 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2010 $arr = ['item' => $item, 'user' => $owner];
2012 Hook::callAll('tagged', $arr);
2014 $tags = Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2015 foreach ($tags as $tag) {
2016 if (Strings::compareLink($owner['url'], $tag['url'])) {
2018 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']]);
2023 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2028 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2030 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2032 $allow_gid = '<' . Group::FOLLOWERS . '>';
2035 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2037 self::performActivity($item['id'], 'announce', $uid);
2040 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2045 * Automatically reshare the item if the "remote_self" option is selected
2047 * @param array $item
2050 private static function autoReshare(array $item)
2052 if ($item['gravity'] != GRAVITY_PARENT) {
2056 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2060 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2064 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2066 self::performActivity($item['id'], 'announce', $item['uid']);
2069 public static function isRemoteSelf(array $contact, array &$datarray): bool
2071 if (!$contact['remote_self']) {
2075 // Prevent the forwarding of posts that are forwarded
2076 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2077 Logger::info('Already forwarded');
2081 // Prevent to forward already forwarded posts
2082 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2083 Logger::info('Already forwarded (second test)');
2087 // Only forward posts
2088 if ($datarray["verb"] != Activity::POST) {
2089 Logger::info('No post');
2093 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2094 Logger::info('Not public');
2098 $datarray2 = $datarray;
2099 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2100 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2101 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2102 ['uid' => $contact['uid'], 'self' => true]);
2103 if (DBA::isResult($self)) {
2104 $datarray['contact-id'] = $self["id"];
2106 $datarray['owner-name'] = $self["name"];
2107 $datarray['owner-link'] = $self["url"];
2108 $datarray['owner-avatar'] = $self["thumb"];
2110 $datarray['author-name'] = $datarray['owner-name'];
2111 $datarray['author-link'] = $datarray['owner-link'];
2112 $datarray['author-avatar'] = $datarray['owner-avatar'];
2114 unset($datarray['edited']);
2116 unset($datarray['network']);
2117 unset($datarray['owner-id']);
2118 unset($datarray['author-id']);
2121 if ($contact['network'] != Protocol::FEED) {
2122 $old_uri_id = $datarray["uri-id"] ?? 0;
2123 $datarray["guid"] = System::createUUID();
2124 unset($datarray["plink"]);
2125 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2126 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2127 $datarray["extid"] = Protocol::DFRN;
2128 $urlpart = parse_url($datarray2['author-link']);
2129 $datarray["app"] = $urlpart["host"];
2130 if (!empty($old_uri_id)) {
2131 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2134 unset($datarray["parent-uri"]);
2135 unset($datarray["thr-parent"]);
2137 $datarray['private'] = self::PUBLIC;
2141 if ($contact['network'] != Protocol::FEED) {
2142 // Store the original post
2143 $result = self::insert($datarray2);
2144 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2146 $datarray["app"] = "Feed";
2150 return (bool)$result;
2157 * @param array $item
2160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2161 * @throws \ImagickException
2163 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2165 if (DI::config()->get('system', 'disable_embedded')) {
2169 Logger::info('check for photos');
2170 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2175 $img_start = strpos($orig_body, '[img');
2176 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2177 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2179 while (($img_st_close !== false) && ($img_len !== false)) {
2180 $img_st_close++; // make it point to AFTER the closing bracket
2181 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2183 Logger::info('found photo', ['image' => $image]);
2185 if (stristr($image, $site . '/photo/')) {
2186 // Only embed locally hosted photos
2188 $i = basename($image);
2189 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2190 $x = strpos($i, '-');
2193 $res = substr($i, $x + 1);
2194 $i = substr($i, 0, $x);
2195 $photo = Photo::getPhotoForUser($uid, $i, $res);
2196 if (DBA::isResult($photo)) {
2198 * Check to see if we should replace this photo link with an embedded image
2199 * 1. No need to do so if the photo is public
2200 * 2. If there's a contact-id provided, see if they're in the access list
2201 * for the photo. If so, embed it.
2202 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2203 * permissions, regardless of order but first check to see if they're an exact
2204 * match to save some processing overhead.
2206 if (self::hasPermissions($photo)) {
2208 $recips = self::enumeratePermissions($photo);
2209 if (in_array($cid, $recips)) {
2213 if (self::samePermissions($uid, $item, $photo)) {
2219 $photo_img = Photo::getImageForPhoto($photo);
2220 // If a custom width and height were specified, apply before embedding
2221 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2222 Logger::info('scaling photo');
2224 $width = intval($match[1]);
2225 $height = intval($match[2]);
2227 $photo_img->scaleDown(max($width, $height));
2230 $data = $photo_img->asString();
2231 $type = $photo_img->getType();
2233 Logger::info('replacing photo');
2234 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2235 Logger::debug('replaced', ['image' => $image]);
2241 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2242 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2243 if ($orig_body === false) {
2247 $img_start = strpos($orig_body, '[img');
2248 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2249 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2252 $new_body = $new_body . $orig_body;
2257 private static function hasPermissions(array $obj)
2259 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2260 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2263 // @TODO $uid is unused parameter
2264 private static function samePermissions($uid, array $obj1, array $obj2): bool
2266 // first part is easy. Check that these are exactly the same.
2267 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2268 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2269 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2270 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2274 // This is harder. Parse all the permissions and compare the resulting set.
2275 $recipients1 = self::enumeratePermissions($obj1);
2276 $recipients2 = self::enumeratePermissions($obj2);
2280 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2281 return ($recipients1 == $recipients2);
2285 * Returns an array of contact-ids that are allowed to see this object
2287 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2288 * @param bool $check_dead Prunes unavailable contacts from the result
2290 * @throws \Exception
2292 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2294 $aclFormater = DI::aclFormatter();
2296 $allow_people = $aclFormater->expand($obj['allow_cid']);
2297 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2298 $deny_people = $aclFormater->expand($obj['deny_cid']);
2299 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2300 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2301 $deny = array_unique(array_merge($deny_people, $deny_groups));
2302 $recipients = array_diff($recipients, $deny);
2306 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2308 if (!$uid || ($days < 1)) {
2312 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2313 $uid, GRAVITY_PARENT];
2316 * $expire_network_only = save your own wall posts
2317 * and just expire conversations started by others
2319 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2321 if ($expire_network_only) {
2322 $condition[0] .= " AND NOT `wall`";
2325 if ($network != "") {
2326 $condition[0] .= " AND `network` = ?";
2327 $condition[] = $network;
2330 $condition[0] .= " AND `received` < ?";
2331 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2333 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2335 if (!DBA::isResult($items)) {
2339 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2341 // Forcing expiring of items - but not notes and marked items
2343 $expire_items = true;
2346 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2347 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2348 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2352 $priority = DI::config()->get('system', 'expire-notify-priority');
2354 while ($item = Post::fetch($items)) {
2355 // don't expire filed items
2356 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2360 // Only expire posts, not photos and photo comments
2362 if (!$expire_photos && !empty($item['resource-id'])) {
2364 } elseif (!$expire_starred && intval($item['starred'])) {
2366 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2368 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2372 self::markForDeletionById($item['id'], $priority);
2377 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2380 public static function firstPostDate(int $uid, bool $wall = false)
2382 $user = User::getById($uid, ['register_date']);
2387 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2388 $uid, $wall, $user['register_date']];
2389 $params = ['order' => ['received' => false]];
2390 $thread = Post::selectFirstThread(['received'], $condition, $params);
2391 if (DBA::isResult($thread)) {
2392 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2399 * add/remove activity to an item
2401 * Toggle activities as like,dislike,attend of an item
2403 * @param int $item_id
2404 * @param string $verb
2405 * Activity verb. One of
2406 * like, unlike, dislike, undislike, attendyes, unattendyes,
2407 * attendno, unattendno, attendmaybe, unattendmaybe,
2408 * announce, unannouce
2410 * @param string $allow_cid
2411 * @param string $allow_gid
2412 * @param string $deny_cid
2413 * @param string $deny_gid
2415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2416 * @throws \ImagickException
2417 * @hook 'post_local_end'
2419 * 'post_id' => ID of posted item
2421 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
2427 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2429 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2430 if (!DBA::isResult($item)) {
2431 Logger::notice('like: unknown item', ['id' => $item_id]);
2435 $uri_id = $item['uri-id'];
2437 if (!in_array($item['uid'], [0, $uid])) {
2441 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2442 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
2443 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2444 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2445 if (!DBA::isResult($item)) {
2446 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2452 // Retrieves the local post owner
2453 $owner = User::getOwnerDataById($uid);
2454 if (empty($owner)) {
2455 Logger::info('Empty owner for user', ['uid' => $uid]);
2459 // Retrieve the current logged in user's public contact
2460 $author_id = Contact::getIdForURL($owner['url']);
2461 if (empty($author_id)) {
2462 Logger::info('Empty public contact');
2470 $activity = Activity::LIKE;
2474 $activity = Activity::DISLIKE;
2478 $activity = Activity::ATTEND;
2482 $activity = Activity::ATTENDNO;
2485 case 'unattendmaybe':
2486 $activity = Activity::ATTENDMAYBE;
2490 $activity = Activity::FOLLOW;
2494 $activity = Activity::ANNOUNCE;
2497 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2501 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2503 // Enable activity toggling instead of on/off
2504 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2506 // Look for an existing verb row
2507 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2508 if ($event_verb_flag) {
2509 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2511 // Translate to the index based activity index
2513 foreach ($verbs as $verb) {
2514 $vids[] = Verb::getID($verb);
2517 $vids = Verb::getID($activity);
2520 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2521 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2522 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2524 if (DBA::isResult($like_item)) {
2526 * Truth table for existing activities
2528 * | Inputs || Outputs |
2529 * |----------------------------||-------------------|
2530 * | Mode | Event | Same verb || Delete? | Return? |
2531 * |--------|-------|-----------||---------|---------|
2532 * | create | Yes | Yes || No | Yes |
2533 * | create | Yes | No || Yes | No |
2534 * | create | No | Yes || No | Yes |
2535 * | create | No | No || N/A†|
2536 * | delete | Yes | Yes || Yes | N/A‡ |
2537 * | delete | Yes | No || No | N/A‡ |
2538 * | delete | No | Yes || Yes | N/A‡ |
2539 * | delete | No | No || N/A†|
2540 * |--------|-------|-----------||---------|---------|
2541 * | A | B | C || A xor C | !B or C |
2543 * †Can't happen: It's impossible to find an existing non-event activity without
2544 * the same verb because we are only looking for this single verb.
2546 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2548 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2549 self::markForDeletionById($like_item['id']);
2552 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2557 // No need to go further if we aren't creating anything
2558 if ($mode == 'delete') {
2562 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2565 'guid' => System::createUUID(),
2566 'uri' => self::newURI($item['uid']),
2567 'uid' => $item['uid'],
2568 'contact-id' => $owner['id'],
2569 'wall' => $item['wall'],
2571 'network' => Protocol::DFRN,
2572 'protocol' => Conversation::PARCEL_DIRECT,
2573 'direction' => Conversation::PUSH,
2574 'gravity' => GRAVITY_ACTIVITY,
2575 'parent' => $item['id'],
2576 'thr-parent' => $item['uri'],
2577 'owner-id' => $author_id,
2578 'author-id' => $author_id,
2579 'body' => $activity,
2580 'verb' => $activity,
2581 'object-type' => $objtype,
2582 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2583 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2584 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2585 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2590 $signed = Diaspora::createLikeSignature($uid, $new_item);
2591 if (!empty($signed)) {
2592 $new_item['diaspora_signed_text'] = json_encode($signed);
2595 $new_item_id = self::insert($new_item);
2597 // If the parent item isn't visible then set it to visible
2598 if (!$item['visible']) {
2599 self::update(['visible' => true], ['id' => $item['id']]);
2602 $new_item['id'] = $new_item_id;
2604 Hook::callAll('post_local_end', $new_item);
2610 * Fetch the SQL condition for the given user id
2612 * @param integer $owner_id User ID for which the permissions should be fetched
2613 * @return array condition
2615 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2617 $local_user = local_user();
2618 $remote_user = Session::getRemoteContactID($owner_id);
2620 // default permissions - anonymous user
2621 $condition = ["`private` != ?", self::PRIVATE];
2623 if ($local_user && ($local_user == $owner_id)) {
2624 // Profile owner - everything is visible
2626 } elseif ($remote_user) {
2627 // Authenticated visitor - fetch the matching permissionsets
2628 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2630 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2631 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2632 self::PRIVATE, self::PRIVATE];
2633 $condition = array_merge($condition, $permissionSets->column('id'));
2641 * Get a permission SQL string for the given user
2643 * @param int $owner_id
2644 * @param string $table
2647 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2649 $local_user = local_user();
2650 $remote_user = Session::getRemoteContactID($owner_id);
2652 if (!empty($table)) {
2653 $table = DBA::quoteIdentifier($table) . '.';
2657 * Construct permissions
2659 * default permissions - anonymous user
2661 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2663 // Profile owner - everything is visible
2664 if ($local_user && ($local_user == $owner_id)) {
2666 } elseif ($remote_user) {
2668 * Authenticated visitor. Unless pre-verified,
2669 * check that the contact belongs to this $owner_id
2670 * and load the groups the visitor belongs to.
2671 * If pre-verified, the caller is expected to have already
2672 * done this and passed the groups into this function.
2674 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2677 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2682 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2689 * get translated item type
2691 * @param array $item
2692 * @param \Friendica\Core\L10n $l10n
2695 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2697 if (!empty($item['event-id'])) {
2698 return $l10n->t('event');
2699 } elseif (!empty($item['resource-id'])) {
2700 return $l10n->t('photo');
2701 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2702 return $l10n->t('activity');
2703 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2704 return $l10n->t('comment');
2707 return $l10n->t('post');
2711 * Sets the "rendered-html" field of the provided item
2713 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2715 * @param array $item
2717 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2718 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2720 private static function putInCache(&$item)
2722 // Save original body to prevent addons to modify it
2723 $body = $item['body'];
2725 $rendered_hash = $item['rendered-hash'] ?? '';
2726 $rendered_html = $item['rendered-html'] ?? '';
2728 if ($rendered_hash == ''
2729 || $rendered_html == ''
2730 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2731 || DI::config()->get('system', 'ignore_cache')
2733 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2734 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2736 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2737 Hook::callAll('put_item_in_cache', $hook_data);
2738 $item['rendered-html'] = $hook_data['rendered-html'];
2739 $item['rendered-hash'] = $hook_data['rendered-hash'];
2742 // Update if the generated values differ from the existing ones
2743 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2746 'rendered-html' => $item['rendered-html'],
2747 'rendered-hash' => $item['rendered-hash']
2749 ['id' => $item['id']]
2754 $item['body'] = $body;
2758 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2759 * If attach is true, also add icons for item attachments.
2761 * @param array $item Record from item table
2762 * @param boolean $attach If true, add icons for item attachments as well
2763 * @param boolean $is_preview Whether this is a preview
2764 * @param boolean $only_cache Whether only cached HTML should be updated
2765 * @return string item body html
2766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2767 * @throws \ImagickException
2768 * @hook prepare_body_init item array before any work
2769 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2770 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2771 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2773 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2776 Hook::callAll('prepare_body_init', $item);
2778 // In order to provide theme developers more possibilities, event items
2779 // are treated differently.
2780 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2781 $ev = Event::getItemHTML($item);
2785 $tags = Tag::populateFromItem($item);
2787 $item['tags'] = $tags['tags'];
2788 $item['hashtags'] = $tags['hashtags'];
2789 $item['mentions'] = $tags['mentions'];
2791 $body = $item['body'] ?? '';
2792 $shared = BBCode::fetchShareAttributes($body);
2793 if (!empty($shared['guid'])) {
2794 $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2795 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2796 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2797 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2798 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2799 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2800 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2801 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2806 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media']);
2807 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2809 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2810 self::putInCache($item);
2811 $item['body'] = $body;
2812 $s = $item["rendered-html"];
2818 // Compile eventual content filter reasons
2819 $filter_reasons = [];
2820 if (!$is_preview && public_contact() != $item['author-id']) {
2821 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2822 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2825 $item['attachments'] = $attachments;
2829 'filter_reasons' => $filter_reasons
2831 Hook::callAll('prepare_body_content_filter', $hook_data);
2832 $filter_reasons = $hook_data['filter_reasons'];
2839 'preview' => $is_preview,
2840 'filter_reasons' => $filter_reasons
2842 Hook::callAll('prepare_body', $hook_data);
2843 $s = $hook_data['html'];
2847 // Replace the blockquotes with quotes that are used in mails.
2848 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2849 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2853 if (!empty($shared_attachments)) {
2854 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2855 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2856 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2857 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2860 $s = self::addVisualAttachments($attachments, $item, $s, false);
2861 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2862 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2863 $s = self::addQuestions($item, $s);
2866 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2867 $x = Map::byCoordinates(trim($item['coord']));
2869 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2873 // Replace friendica image url size with theme preference.
2874 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2875 $ps = $a->getThemeInfoValue('item_image_size');
2876 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2879 $s = HTML::applyContentFilter($s, $filter_reasons);
2881 $hook_data = ['item' => $item, 'html' => $s];
2882 Hook::callAll('prepare_body_final', $hook_data);
2884 return $hook_data['html'];
2888 * Check if the body contains a link
2890 * @param string $body
2891 * @param string $url
2895 public static function containsLink(string $body, string $url, int $type = 0): bool
2897 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2898 $urlparts = parse_url($url);
2899 unset($urlparts['query']);
2900 unset($urlparts['fragment']);
2901 $url = Network::unparseURL($urlparts);
2903 // Remove media links to only search in embedded content
2904 // @todo Check images for image link, audio for audio links, ...
2905 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2906 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2909 if (strpos($body, $url)) {
2912 foreach ([0, 1, 2] as $size) {
2913 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2914 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2922 * Replace visual attachments in the body
2924 * @param array $attachments
2925 * @param string $body
2926 * @return string modified body
2928 private static function replaceVisualAttachments(array $attachments, string $body): string
2930 DI::profiler()->startRecording('rendering');
2932 foreach ($attachments['visual'] as $attachment) {
2933 if (!empty($attachment['preview'])) {
2934 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2935 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
2936 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
2938 $body = str_replace($search, $replace, $body);
2939 } elseif ($attachment['filetype'] == 'image') {
2940 $proxy = Post\Media::getUrlForId($attachment['id']);
2941 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
2942 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
2944 $body = str_replace($search, $replace, $body);
2947 DI::profiler()->stopRecording();
2952 * Add visual attachments to the content
2954 * @param array $attachments
2955 * @param array $item
2956 * @param string $content
2957 * @return string modified content
2959 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
2961 DI::profiler()->startRecording('rendering');
2965 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
2966 foreach ($attachments['visual'] as $attachment) {
2967 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
2971 if (!empty($attachment['preview'])) {
2972 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2977 if (($attachment['filetype'] == 'video')) {
2978 /// @todo Move the template to /content as well
2979 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
2981 'id' => $attachment['id'],
2982 'src' => $attachment['url'],
2983 'name' => $attachment['name'] ?: $attachment['url'],
2984 'preview' => $preview_url,
2985 'mime' => $attachment['mimetype'],
2988 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
2991 $trailing .= $media;
2993 } elseif ($attachment['filetype'] == 'audio') {
2994 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
2996 'id' => $attachment['id'],
2997 'src' => $attachment['url'],
2998 'name' => $attachment['name'] ?: $attachment['url'],
2999 'mime' => $attachment['mimetype'],
3002 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3005 $trailing .= $media;
3007 } elseif ($attachment['filetype'] == 'image') {
3008 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3010 'src' => Post\Media::getUrlForId($attachment['id']),
3011 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3012 'attachment' => $attachment,
3015 // On Diaspora posts the attached pictures are leading
3016 if ($item['network'] == Protocol::DIASPORA) {
3019 $trailing .= $media;
3025 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3026 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3028 if ($leading != '') {
3029 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3032 if ($trailing != '') {
3033 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3037 DI::profiler()->stopRecording();
3042 * Add link attachment to the content
3044 * @param array $attachments
3045 * @param string $body
3046 * @param string $content
3047 * @param bool $shared
3048 * @param array $ignore_links A list of URLs to ignore
3049 * @return string modified content
3051 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3053 DI::profiler()->startRecording('rendering');
3054 // Don't show a preview when there is a visual attachment (audio or video)
3055 $types = array_column($attachments['visual'], 'type');
3056 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3058 if (!empty($attachments['link'])) {
3059 foreach ($attachments['link'] as $link) {
3061 foreach ($ignore_links as $ignore_link) {
3062 if (Strings::compareLink($link['url'], $ignore_link)) {
3066 // @todo Judge between the links to use the one with most information
3067 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3068 (empty($attachment['name']) && !empty($link['name'])) ||
3069 (empty($attachment['description']) && !empty($link['description'])) ||
3070 (empty($attachment['preview']) && !empty($link['preview'])))) {
3071 $attachment = $link;
3076 if (!empty($attachment)) {
3079 'author_name' => $attachment['author-name'] ?? '',
3080 'author_url' => $attachment['author-url'] ?? '',
3081 'description' => $attachment['description'] ?? '',
3084 'provider_name' => $attachment['publisher-name'] ?? '',
3085 'provider_url' => $attachment['publisher-url'] ?? '',
3087 'title' => $attachment['name'] ?? '',
3089 'url' => $attachment['url']];
3091 if ($preview && !empty($attachment['preview'])) {
3092 if ($attachment['preview-width'] >= 500) {
3093 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3095 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3099 if (!empty($data['description']) && !empty($content)) {
3100 similar_text($data['description'], $content, $percent);
3105 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3106 $data['description'] = '';
3109 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3110 $data['author_name'] = '';
3113 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3114 $data['author_url'] = '';
3116 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3117 $data = BBCode::getAttachmentData($match[1]);
3119 DI::profiler()->stopRecording();
3121 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3122 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3123 $parts = parse_url($data['url']);
3124 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3125 if (empty($data['provider_name'])) {
3126 $data['provider_name'] = $parts['host'];
3128 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3129 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3131 if (!empty($parts['port'])) {
3132 $data['provider_url'] .= ':' . $parts['port'];
3137 // @todo Use a template
3138 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3139 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3140 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3141 '$url' => $data['url'],
3142 '$title' => $data['title'],
3149 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3151 return $content . $rendered;
3158 * Add non visual attachments to the content
3160 * @param array $attachments
3161 * @param array $item
3162 * @param string $content
3163 * @return string modified content
3165 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3167 DI::profiler()->startRecording('rendering');
3169 foreach ($attachments['additional'] as $attachment) {
3170 if (strpos($item['body'], $attachment['url'])) {
3174 $author = ['uid' => 0, 'id' => $item['author-id'],
3175 'network' => $item['author-network'], 'url' => $item['author-link']];
3176 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3178 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3180 if (!empty($attachment['size'])) {
3181 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3184 /// @todo Use a template
3185 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3186 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3189 if ($trailing != '') {
3190 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3193 DI::profiler()->stopRecording();
3197 private static function addQuestions(array $item, string $content): string
3199 DI::profiler()->startRecording('rendering');
3200 if (!empty($item['question-id'])) {
3202 'id' => $item['question-id'],
3203 'multiple' => $item['question-multiple'],
3204 'voters' => $item['question-voters'],
3205 'endtime' => $item['question-end-time']
3208 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3209 foreach ($options as $key => $option) {
3210 $percent = $question['voters'] ? ($option['replies'] / $question['voters'] * 100) : 0;
3212 $options[$key]['percent'] = $percent;
3214 if ($question['voters'] > 0) {
3215 $options[$key]['vote'] = DI::l10n()->t('%s (%d%s, %d votes)', $option['name'], round($percent, 1), '%', $option['replies']);
3217 $options[$key]['vote'] = DI::l10n()->t('%s (%d votes)', $option['name'], $option['replies']);
3221 if (!empty($question['voters']) && !empty($question['endtime'])) {
3222 $summary = DI::l10n()->t('%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3223 } elseif (!empty($question['voters'])) {
3224 $summary = DI::l10n()->t('%d voters.', $question['voters']);
3225 } elseif (!empty($question['endtime'])) {
3226 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3231 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3232 '$question' => $question,
3233 '$options' => $options,
3234 '$summary' => $summary,
3237 DI::profiler()->stopRecording();
3242 * get private link for item
3244 * @param array $item
3245 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3246 * @throws \Exception
3248 public static function getPlink(array $item)
3250 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3251 $plink = $item['plink'];
3252 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3253 $plink = $item['uri'];
3258 'href' => "display/" . $item['guid'],
3259 'orig' => "display/" . $item['guid'],
3260 'title' => DI::l10n()->t('View on separate page'),
3261 'orig_title' => DI::l10n()->t('View on separate page'),
3264 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3265 $author = ['uid' => 0, 'id' => $item['author-id'],
3266 'network' => $item['author-network'], 'url' => $item['author-link']];
3267 $plink = Contact::magicLinkByContact($author, $plink);
3270 if (!empty($plink)) {
3271 $ret['href'] = DI::baseUrl()->remove($plink);
3272 $ret['title'] = DI::l10n()->t('Link to source');
3274 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3278 'title' => DI::l10n()->t('Link to source'),
3279 'orig_title' => DI::l10n()->t('Link to source'),
3289 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3291 * @param int $uri_id
3293 * @return boolean "true" when it is a forum post
3295 public static function isForumPost(int $uri_id): bool
3297 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3298 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3306 * Search item id for given URI or plink
3308 * @param string $uri
3309 * @param integer $uid
3311 * @return integer item id
3313 public static function searchByLink(string $uri, int $uid = 0): int
3315 $ssl_uri = str_replace('http://', 'https://', $uri);
3316 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3318 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3319 if (DBA::isResult($item)) {
3323 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3324 if (DBA::isResult($item)) {
3332 * Return the URI for a link to the post
3334 * @param string $uri URI or link to post
3336 * @return string URI
3338 public static function getURIByLink(string $uri): string
3340 $ssl_uri = str_replace('http://', 'https://', $uri);
3341 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3343 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3344 if (DBA::isResult($item)) {
3345 return $item['uri'];
3348 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3349 if (DBA::isResult($item)) {
3350 return $item['uri'];
3357 * Fetches item for given URI or plink
3359 * @param string $uri
3360 * @param integer $uid
3362 * @return integer item id
3364 public static function fetchByLink(string $uri, int $uid = 0): int
3366 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3367 $item_id = self::searchByLink($uri, $uid);
3368 if (!empty($item_id)) {
3369 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3379 Hook::callAll('item_by_link', $hookData);
3381 if (isset($hookData['item_id'])) {
3382 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3385 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3386 $item_id = self::searchByLink($fetched_uri, $uid);
3388 $item_id = Diaspora::fetchByURL($uri);
3391 if (!empty($item_id)) {
3392 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3396 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3401 * Return share data from an item array (if the item is shared item)
3402 * We are providing the complete Item array, because at some time in the future
3403 * we hopefully will define these values not in the body anymore but in some item fields.
3404 * This function is meant to replace all similar functions in the system.
3406 * @param array $item
3408 * @return array with share information
3410 public static function getShareArray(array $item): array
3412 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3416 $attribute_string = $matches[2];
3417 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3418 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3419 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3420 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3427 * Fetch item information for shared items from the original items and adds it.
3429 * @param array $item
3431 * @return array item array with data from the original item
3433 public static function addShareDataFromOriginal(array $item): array
3435 $shared = self::getShareArray($item);
3436 if (empty($shared)) {
3440 // Real reshares always have got a GUID.
3441 if (empty($shared['guid'])) {
3445 $uid = $item['uid'] ?? 0;
3447 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3448 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3449 if (!DBA::isResult($shared_item)) {
3450 if (empty($shared['link'])) {
3454 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3455 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3457 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3461 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3462 if (!DBA::isResult($shared_item)) {
3465 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3467 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3470 if (!empty($shared_item['title'])) {
3471 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3472 unset($shared_item['title']);
3474 $body = $shared_item['body'];
3477 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3478 unset($shared_item['body']);
3480 return array_merge($item, $shared_item);
3484 * Check a prospective item array against user-level permissions
3486 * @param array $item Expected keys: uri, gravity, and
3487 * author-link if is author-id is set,
3488 * owner-link if is owner-id is set,
3489 * causer-link if is causer-id is set.
3490 * @param int $user_id Local user ID
3492 * @throws \Exception
3494 protected static function isAllowedByUser(array $item, int $user_id): bool
3496 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3497 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3501 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3502 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3506 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3507 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3508 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3512 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3513 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3521 * Improve the data in shared posts
3523 * @param array $item
3524 * @return string body
3526 public static function improveSharedDataInBody(array $item): string
3528 $shared = BBCode::fetchShareAttributes($item['body']);
3529 if (empty($shared['link'])) {
3530 return $item['body'];
3533 $id = self::fetchByLink($shared['link']);
3534 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3536 return $item['body'];
3539 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3540 if (!DBA::isResult($shared_item)) {
3541 return $item['body'];
3544 $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']);
3546 if (!empty($shared_item['title'])) {
3547 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3550 $shared_content .= $shared_item['body'];
3552 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3553 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3554 return $item['body'];