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 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
103 // Field list that is used to deliver items via the protocols
104 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
105 'parent-guid', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
106 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
107 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
108 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
109 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
110 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
111 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
112 'event-created', 'event-edited', 'event-start', 'event-finish',
113 'event-summary', 'event-desc', 'event-location', 'event-type',
114 'event-nofinish', 'event-ignore', 'event-id'];
116 // All fields in the item table
117 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
118 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
119 'contact-id', 'wall', 'gravity', 'extid', 'psid',
120 'created', 'edited', 'commented', 'received', 'changed', 'verb',
121 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
122 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
123 'private', 'pubmail', 'visible', 'starred',
124 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
125 'title', 'content-warning', 'body', 'location', 'coord', 'app',
126 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
127 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
128 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
130 // List of all verbs that don't need additional content data.
131 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
133 Activity::LIKE, Activity::DISLIKE,
134 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
143 * Update existing item entries
145 * @param array $fields The fields that are to be changed
146 * @param array $condition The condition for finding the item entries
148 * In the future we may have to change permissions as well.
149 * Then we had to add the user id as third parameter.
151 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
153 * @return integer|boolean number of affected rows - or "false" if there was an error
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
156 public static function update(array $fields, array $condition)
158 if (empty($condition) || empty($fields)) {
162 if (isset($fields['extid'])) {
163 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
166 if (!empty($fields['verb'])) {
167 $fields['vid'] = Verb::getID($fields['verb']);
170 if (!empty($fields['edited'])) {
171 $previous = Post::selectFirst(['edited'], $condition);
174 $rows = Post::update($fields, $condition);
175 if (is_bool($rows)) {
179 // We only need to call the line by line update for specific fields
180 if (empty($fields['body']) && empty($fields['file']) &&
181 empty($fields['attach']) && empty($fields['edited'])) {
185 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
187 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
191 while ($item = DBA::fetch($items)) {
192 if (!empty($fields['body'])) {
193 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
195 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
197 // Remove all media attachments from the body and store them in the post-media table
198 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
199 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
200 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
202 if ($item['author-network'] != Protocol::DFRN) {
203 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
206 Post\Content::update($item['uri-id'], $content_fields);
209 if (!empty($fields['file'])) {
210 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
213 if (!empty($fields['attach'])) {
214 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
217 // We only need to notfiy others when it is an original entry from us.
218 // Only call the notifier when the item had been edited and records had been changed.
219 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
220 $notify_items[] = $item['id'];
226 foreach ($notify_items as $notify_item) {
227 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
228 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
235 * Delete an item and notify others about it - if it was ours
237 * @param array $condition The condition for finding the item entries
238 * @param integer $priority Priority for the notification
239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
241 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
243 $items = Post::select(['id'], $condition);
244 while ($item = Post::fetch($items)) {
245 self::markForDeletionById($item['id'], $priority);
251 * Delete an item for an user and notify others about it - if it was ours
253 * @param array $condition The condition for finding the item entries
254 * @param integer $uid User who wants to delete this item
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 public static function deleteForUser($condition, $uid)
263 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
264 while ($item = Post::fetch($items)) {
265 if (in_array($item['uid'], [$uid, 0])) {
266 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
267 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
270 if ($item['uid'] == $uid) {
271 self::markForDeletionById($item['id'], PRIORITY_HIGH);
272 } elseif ($item['uid'] != 0) {
273 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
280 * Mark an item for deletion, delete related data and notify others about it - if it was ours
282 * @param integer $item_id
283 * @param integer $priority Priority for the notification
285 * @return boolean success
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
290 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
291 // locate item to be deleted
292 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
293 'deleted', 'resource-id', 'event-id',
294 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
295 $item = Post::selectFirst($fields, ['id' => $item_id]);
296 if (!DBA::isResult($item)) {
297 Logger::info('Item not found.', ['id' => $item_id]);
301 if ($item['deleted']) {
302 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
306 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
307 if (!DBA::isResult($parent)) {
308 $parent = ['origin' => false];
311 // clean up categories and tags so they don't end up as orphans
312 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
315 * If item is a link to a photo resource, nuke all the associated photos
316 * (visitors will not have photo resources)
317 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
318 * generate a resource-id and therefore aren't intimately linked to the item.
320 /// @TODO: this should first check if photo is used elsewhere
321 if (strlen($item['resource-id'])) {
322 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
325 // If item is a link to an event, delete the event.
326 if (intval($item['event-id'])) {
327 Event::delete($item['event-id']);
330 // If item has attachments, drop them
331 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
332 foreach($attachments as $attachment) {
333 if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
334 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
338 // Set the item to "deleted"
339 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
340 Post::update($item_fields, ['id' => $item['id']]);
342 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
344 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
345 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
348 Post\DeliveryData::delete($item['uri-id']);
350 // If it's the parent of a comment thread, kill all the kids
351 if ($item['gravity'] == GRAVITY_PARENT) {
352 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
355 // Is it our comment and/or our thread?
356 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
357 // When we delete the original post we will delete all existing copies on the server as well
358 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
360 // send the notification upstream/downstream
362 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
364 } elseif ($item['uid'] != 0) {
365 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
366 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
369 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
374 public static function guid($item, $notify)
376 if (!empty($item['guid'])) {
377 return trim($item['guid']);
381 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
382 // We add the hash of our own host because our host is the original creator of the post.
383 $prefix_host = DI::baseUrl()->getHostname();
387 // We are only storing the post so we create a GUID from the original hostname.
388 if (!empty($item['author-link'])) {
389 $parsed = parse_url($item['author-link']);
390 if (!empty($parsed['host'])) {
391 $prefix_host = $parsed['host'];
395 if (empty($prefix_host) && !empty($item['plink'])) {
396 $parsed = parse_url($item['plink']);
397 if (!empty($parsed['host'])) {
398 $prefix_host = $parsed['host'];
402 if (empty($prefix_host) && !empty($item['uri'])) {
403 $parsed = parse_url($item['uri']);
404 if (!empty($parsed['host'])) {
405 $prefix_host = $parsed['host'];
409 // Is it in the format data@host.tld? - Used for mail contacts
410 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
411 $mailparts = explode('@', $item['author-link']);
412 $prefix_host = array_pop($mailparts);
416 if (!empty($item['plink'])) {
417 $guid = self::guidFromUri($item['plink'], $prefix_host);
418 } elseif (!empty($item['uri'])) {
419 $guid = self::guidFromUri($item['uri'], $prefix_host);
421 $guid = System::createUUID(hash('crc32', $prefix_host));
427 private static function contactId($item)
429 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
430 return $item['contact-id'];
431 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
432 return $item['contact-id'];
433 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
434 return $item['author-id'];
435 } elseif (!empty($item['contact-id'])) {
436 return $item['contact-id'];
438 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
439 if (!empty($contact_id)) {
443 return $item['author-id'];
447 * Write an item array into a spool file to be inserted later.
448 * This command is called whenever there are issues storing an item.
450 * @param array $item The item fields that are to be inserted
453 private static function spool($orig_item)
455 // Now we store the data in the spool directory
456 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
457 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
459 $spoolpath = System::getSpoolPath();
460 if ($spoolpath != "") {
461 $spool = $spoolpath . '/' . $file;
463 file_put_contents($spool, json_encode($orig_item));
464 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
469 * Check if the item array is a duplicate
472 * @return boolean is it a duplicate?
474 private static function isDuplicate(array $item)
476 // Checking if there is already an item with the same guid
477 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
478 if (Post::exists($condition)) {
479 Logger::notice('Found already existing item', $condition);
483 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
484 'network' => [$item['network'], Protocol::DFRN]];
485 if (Post::exists($condition)) {
486 Logger::notice('duplicated item with the same uri found.', $condition);
490 // On Friendica and Diaspora the GUID is unique
491 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
492 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
493 if (Post::exists($condition)) {
494 Logger::notice('duplicated item with the same guid found.', $condition);
497 } elseif ($item['network'] == Protocol::OSTATUS) {
498 // Check for an existing post with the same content. There seems to be a problem with OStatus.
499 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
500 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
501 if (Post::exists($condition)) {
502 Logger::notice('duplicated item with the same body found.', $item);
508 * Check for already added items.
509 * There is a timing issue here that sometimes creates double postings.
510 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
512 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
513 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
521 * Check if the item array is valid
524 * @return boolean item is valid
526 public static function isValid(array $item)
528 // When there is no content then we don't post it
529 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
530 Logger::notice('No body, no title.');
534 if (!empty($item['uid'])) {
535 $owner = User::getOwnerDataById($item['uid'], false);
537 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
541 if ($owner['account_expired'] || $owner['account_removed']) {
542 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']]);
547 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
548 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
552 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
553 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
557 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
558 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
562 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
563 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
567 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
571 if ($item['verb'] == Activity::FOLLOW) {
572 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
573 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
574 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
578 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
579 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
580 if (Post::exists($condition)) {
581 // It happens that we receive multiple follow requests by the same author - we only store one.
582 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
591 * Check if the item array is too old
594 * @return boolean item is too old
596 public static function isTooOld(array $item)
598 // check for create date and expire time
599 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
601 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
602 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
603 $expire_interval = $user['expire'];
606 if (($expire_interval > 0) && !empty($item['created'])) {
607 $expire_date = time() - ($expire_interval * 86400);
608 $created_date = strtotime($item['created']);
609 if ($created_date < $expire_date) {
610 Logger::notice('Item created before expiration interval.', [
611 'created' => date('c', $created_date),
612 'expired' => date('c', $expire_date),
623 * Return the id of the given item array if it has been stored before
626 * @return integer item id
628 private static function getDuplicateID(array $item)
630 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
631 $condition = ["`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
632 $item['uri-id'], $item['uid'],
633 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
634 $existing = Post::selectFirst(['id', 'network'], $condition);
635 if (DBA::isResult($existing)) {
636 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
637 if ($item['uid'] != 0) {
638 Logger::notice('Item already existed for user', [
639 'uri-id' => $item['uri-id'],
640 'uid' => $item['uid'],
641 'network' => $item['network'],
642 'existing_id' => $existing["id"],
643 'existing_network' => $existing["network"]
647 return $existing["id"];
654 * Fetch top-level parent data for the given item array
657 * @return array item array with parent data
660 private static function getTopLevelParent(array $item)
662 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
663 'uri-id', 'parent-uri-id',
664 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
665 'wall', 'private', 'origin', 'author-id'];
666 $condition = ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']];
667 $params = ['order' => ['id' => false]];
668 $parent = Post::selectFirst($fields, $condition, $params);
670 if (!DBA::isResult($parent) && $item['origin']) {
671 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid']);
672 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
673 $parent = Post::selectFirst($fields, $condition, $params);
676 if (!DBA::isResult($parent)) {
677 Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
681 if ($parent['uri-id'] == $parent['parent-uri-id']) {
685 $condition = ['uri-id' => $parent['parent-uri-id'],
686 'parent-uri-id' => $parent['parent-uri-id'],
687 'uid' => $parent['uid']];
688 $params = ['order' => ['id' => false]];
689 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
691 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
692 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid']);
693 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
694 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
697 if (!DBA::isResult($toplevel_parent)) {
698 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
702 return $toplevel_parent;
706 * Get the gravity for the given item array
709 * @return integer gravity
711 private static function getGravity(array $item)
713 $activity = DI::activity();
715 if (isset($item['gravity'])) {
716 return intval($item['gravity']);
717 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
718 return GRAVITY_PARENT;
719 } elseif ($activity->match($item['verb'], Activity::POST)) {
720 return GRAVITY_COMMENT;
721 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
722 return GRAVITY_ACTIVITY;
723 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
724 return GRAVITY_ACTIVITY;
726 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
727 return GRAVITY_UNKNOWN; // Should not happen
730 public static function insert(array $item, int $notify = 0, bool $post_local = true)
734 $priority = PRIORITY_HIGH;
736 // If it is a posting where users should get notifications, then define it as wall posting
740 $item['network'] = Protocol::DFRN;
741 $item['protocol'] = Conversation::PARCEL_DIRECT;
742 $item['direction'] = Conversation::PUSH;
744 if (is_int($notify) && in_array($notify, PRIORITIES)) {
748 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
751 $uid = intval($item['uid']);
753 $item['guid'] = self::guid($item, $notify);
754 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
757 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
759 // Backward compatibility: parent-uri used to be the direct parent uri.
760 // If it is provided without a thr-parent, it probably is the old behavior.
761 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
762 $item['parent-uri'] = $item['thr-parent'];
764 $item['thr-parent-id'] = $item['parent-uri-id'] = ItemURI::getIdByURI($item['thr-parent']);
766 // Store conversation data
767 $item = Conversation::insert($item);
770 * Do we already have this item?
771 * We have to check several networks since Friendica posts could be repeated
772 * via OStatus (maybe Diasporsa as well)
774 $duplicate = self::getDuplicateID($item);
779 // Additional duplicate checks
780 /// @todo Check why the first duplication check returns the item number and the second a 0
781 if (self::isDuplicate($item)) {
785 if (!isset($item['post-type'])) {
786 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
789 $item['wall'] = intval($item['wall'] ?? 0);
790 $item['extid'] = trim($item['extid'] ?? '');
791 $item['author-name'] = trim($item['author-name'] ?? '');
792 $item['author-link'] = trim($item['author-link'] ?? '');
793 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
794 $item['owner-name'] = trim($item['owner-name'] ?? '');
795 $item['owner-link'] = trim($item['owner-link'] ?? '');
796 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
797 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
798 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
799 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
800 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
801 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
802 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
803 $item['location'] = trim($item['location'] ?? '');
804 $item['coord'] = trim($item['coord'] ?? '');
805 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
806 $item['deleted'] = 0;
807 $item['verb'] = trim($item['verb'] ?? '');
808 $item['object-type'] = trim($item['object-type'] ?? '');
809 $item['object'] = trim($item['object'] ?? '');
810 $item['target-type'] = trim($item['target-type'] ?? '');
811 $item['target'] = trim($item['target'] ?? '');
812 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
813 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
814 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
815 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
816 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
817 $item['private'] = intval($item['private'] ?? self::PUBLIC);
818 $item['body'] = trim($item['body'] ?? '');
819 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
820 $item['app'] = trim($item['app'] ?? '');
821 $item['origin'] = intval($item['origin'] ?? 0);
822 $item['postopts'] = trim($item['postopts'] ?? '');
823 $item['resource-id'] = trim($item['resource-id'] ?? '');
824 $item['event-id'] = intval($item['event-id'] ?? 0);
825 $item['inform'] = trim($item['inform'] ?? '');
826 $item['file'] = trim($item['file'] ?? '');
828 // Communities aren't working with the Diaspora protoccol
829 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
830 $user = User::getById($uid, ['account-type']);
831 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
832 Logger::info('Community posts are not supported via Diaspora');
837 // Items cannot be stored before they happen ...
838 if ($item['created'] > DateTimeFormat::utcNow()) {
839 $item['created'] = DateTimeFormat::utcNow();
842 // We haven't invented time travel by now.
843 if ($item['edited'] > DateTimeFormat::utcNow()) {
844 $item['edited'] = DateTimeFormat::utcNow();
847 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
849 $item['gravity'] = self::getGravity($item);
851 $item['language'] = self::getLanguage($item);
853 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
854 'photo' => $item['author-avatar'], 'network' => $item['network']];
855 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
857 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
858 'photo' => $item['owner-avatar'], 'network' => $item['network']];
859 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
861 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
862 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
863 $item['post-reason'] = self::PR_FOLLOWER;
866 // Ensure that there is an avatar cache
867 Contact::checkAvatarCache($item['author-id']);
868 Contact::checkAvatarCache($item['owner-id']);
870 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
871 $item["contact-id"] = self::contactId($item);
873 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
874 empty($item['origin']) &&self::isTooOld($item)) {
875 Logger::info('Item is too old', ['item' => $item]);
879 if (!self::isValid($item)) {
883 if ($item['gravity'] !== GRAVITY_PARENT) {
884 $toplevel_parent = self::getTopLevelParent($item);
885 if (empty($toplevel_parent)) {
889 // If the thread originated from this node, we check the permission against the thread starter
890 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
891 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
892 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
896 $parent_id = $toplevel_parent['id'];
897 $item['parent-uri'] = $toplevel_parent['uri'];
898 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
899 $item['deleted'] = $toplevel_parent['deleted'];
901 // Reshares have to keep their permissions to allow forums to work
902 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
903 $item['allow_cid'] = $toplevel_parent['allow_cid'];
904 $item['allow_gid'] = $toplevel_parent['allow_gid'];
905 $item['deny_cid'] = $toplevel_parent['deny_cid'];
906 $item['deny_gid'] = $toplevel_parent['deny_gid'];
909 $parent_origin = $toplevel_parent['origin'];
911 // Don't federate received participation messages
912 if ($item['verb'] != Activity::FOLLOW) {
913 $item['wall'] = $toplevel_parent['wall'];
915 $item['wall'] = false;
916 // Participations are technical messages, so they are set to "seen" automatically
917 $item['unseen'] = false;
921 * If the parent is private, force privacy for the entire conversation
922 * This differs from the above settings as it subtly allows comments from
923 * email correspondents to be private even if the overall thread is not.
925 if ($toplevel_parent['private']) {
926 $item['private'] = $toplevel_parent['private'];
929 // If its a post that originated here then tag the thread as "mention"
930 if ($item['origin'] && $item['uid']) {
931 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
932 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
935 // Update the contact relations
936 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
939 $parent_origin = $item['origin'];
942 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
943 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
945 // Is this item available in the global items (with uid=0)?
946 if ($item["uid"] == 0) {
947 $item["global"] = true;
949 // Set the global flag on all items if this was a global item entry
950 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
952 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
956 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
957 $item["private"] = self::PRIVATE;
960 if ($notify && $post_local) {
961 $item['edit'] = false;
962 $item['parent'] = $parent_id;
964 // Trigger automatic reactions for addons
965 if (!isset($item['api_source'])) {
966 $item['api_source'] = true;
969 // We have to tell the hooks who we are - this really should be improved
971 $_SESSION['authenticated'] = true;
972 $_SESSION['uid'] = $uid;
973 $dummy_session = true;
975 $dummy_session = false;
978 Hook::callAll('post_local', $item);
980 if ($dummy_session) {
981 unset($_SESSION['authenticated']);
982 unset($_SESSION['uid']);
984 } elseif (!$notify) {
985 Hook::callAll('post_remote', $item);
988 if (!empty($item['cancel'])) {
989 Logger::notice('post cancelled by addon.');
993 if (empty($item['vid']) && !empty($item['verb'])) {
994 $item['vid'] = Verb::getID($item['verb']);
997 // Creates or assigns the permission set
998 $item['psid'] = DI::permissionSet()->selectOrCreate(
999 DI::permissionSetFactory()->createFromString(
1007 if (!empty($item['extid'])) {
1008 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1011 if ($item['verb'] == Activity::ANNOUNCE) {
1012 self::setOwnerforResharedItem($item);
1015 if (isset($item['attachments'])) {
1016 foreach ($item['attachments'] as $attachment) {
1017 $attachment['uri-id'] = $item['uri-id'];
1018 Post\Media::insert($attachment);
1020 unset($item['attachments']);
1023 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1025 // Remove all media attachments from the body and store them in the post-media table
1026 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1027 $item['raw-body'] = self::setHashtags($item['raw-body']);
1029 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1030 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1033 // Check for hashtags in the body and repair or add hashtag links
1034 $item['body'] = self::setHashtags($item['body']);
1036 if (stristr($item['verb'], Activity::POKE)) {
1037 $notify_type = Delivery::POKE;
1039 $notify_type = Delivery::POST;
1042 // Filling item related side tables
1043 if (!empty($item['attach'])) {
1044 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1047 if (empty($item['event-id'])) {
1048 unset($item['event-id']);
1050 $ev = Event::fromBBCode($item['body']);
1051 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1052 Logger::info('Event found.');
1053 $ev['cid'] = $item['contact-id'];
1054 $ev['uid'] = $item['uid'];
1055 $ev['uri'] = $item['uri'];
1056 $ev['edited'] = $item['edited'];
1057 $ev['private'] = $item['private'];
1058 $ev['guid'] = $item['guid'];
1059 $ev['plink'] = $item['plink'];
1060 $ev['network'] = $item['network'];
1061 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1062 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1063 $ev['source'] = $item['source'] ?? '';
1065 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1066 if (DBA::isResult($event)) {
1067 $ev['id'] = $event['id'];
1070 $event_id = Event::store($ev);
1071 $item = Event::getItemArrayForImportedId($event_id, $item);
1073 Logger::info('Event was stored', ['id' => $event_id]);
1077 if (empty($item['causer-id'])) {
1078 unset($item['causer-id']);
1081 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1082 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1083 if (!empty($content_warning) && empty($item['content-warning'])) {
1084 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1088 Post::insert($item['uri-id'], $item);
1090 if ($item['gravity'] == GRAVITY_PARENT) {
1091 Post\Thread::insert($item['uri-id'], $item);
1094 if (!in_array($item['verb'], self::ACTIVITIES)) {
1095 Post\Content::insert($item['uri-id'], $item);
1098 // Create Diaspora signature
1099 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1100 $signed = Diaspora::createCommentSignature($item);
1101 if (!empty($signed)) {
1102 $item['diaspora_signed_text'] = json_encode($signed);
1106 if (!empty($item['diaspora_signed_text'])) {
1107 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1110 // Attached file links
1111 if (!empty($item['file'])) {
1112 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1115 // Delivery relevant data
1116 $delivery_data = Post\DeliveryData::extractFields($item);
1118 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1119 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1122 // Store tags from the body if this hadn't been handled previously in the protocol classes
1123 if (!Tag::existsForPost($item['uri-id'])) {
1124 Tag::storeFromBody($item['uri-id'], $item['body']);
1127 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1128 if (Post::exists($condition)) {
1129 Logger::notice('Item is already inserted - aborting', $condition);
1133 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1134 if (!$post_user_id) {
1135 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1139 if ($item['gravity'] == GRAVITY_PARENT) {
1140 $item['post-user-id'] = $post_user_id;
1141 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1144 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1146 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1147 if (!DBA::isResult($posted_item)) {
1148 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1149 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1150 self::spool($orig_item);
1154 // update the commented timestamp on the parent
1155 if (DI::config()->get('system', 'like_no_comment')) {
1156 // Update when it is a comment
1157 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1159 // Update when it isn't a follow or tag verb
1160 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1163 if ($update_commented) {
1164 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1166 $fields = ['changed' => DateTimeFormat::utcNow()];
1169 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1171 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1172 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1173 // Get the user information for the logging
1174 $user = User::getById($uid);
1176 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1181 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1182 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1184 Hook::callAll('post_local_end', $posted_item);
1186 Hook::callAll('post_remote_end', $posted_item);
1189 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1190 self::addShadow($post_user_id);
1192 self::addShadowPost($post_user_id);
1195 self::updateContact($posted_item);
1197 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1199 // Distribute items to users who subscribed to their tags
1200 self::distributeByTags($posted_item);
1202 // Automatically reshare the item if the "remote_self" option is selected
1203 self::autoReshare($posted_item);
1205 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1208 // Don't relay participation messages
1209 if (($posted_item['verb'] == Activity::FOLLOW) &&
1210 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1211 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1217 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1220 // Fill the cache with the rendered content.
1221 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1222 self::updateDisplayCache($posted_item['uri-id']);
1225 return $post_user_id;
1229 * Update the display cache
1231 * @param integer $uri_id
1234 public static function updateDisplayCache(int $uri_id)
1236 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1237 self::prepareBody($item, false, false, true);
1241 * Change the owner of a parent item if it had been shared by a forum
1243 * (public) forum posts in the new format consist of the regular post by the author
1244 * followed by an announce message sent from the forum account.
1245 * Changing the owner helps in grouping forum posts.
1247 * @param array $item
1250 private static function setOwnerforResharedItem(array $item)
1252 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1253 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1254 if (!DBA::isResult($parent)) {
1255 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1259 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1260 if (!DBA::isResult($author)) {
1261 Logger::error('Author not found', ['id' => $item['author-id']]);
1265 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1266 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1268 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1269 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1270 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1274 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1275 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1276 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']]);
1280 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1281 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1286 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1287 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1291 * Distribute the given item to users who subscribed to their tags
1293 * @param array $item Processed item
1295 private static function distributeByTags(array $item)
1297 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1301 $uids = Tag::getUIDListByURIId($item['uri-id']);
1302 foreach ($uids as $uid) {
1303 if (Contact::isSharing($item['author-id'], $uid)) {
1306 $fields = ['post-reason' => self::PR_TAG];
1309 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
1310 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
1315 * Distributes public items to the receivers
1317 * @param integer $itemid Item ID that should be added
1318 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1319 * @throws \Exception
1321 public static function distribute($itemid, $signed_text = '')
1323 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1324 $parent = Post::selectFirst(['owner-id'], $condition);
1325 if (!DBA::isResult($parent)) {
1326 Logger::warning('Item not found', ['condition' => $condition]);
1330 // Only distribute public items from native networks
1331 $condition = ['id' => $itemid, 'uid' => 0,
1332 'network' => array_merge(Protocol::FEDERATED ,['']),
1333 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1334 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
1335 if (!DBA::isResult($item)) {
1336 Logger::warning('Item not found', ['condition' => $condition]);
1340 $origin = $item['origin'];
1344 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1345 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1346 if (!DBA::isResult($owner)) {
1350 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1351 $contacts = DBA::select('contact', ['uid'], $condition);
1352 while ($contact = DBA::fetch($contacts)) {
1353 if ($contact['uid'] == 0) {
1357 $users[$contact['uid']] = $contact['uid'];
1359 DBA::close($contacts);
1361 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1362 $contacts = DBA::select('contact', ['uid'], $condition);
1363 while ($contact = DBA::fetch($contacts)) {
1364 if ($contact['uid'] == 0) {
1368 $users[$contact['uid']] = $contact['uid'];
1370 DBA::close($contacts);
1372 if (!empty($owner['alias'])) {
1373 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1374 $contacts = DBA::select('contact', ['uid'], $condition);
1375 while ($contact = DBA::fetch($contacts)) {
1376 if ($contact['uid'] == 0) {
1380 $users[$contact['uid']] = $contact['uid'];
1382 DBA::close($contacts);
1387 if ($item['uri-id'] != $item['parent-uri-id']) {
1388 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1389 while ($parent = Post::fetch($parents)) {
1390 $users[$parent['uid']] = $parent['uid'];
1391 if ($parent['origin'] && !$origin) {
1392 $origin_uid = $parent['uid'];
1395 DBA::close($parents);
1398 foreach ($users as $uid) {
1399 if ($origin_uid == $uid) {
1400 $item['diaspora_signed_text'] = $signed_text;
1402 self::storeForUser($item, $uid);
1407 * Store a public item defined by their URI-ID for the given users
1409 * @param integer $uri_id URI-ID of the given item
1410 * @param integer $uid The user that will receive the item entry
1411 * @param array $fields Additional fields to be stored
1412 * @param integer $source_uid User id of the source post
1413 * @return integer stored item id
1415 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0)
1417 if ($uid == $source_uid) {
1418 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1422 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => $source_uid]);
1423 if (!DBA::isResult($item)) {
1424 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1428 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1429 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']]);
1433 $item['post-reason'] = self::PR_STORED;
1435 $item = array_merge($item, $fields);
1437 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1439 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1440 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1441 !Contact::isSharingByURL($item['author-link'], $uid) &&
1442 !Contact::isSharingByURL($item['owner-link'], $uid)) {
1443 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1447 if (($uri_id != $item['thr-parent-id']) && (($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1448 // Fetch the origin user for the post
1449 $origin_uid = self::GetOriginUidForUriId($item['thr-parent-id'], $uid);
1450 if (is_null($origin_uid)) {
1451 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $item['thr-parent-id']]);
1455 $causer = $item['causer-id'] ?: $item['author-id'];
1456 $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1457 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1460 $stored = self::storeForUser($item, $uid);
1461 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1466 * Returns the origin uid of a post if the given user is allowed to see it.
1472 private static function GetOriginUidForUriId(int $uriid, int $uid)
1474 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1478 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1479 if (!empty($post)) {
1480 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1481 return $post['uid'];
1484 $pcid = Contact::getPublicIdByUserId($uid);
1489 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1490 if ($receiver == $pcid) {
1491 return $post['uid'];
1498 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1502 // When the post belongs to a a forum then all forum users are allowed to access it
1503 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1504 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1505 $target_uid = User::getIdForURL($tag['url']);
1506 if (!empty($target_uid)) {
1516 * Store a public item array for the given users
1518 * @param array $item The item entry that will be stored
1519 * @param integer $uid The user that will receive the item entry
1520 * @return integer stored item id
1521 * @throws \Exception
1523 private static function storeForUser(array $item, int $uid)
1525 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1526 if (!empty($item['event-id'])) {
1527 $post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1528 if (!empty($post['event-id'])) {
1529 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1530 if (!empty($event)) {
1531 // We aren't using "Event::store" here, since we don't want to trigger any further action
1532 $ret = DBA::update('event', $event, ['id' => $post['event-id']]);
1533 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $post['event-id'], 'ret' => $ret]);
1537 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1541 // Data from the "post-user" table
1543 unset($item['mention']);
1544 unset($item['starred']);
1545 unset($item['unseen']);
1546 unset($item['psid']);
1547 unset($item['pinned']);
1548 unset($item['ignored']);
1549 unset($item['pubmail']);
1550 unset($item['event-id']);
1551 unset($item['hidden']);
1552 unset($item['notification-type']);
1553 unset($item['post-reason']);
1555 // Data from the "post-delivery-data" table
1556 unset($item['postopts']);
1557 unset($item['inform']);
1559 $item['uid'] = $uid;
1560 $item['origin'] = 0;
1563 if ($item['gravity'] == GRAVITY_PARENT) {
1564 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1566 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1569 if (!empty($contact['id'])) {
1570 $item['contact-id'] = $contact['id'];
1572 // Shouldn't happen at all
1573 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1574 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1575 if (!DBA::isResult($self)) {
1576 // Shouldn't happen even less
1577 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1580 $item['contact-id'] = $self['id'];
1584 if ($item['gravity'] == GRAVITY_PARENT) {
1585 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1586 if (DBA::isResult($contact)) {
1587 $notify = self::isRemoteSelf($contact, $item);
1591 $distributed = self::insert($item, $notify);
1593 if (!$distributed) {
1594 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1596 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1598 return $distributed;
1602 * Add a shadow entry for a given item id that is a thread starter
1604 * We store every public item entry additionally with the user id "0".
1605 * This is used for the community page and for the search.
1606 * It is planned that in the future we will store public item entries only once.
1608 * @param integer $itemid Item ID that should be added
1609 * @throws \Exception
1611 private static function addShadow($itemid)
1613 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1614 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1615 $item = Post::selectFirst($fields, $condition);
1617 if (!DBA::isResult($item)) {
1621 // is it already a copy?
1622 if (($itemid == 0) || ($item['uid'] == 0)) {
1626 // Is it a visible public post?
1627 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1631 // is it an entry from a connector? Only add an entry for natively connected networks
1632 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1636 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1640 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1642 if (DBA::isResult($item)) {
1643 // Preparing public shadow (removing user specific data)
1646 unset($item['parent']);
1647 unset($item['wall']);
1648 unset($item['mention']);
1649 unset($item['origin']);
1650 unset($item['starred']);
1651 unset($item['postopts']);
1652 unset($item['inform']);
1653 unset($item['post-reason']);
1654 if ($item['uri-id'] == $item['parent-uri-id']) {
1655 $item['contact-id'] = $item['owner-id'];
1657 $item['contact-id'] = $item['author-id'];
1660 $public_shadow = self::insert($item);
1662 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1667 * Add a shadow entry for a given item id that is a comment
1669 * This function does the same like the function above - but for comments
1671 * @param integer $itemid Item ID that should be added
1672 * @throws \Exception
1674 private static function addShadowPost($itemid)
1676 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1677 if (!DBA::isResult($item)) {
1681 // Is it a toplevel post?
1682 if ($item['gravity'] == GRAVITY_PARENT) {
1683 self::addShadow($itemid);
1687 // Is this a shadow entry?
1688 if ($item['uid'] == 0) {
1692 // Is there a shadow parent?
1693 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1697 // Is there already a shadow entry?
1698 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1702 // Save "origin" and "parent" state
1703 $origin = $item['origin'];
1704 $parent = $item['parent'];
1706 // Preparing public shadow (removing user specific data)
1709 unset($item['parent']);
1710 unset($item['wall']);
1711 unset($item['mention']);
1712 unset($item['origin']);
1713 unset($item['starred']);
1714 unset($item['postopts']);
1715 unset($item['inform']);
1716 unset($item['post-reason']);
1717 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1719 $public_shadow = self::insert($item);
1721 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1723 // If this was a comment to a Diaspora post we don't get our comment back.
1724 // This means that we have to distribute the comment by ourselves.
1725 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1726 self::distribute($public_shadow);
1731 * Adds a language specification in a "language" element of given $arr.
1732 * Expects "body" element to exist in $arr.
1734 * @param array $item
1735 * @return string detected language
1736 * @throws \Text_LanguageDetect_Exception
1738 private static function getLanguage(array $item)
1740 if (!empty($item['language'])) {
1741 return $item['language'];
1744 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1748 // Convert attachments to links
1749 $naked_body = BBCode::removeAttachment($item['body']);
1750 if (empty($naked_body)) {
1754 // Remove links and pictures
1755 $naked_body = BBCode::removeLinks($naked_body);
1757 // Convert the title and the body to plain text
1758 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1760 // Remove possibly remaining links
1761 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1763 if (empty($naked_body)) {
1767 $availableLanguages = DI::l10n()->getAvailableLanguages();
1768 // See https://github.com/friendica/friendica/issues/10511
1769 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1770 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1771 $availableLanguages['fa'] = 'fa';
1773 $ld = new Language(array_keys($availableLanguages));
1774 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1775 if (is_array($languages)) {
1776 return json_encode($languages);
1782 public static function getLanguageMessage(array $item)
1784 $iso639 = new \Matriphe\ISO639\ISO639;
1786 $used_languages = '';
1787 foreach (json_decode($item['language'], true) as $language => $reliability) {
1788 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1790 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1791 return $used_languages;
1795 * Creates an unique guid out of a given uri.
1796 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1797 * Posts that are created on this system are using System::createUUID.
1798 * Received ActivityPub posts are using Processor::getGUIDByURL.
1800 * @param string $uri uri of an item entry
1801 * @param string $host hostname for the GUID prefix
1802 * @return string unique guid
1804 public static function guidFromUri($uri, $host)
1806 // Our regular guid routine is using this kind of prefix as well
1807 // We have to avoid that different routines could accidentally create the same value
1808 $parsed = parse_url($uri);
1810 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1811 unset($parsed["scheme"]);
1813 // Glue it together to be able to make a hash from it
1814 $host_id = implode("/", $parsed);
1816 // Use a mixture of several hashes to provide some GUID like experience
1817 return hash("crc32", $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1821 * generate an unique URI
1823 * @param integer $uid User id
1824 * @param string $guid An existing GUID (Otherwise it will be generated)
1827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1829 public static function newURI($uid, $guid = "")
1832 $guid = System::createUUID();
1835 return DI::baseUrl()->get() . '/objects/' . $guid;
1839 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1841 * This can be used to filter for inactive contacts.
1842 * Only do this for public postings to avoid privacy problems, since poco data is public.
1843 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1845 * @param array $arr Contains the just posted item record
1846 * @throws \Exception
1848 private static function updateContact($arr)
1850 // Unarchive the author
1851 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1852 if (DBA::isResult($contact)) {
1853 Contact::unmarkForArchival($contact);
1856 // Unarchive the contact if it's not our own contact
1857 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1858 if (DBA::isResult($contact)) {
1859 Contact::unmarkForArchival($contact);
1862 /// @todo On private posts we could obfuscate the date
1863 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1865 // Is it a forum? Then we don't care about the rules from above
1866 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1867 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1873 // The "self" contact id is used (for example in the connectors) when the contact is unknown
1874 // So we have to ensure to only update the last item when it had been our own post,
1875 // or it had been done by a "regular" contact.
1876 if (!empty($arr['wall'])) {
1877 $condition = ['id' => $arr['contact-id']];
1879 $condition = ['id' => $arr['contact-id'], 'self' => false];
1881 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1883 // Now do the same for the system wide contacts with uid=0
1884 if ($arr['private'] != self::PRIVATE) {
1885 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1886 ['id' => $arr['owner-id']]);
1888 if ($arr['owner-id'] != $arr['author-id']) {
1889 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1890 ['id' => $arr['author-id']]);
1895 public static function setHashtags($body)
1897 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1898 $tags = BBCode::getTags($body);
1901 if (!count($tags)) {
1905 // This sorting is important when there are hashtags that are part of other hashtags
1906 // Otherwise there could be problems with hashtags like #test and #test2
1907 // Because of this we are sorting from the longest to the shortest tag.
1908 usort($tags, function ($a, $b) {
1909 return strlen($b) <=> strlen($a);
1912 $URLSearchString = "^\[\]";
1914 // All hashtags should point to the home server if "local_tags" is activated
1915 if (DI::config()->get('system', 'local_tags')) {
1916 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1917 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1920 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1921 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1923 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1926 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1928 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1931 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1933 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1936 // Repair recursive urls
1937 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1940 foreach ($tags as $tag) {
1941 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
1945 $basetag = str_replace('_', ' ', substr($tag, 1));
1946 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1948 $body = str_replace($tag, $newtag, $body);
1951 // Convert back the masked hashtags
1952 $body = str_replace("#", "#", $body);
1961 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1964 * @param int $item_id
1965 * @return boolean true if item was deleted, else false
1966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1967 * @throws \ImagickException
1969 private static function tagDeliver($uid, $item_id)
1973 $owner = User::getOwnerDataById($uid);
1974 if (!DBA::isResult($owner)) {
1975 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
1979 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1980 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
1984 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
1985 if (!DBA::isResult($item)) {
1986 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
1990 if ($item['gravity'] == GRAVITY_PARENT) {
1991 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
1992 foreach ($tags as $tag) {
1993 if (Strings::compareLink($owner['url'], $tag['url'])) {
1995 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']]);
2000 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2001 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2005 $arr = ['item' => $item, 'user' => $owner];
2007 Hook::callAll('tagged', $arr);
2009 $tags = Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2010 foreach ($tags as $tag) {
2011 if (Strings::compareLink($owner['url'], $tag['url'])) {
2013 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']]);
2018 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2023 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2025 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2027 $allow_gid = '<' . Group::FOLLOWERS . '>';
2030 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2032 self::performActivity($item['id'], 'announce', $uid);
2035 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2040 * Automatically reshare the item if the "remote_self" option is selected
2042 * @param array $item
2045 private static function autoReshare(array $item)
2047 if ($item['gravity'] != GRAVITY_PARENT) {
2051 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2055 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2059 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2061 self::performActivity($item['id'], 'announce', $item['uid']);
2064 public static function isRemoteSelf($contact, &$datarray)
2066 if (!$contact['remote_self']) {
2070 // Prevent the forwarding of posts that are forwarded
2071 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2072 Logger::info('Already forwarded');
2076 // Prevent to forward already forwarded posts
2077 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2078 Logger::info('Already forwarded (second test)');
2082 // Only forward posts
2083 if ($datarray["verb"] != Activity::POST) {
2084 Logger::info('No post');
2088 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2089 Logger::info('Not public');
2093 $datarray2 = $datarray;
2094 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2095 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2096 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2097 ['uid' => $contact['uid'], 'self' => true]);
2098 if (DBA::isResult($self)) {
2099 $datarray['contact-id'] = $self["id"];
2101 $datarray['owner-name'] = $self["name"];
2102 $datarray['owner-link'] = $self["url"];
2103 $datarray['owner-avatar'] = $self["thumb"];
2105 $datarray['author-name'] = $datarray['owner-name'];
2106 $datarray['author-link'] = $datarray['owner-link'];
2107 $datarray['author-avatar'] = $datarray['owner-avatar'];
2109 unset($datarray['edited']);
2111 unset($datarray['network']);
2112 unset($datarray['owner-id']);
2113 unset($datarray['author-id']);
2116 if ($contact['network'] != Protocol::FEED) {
2117 $old_uri_id = $datarray["uri-id"] ?? 0;
2118 $datarray["guid"] = System::createUUID();
2119 unset($datarray["plink"]);
2120 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2121 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2122 $datarray["extid"] = Protocol::DFRN;
2123 $urlpart = parse_url($datarray2['author-link']);
2124 $datarray["app"] = $urlpart["host"];
2125 if (!empty($old_uri_id)) {
2126 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2129 unset($datarray["parent-uri"]);
2130 unset($datarray["thr-parent"]);
2132 $datarray['private'] = self::PUBLIC;
2136 if ($contact['network'] != Protocol::FEED) {
2137 // Store the original post
2138 $result = self::insert($datarray2);
2139 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2141 $datarray["app"] = "Feed";
2145 return (bool)$result;
2152 * @param array $item
2155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2156 * @throws \ImagickException
2158 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2160 if (DI::config()->get('system', 'disable_embedded')) {
2164 Logger::info('check for photos');
2165 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2170 $img_start = strpos($orig_body, '[img');
2171 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2172 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2174 while (($img_st_close !== false) && ($img_len !== false)) {
2175 $img_st_close++; // make it point to AFTER the closing bracket
2176 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2178 Logger::info('found photo', ['image' => $image]);
2180 if (stristr($image, $site . '/photo/')) {
2181 // Only embed locally hosted photos
2183 $i = basename($image);
2184 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2185 $x = strpos($i, '-');
2188 $res = substr($i, $x + 1);
2189 $i = substr($i, 0, $x);
2190 $photo = Photo::getPhotoForUser($uid, $i, $res);
2191 if (DBA::isResult($photo)) {
2193 * Check to see if we should replace this photo link with an embedded image
2194 * 1. No need to do so if the photo is public
2195 * 2. If there's a contact-id provided, see if they're in the access list
2196 * for the photo. If so, embed it.
2197 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2198 * permissions, regardless of order but first check to see if they're an exact
2199 * match to save some processing overhead.
2201 if (self::hasPermissions($photo)) {
2203 $recips = self::enumeratePermissions($photo);
2204 if (in_array($cid, $recips)) {
2208 if (self::samePermissions($uid, $item, $photo)) {
2214 $photo_img = Photo::getImageForPhoto($photo);
2215 // If a custom width and height were specified, apply before embedding
2216 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2217 Logger::info('scaling photo');
2219 $width = intval($match[1]);
2220 $height = intval($match[2]);
2222 $photo_img->scaleDown(max($width, $height));
2225 $data = $photo_img->asString();
2226 $type = $photo_img->getType();
2228 Logger::info('replacing photo');
2229 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2230 Logger::debug('replaced', ['image' => $image]);
2236 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2237 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2238 if ($orig_body === false) {
2242 $img_start = strpos($orig_body, '[img');
2243 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2244 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2247 $new_body = $new_body . $orig_body;
2252 private static function hasPermissions($obj)
2254 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2255 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2258 private static function samePermissions($uid, $obj1, $obj2)
2260 // first part is easy. Check that these are exactly the same.
2261 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2262 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2263 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2264 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2268 // This is harder. Parse all the permissions and compare the resulting set.
2269 $recipients1 = self::enumeratePermissions($obj1);
2270 $recipients2 = self::enumeratePermissions($obj2);
2274 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2275 return ($recipients1 == $recipients2);
2279 * Returns an array of contact-ids that are allowed to see this object
2281 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2282 * @param bool $check_dead Prunes unavailable contacts from the result
2284 * @throws \Exception
2286 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2288 $aclFormater = DI::aclFormatter();
2290 $allow_people = $aclFormater->expand($obj['allow_cid']);
2291 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2292 $deny_people = $aclFormater->expand($obj['deny_cid']);
2293 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2294 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2295 $deny = array_unique(array_merge($deny_people, $deny_groups));
2296 $recipients = array_diff($recipients, $deny);
2300 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2302 if (!$uid || ($days < 1)) {
2306 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2307 $uid, GRAVITY_PARENT];
2310 * $expire_network_only = save your own wall posts
2311 * and just expire conversations started by others
2313 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2315 if ($expire_network_only) {
2316 $condition[0] .= " AND NOT `wall`";
2319 if ($network != "") {
2320 $condition[0] .= " AND `network` = ?";
2321 $condition[] = $network;
2324 $condition[0] .= " AND `received` < ?";
2325 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2327 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2329 if (!DBA::isResult($items)) {
2333 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2335 // Forcing expiring of items - but not notes and marked items
2337 $expire_items = true;
2340 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2341 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2342 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2346 $priority = DI::config()->get('system', 'expire-notify-priority');
2348 while ($item = Post::fetch($items)) {
2349 // don't expire filed items
2350 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2354 // Only expire posts, not photos and photo comments
2356 if (!$expire_photos && !empty($item['resource-id'])) {
2358 } elseif (!$expire_starred && intval($item['starred'])) {
2360 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2362 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2366 self::markForDeletionById($item['id'], $priority);
2371 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2374 public static function firstPostDate($uid, $wall = false)
2376 $user = User::getById($uid, ['register_date']);
2381 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2382 $uid, $wall, $user['register_date']];
2383 $params = ['order' => ['received' => false]];
2384 $thread = Post::selectFirstThread(['received'], $condition, $params);
2385 if (DBA::isResult($thread)) {
2386 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2393 * add/remove activity to an item
2395 * Toggle activities as like,dislike,attend of an item
2397 * @param int $item_id
2398 * @param string $verb
2399 * Activity verb. One of
2400 * like, unlike, dislike, undislike, attendyes, unattendyes,
2401 * attendno, unattendno, attendmaybe, unattendmaybe,
2402 * announce, unannouce
2404 * @param string $allow_cid
2405 * @param string $allow_gid
2406 * @param string $deny_cid
2407 * @param string $deny_gid
2409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2410 * @throws \ImagickException
2411 * @hook 'post_local_end'
2413 * 'post_id' => ID of posted item
2415 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)
2421 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2423 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2424 if (!DBA::isResult($item)) {
2425 Logger::notice('like: unknown item', ['id' => $item_id]);
2429 $uri_id = $item['uri-id'];
2431 if (!in_array($item['uid'], [0, $uid])) {
2435 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2436 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
2437 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2438 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2439 if (!DBA::isResult($item)) {
2440 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2446 // Retrieves the local post owner
2447 $owner = User::getOwnerDataById($uid);
2448 if (empty($owner)) {
2449 Logger::info('Empty owner for user', ['uid' => $uid]);
2453 // Retrieve the current logged in user's public contact
2454 $author_id = Contact::getIdForURL($owner['url']);
2455 if (empty($author_id)) {
2456 Logger::info('Empty public contact');
2464 $activity = Activity::LIKE;
2468 $activity = Activity::DISLIKE;
2472 $activity = Activity::ATTEND;
2476 $activity = Activity::ATTENDNO;
2479 case 'unattendmaybe':
2480 $activity = Activity::ATTENDMAYBE;
2484 $activity = Activity::FOLLOW;
2488 $activity = Activity::ANNOUNCE;
2491 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2495 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2497 // Enable activity toggling instead of on/off
2498 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2500 // Look for an existing verb row
2501 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2502 if ($event_verb_flag) {
2503 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2505 // Translate to the index based activity index
2507 foreach ($verbs as $verb) {
2508 $vids[] = Verb::getID($verb);
2511 $vids = Verb::getID($activity);
2514 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2515 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2516 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2518 if (DBA::isResult($like_item)) {
2520 * Truth table for existing activities
2522 * | Inputs || Outputs |
2523 * |----------------------------||-------------------|
2524 * | Mode | Event | Same verb || Delete? | Return? |
2525 * |--------|-------|-----------||---------|---------|
2526 * | create | Yes | Yes || No | Yes |
2527 * | create | Yes | No || Yes | No |
2528 * | create | No | Yes || No | Yes |
2529 * | create | No | No || N/A†|
2530 * | delete | Yes | Yes || Yes | N/A‡ |
2531 * | delete | Yes | No || No | N/A‡ |
2532 * | delete | No | Yes || Yes | N/A‡ |
2533 * | delete | No | No || N/A†|
2534 * |--------|-------|-----------||---------|---------|
2535 * | A | B | C || A xor C | !B or C |
2537 * †Can't happen: It's impossible to find an existing non-event activity without
2538 * the same verb because we are only looking for this single verb.
2540 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2542 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2543 self::markForDeletionById($like_item['id']);
2546 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2551 // No need to go further if we aren't creating anything
2552 if ($mode == 'delete') {
2556 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2559 'guid' => System::createUUID(),
2560 'uri' => self::newURI($item['uid']),
2561 'uid' => $item['uid'],
2562 'contact-id' => $owner['id'],
2563 'wall' => $item['wall'],
2565 'network' => Protocol::DFRN,
2566 'protocol' => Conversation::PARCEL_DIRECT,
2567 'direction' => Conversation::PUSH,
2568 'gravity' => GRAVITY_ACTIVITY,
2569 'parent' => $item['id'],
2570 'thr-parent' => $item['uri'],
2571 'owner-id' => $author_id,
2572 'author-id' => $author_id,
2573 'body' => $activity,
2574 'verb' => $activity,
2575 'object-type' => $objtype,
2576 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2577 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2578 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2579 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2584 $signed = Diaspora::createLikeSignature($uid, $new_item);
2585 if (!empty($signed)) {
2586 $new_item['diaspora_signed_text'] = json_encode($signed);
2589 $new_item_id = self::insert($new_item);
2591 // If the parent item isn't visible then set it to visible
2592 if (!$item['visible']) {
2593 self::update(['visible' => true], ['id' => $item['id']]);
2596 $new_item['id'] = $new_item_id;
2598 Hook::callAll('post_local_end', $new_item);
2604 * Fetch the SQL condition for the given user id
2606 * @param integer $owner_id User ID for which the permissions should be fetched
2607 * @return array condition
2609 public static function getPermissionsConditionArrayByUserId(int $owner_id)
2611 $local_user = local_user();
2612 $remote_user = Session::getRemoteContactID($owner_id);
2614 // default permissions - anonymous user
2615 $condition = ["`private` != ?", self::PRIVATE];
2617 if ($local_user && ($local_user == $owner_id)) {
2618 // Profile owner - everything is visible
2620 } elseif ($remote_user) {
2621 // Authenticated visitor - fetch the matching permissionsets
2622 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2624 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2625 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2626 self::PRIVATE, self::PRIVATE];
2627 $condition = array_merge($condition, $permissionSets->column('id'));
2635 * Get a permission SQL string for the given user
2637 * @param int $owner_id
2638 * @param string $table
2641 public static function getPermissionsSQLByUserId(int $owner_id, string $table = '')
2643 $local_user = local_user();
2644 $remote_user = Session::getRemoteContactID($owner_id);
2646 if (!empty($table)) {
2647 $table = DBA::quoteIdentifier($table) . '.';
2651 * Construct permissions
2653 * default permissions - anonymous user
2655 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2657 // Profile owner - everything is visible
2658 if ($local_user && ($local_user == $owner_id)) {
2660 } elseif ($remote_user) {
2662 * Authenticated visitor. Unless pre-verified,
2663 * check that the contact belongs to this $owner_id
2664 * and load the groups the visitor belongs to.
2665 * If pre-verified, the caller is expected to have already
2666 * done this and passed the groups into this function.
2668 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2671 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2676 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2683 * get translated item type
2685 * @param array $item
2686 * @param \Friendica\Core\L10n $l10n
2689 public static function postType(array $item, \Friendica\Core\L10n $l10n)
2691 if (!empty($item['event-id'])) {
2692 return $l10n->t('event');
2693 } elseif (!empty($item['resource-id'])) {
2694 return $l10n->t('photo');
2695 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2696 return $l10n->t('activity');
2697 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2698 return $l10n->t('comment');
2701 return $l10n->t('post');
2705 * Sets the "rendered-html" field of the provided item
2707 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2709 * @param array $item
2711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2712 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2714 private static function putInCache(&$item)
2716 // Save original body to prevent addons to modify it
2717 $body = $item['body'];
2719 $rendered_hash = $item['rendered-hash'] ?? '';
2720 $rendered_html = $item['rendered-html'] ?? '';
2722 if ($rendered_hash == ''
2723 || $rendered_html == ''
2724 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2725 || DI::config()->get('system', 'ignore_cache')
2727 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2728 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2730 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2731 Hook::callAll('put_item_in_cache', $hook_data);
2732 $item['rendered-html'] = $hook_data['rendered-html'];
2733 $item['rendered-hash'] = $hook_data['rendered-hash'];
2736 // Update if the generated values differ from the existing ones
2737 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2740 'rendered-html' => $item['rendered-html'],
2741 'rendered-hash' => $item['rendered-hash']
2743 ['id' => $item['id']]
2748 $item['body'] = $body;
2752 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2753 * If attach is true, also add icons for item attachments.
2755 * @param array $item
2756 * @param boolean $attach
2757 * @param boolean $is_preview
2758 * @param boolean $only_cache
2759 * @return string item body html
2760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2761 * @throws \ImagickException
2762 * @hook prepare_body_init item array before any work
2763 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2764 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2765 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2767 public static function prepareBody(array &$item, $attach = false, $is_preview = false, $only_cache = false)
2770 Hook::callAll('prepare_body_init', $item);
2772 // In order to provide theme developers more possibilities, event items
2773 // are treated differently.
2774 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2775 $ev = Event::getItemHTML($item);
2779 $tags = Tag::populateFromItem($item);
2781 $item['tags'] = $tags['tags'];
2782 $item['hashtags'] = $tags['hashtags'];
2783 $item['mentions'] = $tags['mentions'];
2785 $body = $item['body'] ?? '';
2786 $shared = BBCode::fetchShareAttributes($body);
2787 if (!empty($shared['guid'])) {
2788 $shared_item = Post::selectFirst(['uri-id', 'plink'], ['guid' => $shared['guid']]);
2789 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2790 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2791 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid']);
2792 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2793 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2794 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2795 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2800 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links);
2801 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2803 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2804 self::putInCache($item);
2805 $item['body'] = $body;
2806 $s = $item["rendered-html"];
2812 // Compile eventual content filter reasons
2813 $filter_reasons = [];
2814 if (!$is_preview && public_contact() != $item['author-id']) {
2815 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2816 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2819 $item['attachments'] = $attachments;
2823 'filter_reasons' => $filter_reasons
2825 Hook::callAll('prepare_body_content_filter', $hook_data);
2826 $filter_reasons = $hook_data['filter_reasons'];
2833 'preview' => $is_preview,
2834 'filter_reasons' => $filter_reasons
2836 Hook::callAll('prepare_body', $hook_data);
2837 $s = $hook_data['html'];
2841 // Replace the blockquotes with quotes that are used in mails.
2842 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2843 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2847 if (!empty($shared_attachments)) {
2848 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2849 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2850 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2851 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2854 $s = self::addVisualAttachments($attachments, $item, $s, false);
2855 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2856 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2857 $s = self::addQuestions($item, $s);
2860 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2861 $x = Map::byCoordinates(trim($item['coord']));
2863 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2867 // Replace friendica image url size with theme preference.
2868 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2869 $ps = $a->getThemeInfoValue('item_image_size');
2870 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2873 $s = HTML::applyContentFilter($s, $filter_reasons);
2875 $hook_data = ['item' => $item, 'html' => $s];
2876 Hook::callAll('prepare_body_final', $hook_data);
2878 return $hook_data['html'];
2882 * Check if the body contains a link
2884 * @param string $body
2885 * @param string $url
2889 public static function containsLink(string $body, string $url, int $type = 0)
2891 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2892 $urlparts = parse_url($url);
2893 unset($urlparts['query']);
2894 unset($urlparts['fragment']);
2895 $url = Network::unparseURL($urlparts);
2897 // Remove media links to only search in embedded content
2898 // @todo Check images for image link, audio for audio links, ...
2899 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2900 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2903 if (strpos($body, $url)) {
2906 foreach ([0, 1, 2] as $size) {
2907 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2908 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2916 * Replace visual attachments in the body
2918 * @param array $attachments
2919 * @param string $body
2920 * @return string modified body
2922 private static function replaceVisualAttachments(array $attachments, string $body)
2924 DI::profiler()->startRecording('rendering');
2926 foreach ($attachments['visual'] as $attachment) {
2927 if (!empty($attachment['preview'])) {
2928 $body = str_replace($attachment['preview'], Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE), $body);
2929 } elseif ($attachment['filetype'] == 'image') {
2930 $body = str_replace($attachment['url'], Post\Media::getUrlForId($attachment['id']), $body);
2933 DI::profiler()->stopRecording();
2938 * Add visual attachments to the content
2940 * @param array $attachments
2941 * @param array $item
2942 * @param string $content
2943 * @return string modified content
2945 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared)
2947 DI::profiler()->startRecording('rendering');
2951 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
2952 foreach ($attachments['visual'] as $attachment) {
2953 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
2957 if (!empty($attachment['preview'])) {
2958 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2963 if (($attachment['filetype'] == 'video')) {
2964 /// @todo Move the template to /content as well
2965 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
2967 'id' => $attachment['id'],
2968 'src' => $attachment['url'],
2969 'name' => $attachment['name'] ?: $attachment['url'],
2970 'preview' => $preview_url,
2971 'mime' => $attachment['mimetype'],
2974 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
2977 $trailing .= $media;
2979 } elseif ($attachment['filetype'] == 'audio') {
2980 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
2982 'id' => $attachment['id'],
2983 'src' => $attachment['url'],
2984 'name' => $attachment['name'] ?: $attachment['url'],
2985 'mime' => $attachment['mimetype'],
2988 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
2991 $trailing .= $media;
2993 } elseif ($attachment['filetype'] == 'image') {
2994 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
2996 'src' => Post\Media::getUrlForId($attachment['id']),
2997 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
2998 'attachment' => $attachment,
3001 // On Diaspora posts the attached pictures are leading
3002 if ($item['network'] == Protocol::DIASPORA) {
3005 $trailing .= $media;
3011 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3012 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3014 if ($leading != '') {
3015 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3018 if ($trailing != '') {
3019 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3023 DI::profiler()->stopRecording();
3028 * Add link attachment to the content
3030 * @param array $attachments
3031 * @param string $body
3032 * @param string $content
3033 * @param bool $shared
3034 * @param array $ignore_links A list of URLs to ignore
3035 * @return string modified content
3037 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links)
3039 DI::profiler()->startRecording('rendering');
3040 // Don't show a preview when there is a visual attachment (audio or video)
3041 $types = array_column($attachments['visual'], 'type');
3042 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3044 if (!empty($attachments['link'])) {
3045 foreach ($attachments['link'] as $link) {
3047 foreach ($ignore_links as $ignore_link) {
3048 if (Strings::compareLink($link['url'], $ignore_link)) {
3052 // @todo Judge between the links to use the one with most information
3053 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3054 (empty($attachment['name']) && !empty($link['name'])) ||
3055 (empty($attachment['description']) && !empty($link['description'])) ||
3056 (empty($attachment['preview']) && !empty($link['preview'])))) {
3057 $attachment = $link;
3062 if (!empty($attachment)) {
3065 'author_name' => $attachment['author-name'] ?? '',
3066 'author_url' => $attachment['author-url'] ?? '',
3067 'description' => $attachment['description'] ?? '',
3070 'provider_name' => $attachment['publisher-name'] ?? '',
3071 'provider_url' => $attachment['publisher-url'] ?? '',
3073 'title' => $attachment['name'] ?? '',
3075 'url' => $attachment['url']];
3077 if ($preview && !empty($attachment['preview'])) {
3078 if ($attachment['preview-width'] >= 500) {
3079 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3081 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3085 if (!empty($data['description']) && !empty($content)) {
3086 similar_text($data['description'], $content, $percent);
3091 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3092 $data['description'] = '';
3095 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3096 $data['author_name'] = '';
3099 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3100 $data['author_url'] = '';
3102 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3103 $data = BBCode::getAttachmentData($match[1]);
3105 DI::profiler()->stopRecording();
3107 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3108 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3109 $parts = parse_url($data['url']);
3110 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3111 if (empty($data['provider_name'])) {
3112 $data['provider_name'] = $parts['host'];
3114 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3115 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3117 if (!empty($parts['port'])) {
3118 $data['provider_url'] .= ':' . $parts['port'];
3123 // @todo Use a template
3124 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3125 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3126 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3127 '$url' => $data['url'],
3128 '$title' => $data['title'],
3135 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3137 return $content . $rendered;
3144 * Add non visual attachments to the content
3146 * @param array $attachments
3147 * @param array $item
3148 * @param string $content
3149 * @return string modified content
3151 private static function addNonVisualAttachments(array $attachments, array $item, string $content)
3153 DI::profiler()->startRecording('rendering');
3155 foreach ($attachments['additional'] as $attachment) {
3156 if (strpos($item['body'], $attachment['url'])) {
3160 $author = ['uid' => 0, 'id' => $item['author-id'],
3161 'network' => $item['author-network'], 'url' => $item['author-link']];
3162 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3164 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3166 if (!empty($attachment['size'])) {
3167 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3170 /// @todo Use a template
3171 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3172 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3175 if ($trailing != '') {
3176 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3179 DI::profiler()->stopRecording();
3183 private static function addQuestions(array $item, string $content)
3185 DI::profiler()->startRecording('rendering');
3186 if (!empty($item['question-id'])) {
3188 'id' => $item['question-id'],
3189 'multiple' => $item['question-multiple'],
3190 'voters' => $item['question-voters'],
3191 'endtime' => $item['question-end-time']
3194 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3195 foreach ($options as $key => $option) {
3196 $percent = $question['voters'] ? ($option['replies'] / $question['voters'] * 100) : 0;
3198 $options[$key]['percent'] = $percent;
3199 $options[$key]['vote'] = DI::l10n()->t('%s (%d%s, %d votes)', $option['name'], round($percent, 1), '%', $option['replies']);
3202 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3203 '$question' => $question,
3204 '$options' => $options,
3205 '$summary' => DI::l10n()->t('%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime'])),
3208 DI::profiler()->stopRecording();
3213 * get private link for item
3215 * @param array $item
3216 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3217 * @throws \Exception
3219 public static function getPlink($item)
3221 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3222 $plink = $item['plink'];
3223 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3224 $plink = $item['uri'];
3229 'href' => "display/" . $item['guid'],
3230 'orig' => "display/" . $item['guid'],
3231 'title' => DI::l10n()->t('View on separate page'),
3232 'orig_title' => DI::l10n()->t('View on separate page'),
3235 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3236 $author = ['uid' => 0, 'id' => $item['author-id'],
3237 'network' => $item['author-network'], 'url' => $item['author-link']];
3238 $plink = Contact::magicLinkByContact($author, $plink);
3241 if (!empty($plink)) {
3242 $ret['href'] = DI::baseUrl()->remove($plink);
3243 $ret['title'] = DI::l10n()->t('Link to source');
3245 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3249 'title' => DI::l10n()->t('Link to source'),
3250 'orig_title' => DI::l10n()->t('Link to source'),
3260 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3262 * @param int $uri_id
3264 * @return boolean "true" when it is a forum post
3266 public static function isForumPost(int $uri_id)
3268 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3269 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3277 * Search item id for given URI or plink
3279 * @param string $uri
3280 * @param integer $uid
3282 * @return integer item id
3284 public static function searchByLink($uri, $uid = 0)
3286 $ssl_uri = str_replace('http://', 'https://', $uri);
3287 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3289 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3290 if (DBA::isResult($item)) {
3294 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3295 if (DBA::isResult($item)) {
3303 * Return the URI for a link to the post
3305 * @param string $uri URI or link to post
3307 * @return string URI
3309 public static function getURIByLink(string $uri)
3311 $ssl_uri = str_replace('http://', 'https://', $uri);
3312 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3314 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3315 if (DBA::isResult($item)) {
3316 return $item['uri'];
3319 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3320 if (DBA::isResult($item)) {
3321 return $item['uri'];
3328 * Fetches item for given URI or plink
3330 * @param string $uri
3331 * @param integer $uid
3333 * @return integer item id
3335 public static function fetchByLink(string $uri, int $uid = 0)
3337 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3338 $item_id = self::searchByLink($uri, $uid);
3339 if (!empty($item_id)) {
3340 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3350 Hook::callAll('item_by_link', $hookData);
3352 if (isset($hookData['item_id'])) {
3353 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3356 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3357 $item_id = self::searchByLink($fetched_uri, $uid);
3359 $item_id = Diaspora::fetchByURL($uri);
3362 if (!empty($item_id)) {
3363 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3367 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3372 * Return share data from an item array (if the item is shared item)
3373 * We are providing the complete Item array, because at some time in the future
3374 * we hopefully will define these values not in the body anymore but in some item fields.
3375 * This function is meant to replace all similar functions in the system.
3377 * @param array $item
3379 * @return array with share information
3381 public static function getShareArray($item)
3383 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3387 $attribute_string = $matches[2];
3388 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3389 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3390 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3391 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3398 * Fetch item information for shared items from the original items and adds it.
3400 * @param array $item
3402 * @return array item array with data from the original item
3404 public static function addShareDataFromOriginal(array $item)
3406 $shared = self::getShareArray($item);
3407 if (empty($shared)) {
3411 // Real reshares always have got a GUID.
3412 if (empty($shared['guid'])) {
3416 $uid = $item['uid'] ?? 0;
3418 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3419 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3420 if (!DBA::isResult($shared_item)) {
3421 if (empty($shared['link'])) {
3425 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3426 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3428 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3432 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3433 if (!DBA::isResult($shared_item)) {
3436 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3438 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3441 if (!empty($shared_item['title'])) {
3442 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3443 unset($shared_item['title']);
3445 $body = $shared_item['body'];
3448 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3449 unset($shared_item['body']);
3451 return array_merge($item, $shared_item);
3455 * Check a prospective item array against user-level permissions
3457 * @param array $item Expected keys: uri, gravity, and
3458 * author-link if is author-id is set,
3459 * owner-link if is owner-id is set,
3460 * causer-link if is causer-id is set.
3461 * @param int $user_id Local user ID
3463 * @throws \Exception
3465 protected static function isAllowedByUser(array $item, int $user_id)
3467 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3468 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3472 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3473 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3477 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3478 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3479 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3483 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3484 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3492 * Improve the data in shared posts
3494 * @param array $item
3495 * @return string body
3497 public static function improveSharedDataInBody(array $item)
3499 $shared = BBCode::fetchShareAttributes($item['body']);
3500 if (empty($shared['link'])) {
3501 return $item['body'];
3504 $id = self::fetchByLink($shared['link']);
3505 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3507 return $item['body'];
3510 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3511 if (!DBA::isResult($shared_item)) {
3512 return $item['body'];
3515 $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']);
3517 if (!empty($shared_item['title'])) {
3518 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3521 $shared_content .= $shared_item['body'];
3523 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3524 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3525 return $item['body'];