3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Post;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Map;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Worker\Delivery;
47 use GuzzleHttp\Psr7\Uri;
48 use LanguageDetection\Language;
52 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
59 const PT_DOCUMENT = 19;
62 const PT_PERSONAL_NOTE = 128;
64 // Posting reasons (Why had a post been stored for a user?)
71 const PR_FOLLOWER = 69;
72 const PR_ANNOUNCEMENT = 70;
73 const PR_COMMENT = 71;
77 const PR_FETCHED = 75;
78 const PR_COMPLETION = 76;
80 const PR_ACTIVITY = 78;
81 const PR_DISTRIBUTE = 79;
83 // system.accept_only_sharer setting values
84 const COMPLETION_NONE = 1;
85 const COMPLETION_COMMENT = 0;
86 const COMPLETION_LIKE = 2;
88 // Field list that is used to display the items
89 const DISPLAY_FIELDLIST = [
90 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
91 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
92 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
93 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
94 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
95 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
96 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
97 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
98 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
99 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
100 'writable', 'self', 'cid', 'alias',
101 'event-created', 'event-edited', 'event-start', 'event-finish',
102 'event-summary', 'event-desc', 'event-location', 'event-type',
103 'event-nofinish', 'event-ignore', 'event-id',
104 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
105 'has-categories', 'has-media',
106 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
109 // Field list that is used to deliver items via the protocols
110 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
111 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
112 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
113 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
114 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
115 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
116 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
117 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
118 'event-created', 'event-edited', 'event-start', 'event-finish',
119 'event-summary', 'event-desc', 'event-location', 'event-type',
120 'event-nofinish', 'event-ignore', 'event-id'];
122 // All fields in the item table
123 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
124 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
125 'contact-id', 'wall', 'gravity', 'extid', 'psid',
126 'created', 'edited', 'commented', 'received', 'changed', 'verb',
127 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
128 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
129 'private', 'pubmail', 'visible', 'starred',
130 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
131 'title', 'content-warning', 'body', 'location', 'coord', 'app',
132 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
133 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
134 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
136 // List of all verbs that don't need additional content data.
137 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
139 Activity::LIKE, Activity::DISLIKE,
140 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
149 * Update existing item entries
151 * @param array $fields The fields that are to be changed
152 * @param array $condition The condition for finding the item entries
154 * In the future we may have to change permissions as well.
155 * Then we had to add the user id as third parameter.
157 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
159 * @return integer|boolean number of affected rows - or "false" if there was an error
160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
162 public static function update(array $fields, array $condition)
164 if (empty($condition) || empty($fields)) {
168 if (isset($fields['extid'])) {
169 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
172 if (!empty($fields['verb'])) {
173 $fields['vid'] = Verb::getID($fields['verb']);
176 if (!empty($fields['edited'])) {
177 $previous = Post::selectFirst(['edited'], $condition);
180 $rows = Post::update($fields, $condition);
181 if (is_bool($rows)) {
185 // We only need to call the line by line update for specific fields
186 if (empty($fields['body']) && empty($fields['file']) &&
187 empty($fields['attach']) && empty($fields['edited'])) {
191 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
193 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
197 while ($item = DBA::fetch($items)) {
198 if (!empty($fields['body'])) {
199 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
201 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
203 // Remove all media attachments from the body and store them in the post-media table
204 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
205 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
206 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
208 if ($item['author-network'] != Protocol::DFRN) {
209 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
212 Post\Content::update($item['uri-id'], $content_fields);
215 if (!empty($fields['file'])) {
216 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
219 if (!empty($fields['attach'])) {
220 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
223 // We only need to notfiy others when it is an original entry from us.
224 // Only call the notifier when the item had been edited and records had been changed.
225 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
226 $notify_items[] = $item['id'];
232 foreach ($notify_items as $notify_item) {
233 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
234 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
241 * Delete an item and notify others about it - if it was ours
243 * @param array $condition The condition for finding the item entries
244 * @param integer $priority Priority for the notification
246 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
248 public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
250 $items = Post::select(['id'], $condition);
251 while ($item = Post::fetch($items)) {
252 self::markForDeletionById($item['id'], $priority);
258 * Delete an item for an user and notify others about it - if it was ours
260 * @param array $condition The condition for finding the item entries
261 * @param integer $uid User who wants to delete this item
263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
265 public static function deleteForUser(array $condition, int $uid)
271 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
272 while ($item = Post::fetch($items)) {
273 if (in_array($item['uid'], [$uid, 0])) {
274 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
275 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
278 if ($item['uid'] == $uid) {
279 self::markForDeletionById($item['id'], PRIORITY_HIGH);
280 } elseif ($item['uid'] != 0) {
281 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
288 * Mark an item for deletion, delete related data and notify others about it - if it was ours
290 * @param integer $item_id
291 * @param integer $priority Priority for the notification
292 * @return boolean success
293 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
297 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
298 // locate item to be deleted
299 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
300 'deleted', 'resource-id', 'event-id',
301 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
302 $item = Post::selectFirst($fields, ['id' => $item_id]);
303 if (!DBA::isResult($item)) {
304 Logger::info('Item not found.', ['id' => $item_id]);
308 if ($item['deleted']) {
309 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
313 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
314 if (!DBA::isResult($parent)) {
315 $parent = ['origin' => false];
318 // clean up categories and tags so they don't end up as orphans
319 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
322 * If item is a link to a photo resource, nuke all the associated photos
323 * (visitors will not have photo resources)
324 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
325 * generate a resource-id and therefore aren't intimately linked to the item.
327 /// @TODO: this should first check if photo is used elsewhere
328 if (strlen($item['resource-id'])) {
329 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
332 // If item is a link to an event, delete the event.
333 if (intval($item['event-id'])) {
334 Event::delete($item['event-id']);
337 // If item has attachments, drop them
338 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
339 foreach($attachments as $attachment) {
340 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
341 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
345 // Set the item to "deleted"
346 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
347 Post::update($item_fields, ['id' => $item['id']]);
349 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
351 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
352 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
355 Post\DeliveryData::delete($item['uri-id']);
357 // If it's the parent of a comment thread, kill all the kids
358 if ($item['gravity'] == GRAVITY_PARENT) {
359 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
362 // Is it our comment and/or our thread?
363 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
364 // When we delete the original post we will delete all existing copies on the server as well
365 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
367 // send the notification upstream/downstream
369 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
371 } elseif ($item['uid'] != 0) {
372 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
373 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
376 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
382 * Get guid from given item record
384 * @param array $item Item record
385 * @param bool Whether to notify (?)
386 * @return string Guid
388 public static function guid(array $item, bool $notify): string
390 if (!empty($item['guid'])) {
391 return trim($item['guid']);
395 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
396 // We add the hash of our own host because our host is the original creator of the post.
397 $prefix_host = DI::baseUrl()->getHostname();
401 // We are only storing the post so we create a GUID from the original hostname.
402 if (!empty($item['author-link'])) {
403 $parsed = parse_url($item['author-link']);
404 if (!empty($parsed['host'])) {
405 $prefix_host = $parsed['host'];
409 if (empty($prefix_host) && !empty($item['plink'])) {
410 $parsed = parse_url($item['plink']);
411 if (!empty($parsed['host'])) {
412 $prefix_host = $parsed['host'];
416 if (empty($prefix_host) && !empty($item['uri'])) {
417 $parsed = parse_url($item['uri']);
418 if (!empty($parsed['host'])) {
419 $prefix_host = $parsed['host'];
423 // Is it in the format data@host.tld? - Used for mail contacts
424 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
425 $mailparts = explode('@', $item['author-link']);
426 $prefix_host = array_pop($mailparts);
430 if (!empty($item['plink'])) {
431 $guid = self::guidFromUri($item['plink'], $prefix_host);
432 } elseif (!empty($item['uri'])) {
433 $guid = self::guidFromUri($item['uri'], $prefix_host);
435 $guid = System::createUUID(hash('crc32', $prefix_host));
442 * Returns contact id from given item record
444 * @param array $item Item record
445 * @return int Contact id
447 private static function contactId(array $item): int
449 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
450 return $item['contact-id'];
451 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
452 return $item['contact-id'];
453 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
454 return $item['author-id'];
455 } elseif (!empty($item['contact-id'])) {
456 return $item['contact-id'];
458 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
459 if (!empty($contact_id)) {
463 return $item['author-id'];
467 * Write an item array into a spool file to be inserted later.
468 * This command is called whenever there are issues storing an item.
470 * @param array $item The item fields that are to be inserted
473 private static function spool(array $item)
475 // Now we store the data in the spool directory
476 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
477 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
479 $spoolpath = System::getSpoolPath();
480 if ($spoolpath != '') {
481 $spool = $spoolpath . '/' . $file;
483 file_put_contents($spool, json_encode($item));
484 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
489 * Check if the item array is a duplicate
491 * @param array $item Item record
492 * @return boolean is it a duplicate?
494 private static function isDuplicate(array $item): bool
496 // Checking if there is already an item with the same guid
497 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
498 if (Post::exists($condition)) {
499 Logger::notice('Found already existing item', $condition);
503 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
504 'network' => [$item['network'], Protocol::DFRN]];
505 if (Post::exists($condition)) {
506 Logger::notice('duplicated item with the same uri found.', $condition);
510 // On Friendica and Diaspora the GUID is unique
511 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
512 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
513 if (Post::exists($condition)) {
514 Logger::notice('duplicated item with the same guid found.', $condition);
517 } elseif ($item['network'] == Protocol::OSTATUS) {
518 // Check for an existing post with the same content. There seems to be a problem with OStatus.
519 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
520 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
521 if (Post::exists($condition)) {
522 Logger::notice('duplicated item with the same body found.', $item);
528 * Check for already added items.
529 * There is a timing issue here that sometimes creates double postings.
530 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
532 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
533 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
541 * Check if the item array is valid
543 * @param array $item Item record
544 * @return boolean item is valid
546 public static function isValid(array $item): bool
548 // When there is no content then we don't post it
549 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
550 Logger::notice('No body, no title.');
554 if (!empty($item['uid'])) {
555 $owner = User::getOwnerDataById($item['uid'], false);
557 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
561 if ($owner['account_expired'] || $owner['account_removed']) {
562 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']]);
567 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
568 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
572 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
573 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
577 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
578 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
582 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
583 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
587 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
591 if ($item['verb'] == Activity::FOLLOW) {
592 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
593 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
594 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
598 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
599 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
600 if (Post::exists($condition)) {
601 // It happens that we receive multiple follow requests by the same author - we only store one.
602 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
611 * Check if the item array is too old
613 * @param array $item Item record
614 * @return boolean item is too old
616 public static function isTooOld(array $item): bool
618 // check for create date and expire time
619 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
621 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
622 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
623 $expire_interval = $user['expire'];
626 if (($expire_interval > 0) && !empty($item['created'])) {
627 $expire_date = time() - ($expire_interval * 86400);
628 $created_date = strtotime($item['created']);
629 if ($created_date < $expire_date) {
630 Logger::notice('Item created before expiration interval.', [
631 'created' => date('c', $created_date),
632 'expired' => date('c', $expire_date),
643 * Return the id of the given item array if it has been stored before
645 * @param array $item Item record
646 * @return integer Item id or zero on error
648 private static function getDuplicateID(array $item): int
650 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
651 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
654 Protocol::ACTIVITYPUB,
659 $existing = Post::selectFirst(['id', 'network'], $condition);
660 if (DBA::isResult($existing)) {
661 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
662 if ($item['uid'] != 0) {
663 Logger::notice('Item already existed for user', [
664 'uri-id' => $item['uri-id'],
665 'uid' => $item['uid'],
666 'network' => $item['network'],
667 'existing_id' => $existing['id'],
668 'existing_network' => $existing['network']
672 return $existing['id'];
679 * Fetch top-level parent data for the given item array
682 * @return array item array with parent data
685 private static function getTopLevelParent(array $item): array
687 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
688 'uri-id', 'parent-uri-id',
689 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
690 'wall', 'private', 'origin', 'author-id'];
691 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
692 $params = ['order' => ['id' => false]];
693 $parent = Post::selectFirst($fields, $condition, $params);
695 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
696 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
697 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
698 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
701 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
702 $parent = Post::selectFirst($fields, $condition, $params);
706 if (!DBA::isResult($parent)) {
707 Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
711 if ($parent['uri-id'] == $parent['parent-uri-id']) {
715 $condition = ['uri-id' => $parent['parent-uri-id'],
716 'parent-uri-id' => $parent['parent-uri-id'],
717 'uid' => $parent['uid']];
718 $params = ['order' => ['id' => false]];
719 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
721 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
722 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
723 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
724 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
727 if (!DBA::isResult($toplevel_parent)) {
728 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
732 return $toplevel_parent;
736 * Get the gravity for the given item array
739 * @return integer gravity
741 private static function getGravity(array $item): int
743 $activity = DI::activity();
745 if (isset($item['gravity'])) {
746 return intval($item['gravity']);
747 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
748 return GRAVITY_PARENT;
749 } elseif ($activity->match($item['verb'], Activity::POST)) {
750 return GRAVITY_COMMENT;
751 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
752 return GRAVITY_ACTIVITY;
753 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
754 return GRAVITY_ACTIVITY;
757 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
758 return GRAVITY_UNKNOWN; // Should not happen
762 * Inserts item record
764 * @param array $item Item array to be inserted
765 * @param int $notify Notification (type?)
766 * @param bool $post_local (???)
767 * @return int Zero means error, otherwise primary key (id) is being returned
769 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
773 $priority = PRIORITY_HIGH;
775 // If it is a posting where users should get notifications, then define it as wall posting
779 $item['network'] = Protocol::DFRN;
780 $item['protocol'] = Conversation::PARCEL_DIRECT;
781 $item['direction'] = Conversation::PUSH;
783 if (is_int($notify) && in_array($notify, PRIORITIES)) {
787 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
790 $uid = intval($item['uid']);
792 $item['guid'] = self::guid($item, $notify);
793 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
796 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
798 // Backward compatibility: parent-uri used to be the direct parent uri.
799 // If it is provided without a thr-parent, it probably is the old behavior.
800 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
801 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
802 $item['parent-uri'] = $item['thr-parent'];
805 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
806 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
808 // Store conversation data
809 $source = $item['source'] ?? '';
810 unset($item['conversation-uri']);
811 unset($item['conversation-href']);
812 unset($item['source']);
815 * Do we already have this item?
816 * We have to check several networks since Friendica posts could be repeated
817 * via OStatus (maybe Diasporsa as well)
819 $duplicate = self::getDuplicateID($item);
824 // Additional duplicate checks
825 /// @todo Check why the first duplication check returns the item number and the second a 0
826 if (self::isDuplicate($item)) {
830 if (!isset($item['post-type'])) {
831 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
834 $item['wall'] = intval($item['wall'] ?? 0);
835 $item['extid'] = trim($item['extid'] ?? '');
836 $item['author-name'] = trim($item['author-name'] ?? '');
837 $item['author-link'] = trim($item['author-link'] ?? '');
838 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
839 $item['owner-name'] = trim($item['owner-name'] ?? '');
840 $item['owner-link'] = trim($item['owner-link'] ?? '');
841 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
842 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
843 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
844 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
845 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
846 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
847 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
848 $item['location'] = trim($item['location'] ?? '');
849 $item['coord'] = trim($item['coord'] ?? '');
850 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
851 $item['deleted'] = 0;
852 $item['verb'] = trim($item['verb'] ?? '');
853 $item['object-type'] = trim($item['object-type'] ?? '');
854 $item['object'] = trim($item['object'] ?? '');
855 $item['target-type'] = trim($item['target-type'] ?? '');
856 $item['target'] = trim($item['target'] ?? '');
857 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
858 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
859 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
860 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
861 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
862 $item['private'] = intval($item['private'] ?? self::PUBLIC);
863 $item['body'] = trim($item['body'] ?? '');
864 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
865 $item['app'] = trim($item['app'] ?? '');
866 $item['origin'] = intval($item['origin'] ?? 0);
867 $item['postopts'] = trim($item['postopts'] ?? '');
868 $item['resource-id'] = trim($item['resource-id'] ?? '');
869 $item['event-id'] = intval($item['event-id'] ?? 0);
870 $item['inform'] = trim($item['inform'] ?? '');
871 $item['file'] = trim($item['file'] ?? '');
873 // Communities aren't working with the Diaspora protoccol
874 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
875 $user = User::getById($uid, ['account-type']);
876 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
877 Logger::info('Community posts are not supported via Diaspora');
882 // Items cannot be stored before they happen ...
883 if ($item['created'] > DateTimeFormat::utcNow()) {
884 $item['created'] = DateTimeFormat::utcNow();
887 // We haven't invented time travel by now.
888 if ($item['edited'] > DateTimeFormat::utcNow()) {
889 $item['edited'] = DateTimeFormat::utcNow();
892 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
894 $item['gravity'] = self::getGravity($item);
896 $item['language'] = self::getLanguage($item);
898 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
899 'photo' => $item['author-avatar'], 'network' => $item['network']];
900 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
902 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
903 'photo' => $item['owner-avatar'], 'network' => $item['network']];
904 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
906 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
907 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
908 $item['post-reason'] = self::PR_FOLLOWER;
911 // Ensure that there is an avatar cache
912 Contact::checkAvatarCache($item['author-id']);
913 Contact::checkAvatarCache($item['owner-id']);
915 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
916 $item['contact-id'] = self::contactId($item);
918 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
919 empty($item['origin']) && self::isTooOld($item)) {
920 Logger::info('Item is too old', ['item' => $item]);
924 if (!self::isValid($item)) {
928 if ($item['gravity'] !== GRAVITY_PARENT) {
929 $toplevel_parent = self::getTopLevelParent($item);
930 if (empty($toplevel_parent)) {
934 // If the thread originated from this node, we check the permission against the thread starter
935 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
936 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
937 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
941 $parent_id = $toplevel_parent['id'];
942 $item['parent-uri'] = $toplevel_parent['uri'];
943 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
944 $item['deleted'] = $toplevel_parent['deleted'];
946 // Reshares have to keep their permissions to allow forums to work
947 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
948 $item['allow_cid'] = $toplevel_parent['allow_cid'];
949 $item['allow_gid'] = $toplevel_parent['allow_gid'];
950 $item['deny_cid'] = $toplevel_parent['deny_cid'];
951 $item['deny_gid'] = $toplevel_parent['deny_gid'];
954 $parent_origin = $toplevel_parent['origin'];
956 // Don't federate received participation messages
957 if ($item['verb'] != Activity::FOLLOW) {
958 $item['wall'] = $toplevel_parent['wall'];
960 $item['wall'] = false;
961 // Participations are technical messages, so they are set to "seen" automatically
962 $item['unseen'] = false;
966 * If the parent is private, force privacy for the entire conversation
967 * This differs from the above settings as it subtly allows comments from
968 * email correspondents to be private even if the overall thread is not.
970 if ($toplevel_parent['private']) {
971 $item['private'] = $toplevel_parent['private'];
974 // If its a post that originated here then tag the thread as "mention"
975 if ($item['origin'] && $item['uid']) {
976 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
977 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
980 // Update the contact relations
981 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
984 $parent_origin = $item['origin'];
986 if ($item['wall'] && empty($item['conversation'])) {
987 $item['conversation'] = $item['parent-uri'] . '#context';
991 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
992 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
994 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
995 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
998 // Is this item available in the global items (with uid=0)?
999 if ($item['uid'] == 0) {
1000 $item['global'] = true;
1002 // Set the global flag on all items if this was a global item entry
1003 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1005 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1009 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1010 $item['private'] = self::PRIVATE;
1013 if ($notify && $post_local) {
1014 $item['edit'] = false;
1015 $item['parent'] = $parent_id;
1017 // Trigger automatic reactions for addons
1018 if (!isset($item['api_source'])) {
1019 $item['api_source'] = true;
1022 // We have to tell the hooks who we are - this really should be improved
1023 if (!local_user()) {
1024 $_SESSION['authenticated'] = true;
1025 $_SESSION['uid'] = $uid;
1026 $dummy_session = true;
1028 $dummy_session = false;
1031 Hook::callAll('post_local', $item);
1033 if ($dummy_session) {
1034 unset($_SESSION['authenticated']);
1035 unset($_SESSION['uid']);
1037 } elseif (!$notify) {
1038 Hook::callAll('post_remote', $item);
1041 if (!empty($item['cancel'])) {
1042 Logger::notice('post cancelled by addon.');
1046 if (empty($item['vid']) && !empty($item['verb'])) {
1047 $item['vid'] = Verb::getID($item['verb']);
1050 // Creates or assigns the permission set
1051 $item['psid'] = DI::permissionSet()->selectOrCreate(
1052 DI::permissionSetFactory()->createFromString(
1060 if (!empty($item['extid'])) {
1061 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1064 if ($item['verb'] == Activity::ANNOUNCE) {
1065 self::setOwnerforResharedItem($item);
1068 if (isset($item['attachments'])) {
1069 foreach ($item['attachments'] as $attachment) {
1070 $attachment['uri-id'] = $item['uri-id'];
1071 Post\Media::insert($attachment);
1073 unset($item['attachments']);
1076 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1078 // Remove all media attachments from the body and store them in the post-media table
1079 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1080 $item['raw-body'] = self::setHashtags($item['raw-body']);
1082 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1083 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1086 // Check for hashtags in the body and repair or add hashtag links
1087 $item['body'] = self::setHashtags($item['body']);
1089 if (stristr($item['verb'], Activity::POKE)) {
1090 $notify_type = Delivery::POKE;
1092 $notify_type = Delivery::POST;
1095 // Filling item related side tables
1096 if (!empty($item['attach'])) {
1097 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1100 if (empty($item['event-id'])) {
1101 unset($item['event-id']);
1103 $ev = Event::fromBBCode($item['body']);
1104 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1105 Logger::info('Event found.');
1106 $ev['cid'] = $item['contact-id'];
1107 $ev['uid'] = $item['uid'];
1108 $ev['uri'] = $item['uri'];
1109 $ev['edited'] = $item['edited'];
1110 $ev['private'] = $item['private'];
1111 $ev['guid'] = $item['guid'];
1112 $ev['plink'] = $item['plink'];
1113 $ev['network'] = $item['network'];
1114 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1115 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1116 $ev['source'] = $item['source'] ?? '';
1118 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1119 if (DBA::isResult($event)) {
1120 $ev['id'] = $event['id'];
1123 $event_id = Event::store($ev);
1124 $item = Event::getItemArrayForImportedId($event_id, $item);
1126 Logger::info('Event was stored', ['id' => $event_id]);
1130 if (empty($item['causer-id'])) {
1131 unset($item['causer-id']);
1134 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1135 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1136 if (!empty($content_warning) && empty($item['content-warning'])) {
1137 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1141 Post::insert($item['uri-id'], $item);
1143 if ($item['gravity'] == GRAVITY_PARENT) {
1144 Post\Thread::insert($item['uri-id'], $item);
1147 if (!in_array($item['verb'], self::ACTIVITIES)) {
1148 Post\Content::insert($item['uri-id'], $item);
1151 // Create Diaspora signature
1152 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1153 $signed = Diaspora::createCommentSignature($item);
1154 if (!empty($signed)) {
1155 $item['diaspora_signed_text'] = json_encode($signed);
1159 if (!empty($item['diaspora_signed_text'])) {
1160 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1163 // Attached file links
1164 if (!empty($item['file'])) {
1165 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1168 // Delivery relevant data
1169 $delivery_data = Post\DeliveryData::extractFields($item);
1171 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1172 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1175 // Store tags from the body if this hadn't been handled previously in the protocol classes
1176 if (!Tag::existsForPost($item['uri-id'])) {
1177 Tag::storeFromBody($item['uri-id'], $item['body']);
1180 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1181 if (Post::exists($condition)) {
1182 Logger::notice('Item is already inserted - aborting', $condition);
1186 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1187 if (!$post_user_id) {
1188 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1192 if ($item['gravity'] == GRAVITY_PARENT) {
1193 $item['post-user-id'] = $post_user_id;
1194 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1197 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1199 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1200 if (!DBA::isResult($posted_item)) {
1201 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1202 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1203 self::spool($orig_item);
1207 // update the commented timestamp on the parent
1208 if (DI::config()->get('system', 'like_no_comment')) {
1209 // Update when it is a comment
1210 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1212 // Update when it isn't a follow or tag verb
1213 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1216 if ($update_commented) {
1217 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1219 $fields = ['changed' => DateTimeFormat::utcNow()];
1222 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1224 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1225 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1226 // Get the user information for the logging
1227 $user = User::getById($uid);
1229 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1234 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1235 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1237 Hook::callAll('post_local_end', $posted_item);
1239 Hook::callAll('post_remote_end', $posted_item);
1242 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1243 self::addShadow($post_user_id);
1245 self::addShadowPost($post_user_id);
1248 self::updateContact($posted_item);
1250 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1252 // Distribute items to users who subscribed to their tags
1253 self::distributeByTags($posted_item);
1255 // Automatically reshare the item if the "remote_self" option is selected
1256 self::autoReshare($posted_item);
1258 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1261 // Don't relay participation messages
1262 if (($posted_item['verb'] == Activity::FOLLOW) &&
1263 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1264 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1270 if (!empty($source)) {
1271 Post\Activity::insert($item['uri-id'], $source);
1273 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1276 // Fill the cache with the rendered content.
1277 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1278 self::updateDisplayCache($posted_item['uri-id']);
1281 if ($posted_item['origin'] && ($posted_item['uid'] != 0) && in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
1282 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_OUTBOX . $posted_item['uid']);
1285 return $post_user_id;
1289 * Update the display cache
1291 * @param integer $uri_id
1294 public static function updateDisplayCache(int $uri_id)
1296 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1297 self::prepareBody($item, false, false, true);
1301 * Change the owner of a parent item if it had been shared by a forum
1303 * (public) forum posts in the new format consist of the regular post by the author
1304 * followed by an announce message sent from the forum account.
1305 * Changing the owner helps in grouping forum posts.
1307 * @param array $item
1310 private static function setOwnerforResharedItem(array $item)
1312 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1313 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1314 if (!DBA::isResult($parent)) {
1315 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1319 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1320 if (!DBA::isResult($author)) {
1321 Logger::error('Author not found', ['id' => $item['author-id']]);
1325 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1326 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1328 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1329 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1330 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1334 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1335 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1336 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']]);
1340 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1341 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1346 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1347 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1351 * Distribute the given item to users who subscribed to their tags
1353 * @param array $item Processed item
1355 private static function distributeByTags(array $item)
1357 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1361 $uids = Tag::getUIDListByURIId($item['uri-id']);
1362 foreach ($uids as $uid) {
1363 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1364 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1369 * Distributes public items to the receivers
1371 * @param integer $itemid Item ID that should be added
1372 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1373 * @throws \Exception
1375 public static function distribute(int $itemid, string $signed_text = '')
1377 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1378 $parent = Post::selectFirst(['owner-id'], $condition);
1379 if (!DBA::isResult($parent)) {
1380 Logger::warning('Item not found', ['condition' => $condition]);
1384 // Only distribute public items from native networks
1385 $condition = ['id' => $itemid, 'uid' => 0,
1386 'network' => array_merge(Protocol::FEDERATED ,['']),
1387 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1388 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
1389 if (!DBA::isResult($item)) {
1390 Logger::warning('Item not found', ['condition' => $condition]);
1394 $origin = $item['origin'];
1398 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1399 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1400 if (!DBA::isResult($owner)) {
1404 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1405 $contacts = DBA::select('contact', ['uid'], $condition);
1406 while ($contact = DBA::fetch($contacts)) {
1407 if ($contact['uid'] == 0) {
1411 $users[$contact['uid']] = $contact['uid'];
1413 DBA::close($contacts);
1415 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1416 $contacts = DBA::select('contact', ['uid'], $condition);
1417 while ($contact = DBA::fetch($contacts)) {
1418 if ($contact['uid'] == 0) {
1422 $users[$contact['uid']] = $contact['uid'];
1424 DBA::close($contacts);
1426 if (!empty($owner['alias'])) {
1427 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1428 $contacts = DBA::select('contact', ['uid'], $condition);
1429 while ($contact = DBA::fetch($contacts)) {
1430 if ($contact['uid'] == 0) {
1434 $users[$contact['uid']] = $contact['uid'];
1436 DBA::close($contacts);
1441 if ($item['uri-id'] != $item['parent-uri-id']) {
1442 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1443 while ($parent = Post::fetch($parents)) {
1444 $users[$parent['uid']] = $parent['uid'];
1445 if ($parent['origin'] && !$origin) {
1446 $origin_uid = $parent['uid'];
1449 DBA::close($parents);
1452 foreach ($users as $uid) {
1453 if ($origin_uid == $uid) {
1454 $item['diaspora_signed_text'] = $signed_text;
1456 $item['post-reason'] = self::PR_DISTRIBUTE;
1457 self::storeForUser($item, $uid);
1462 * Store a public item defined by their URI-ID for the given users
1464 * @param integer $uri_id URI-ID of the given item
1465 * @param integer $uid The user that will receive the item entry
1466 * @param array $fields Additional fields to be stored
1467 * @param integer $source_uid User id of the source post
1468 * @return integer stored item id
1470 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1472 if ($uid == $source_uid) {
1473 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1477 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => $source_uid]);
1478 if (!DBA::isResult($item)) {
1479 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1483 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1484 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']]);
1488 $item['post-reason'] = self::PR_STORED;
1490 $item = array_merge($item, $fields);
1492 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1494 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1495 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1496 !Contact::isSharingByURL($item['author-link'], $uid) &&
1497 !Contact::isSharingByURL($item['owner-link'], $uid)) {
1498 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1502 if (($uri_id != $item['thr-parent-id']) && (($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1503 // Fetch the origin user for the post
1504 $origin_uid = self::GetOriginUidForUriId($item['thr-parent-id'], $uid);
1505 if (is_null($origin_uid)) {
1506 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $item['thr-parent-id']]);
1510 $causer = $item['causer-id'] ?: $item['author-id'];
1511 $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1512 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1515 $stored = self::storeForUser($item, $uid);
1516 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1521 * Returns the origin uid of a post if the given user is allowed to see it.
1527 private static function GetOriginUidForUriId(int $uriid, int $uid)
1529 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1533 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1534 if (!empty($post)) {
1535 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1536 return $post['uid'];
1539 $pcid = Contact::getPublicIdByUserId($uid);
1544 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1545 if ($receiver == $pcid) {
1546 return $post['uid'];
1553 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1557 // When the post belongs to a a forum then all forum users are allowed to access it
1558 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1559 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1560 $target_uid = User::getIdForURL($tag['url']);
1561 if (!empty($target_uid)) {
1571 * Store a public item array for the given users
1573 * @param array $item The item entry that will be stored
1574 * @param integer $uid The user that will receive the item entry
1575 * @return integer stored item id
1576 * @throws \Exception
1578 private static function storeForUser(array $item, int $uid): int
1580 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1581 if (!empty($item['event-id'])) {
1582 $post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1583 if (!empty($post['event-id'])) {
1584 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1585 if (!empty($event)) {
1586 // We aren't using "Event::store" here, since we don't want to trigger any further action
1587 $ret = DBA::update('event', $event, ['id' => $post['event-id']]);
1588 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $post['event-id'], 'ret' => $ret]);
1592 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1596 // Data from the "post-user" table
1598 unset($item['mention']);
1599 unset($item['starred']);
1600 unset($item['unseen']);
1601 unset($item['psid']);
1602 unset($item['pinned']);
1603 unset($item['ignored']);
1604 unset($item['pubmail']);
1605 unset($item['event-id']);
1606 unset($item['hidden']);
1607 unset($item['notification-type']);
1609 // Data from the "post-delivery-data" table
1610 unset($item['postopts']);
1611 unset($item['inform']);
1613 $item['uid'] = $uid;
1614 $item['origin'] = 0;
1617 if ($item['gravity'] == GRAVITY_PARENT) {
1618 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1620 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1623 if (!empty($contact['id'])) {
1624 $item['contact-id'] = $contact['id'];
1626 // Shouldn't happen at all
1627 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1628 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1629 if (!DBA::isResult($self)) {
1630 // Shouldn't happen even less
1631 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1634 $item['contact-id'] = $self['id'];
1638 if ($item['gravity'] == GRAVITY_PARENT) {
1639 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1640 if (DBA::isResult($contact)) {
1641 $notify = self::isRemoteSelf($contact, $item);
1645 $distributed = self::insert($item, $notify);
1647 if (!$distributed) {
1648 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1650 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1652 return $distributed;
1656 * Add a shadow entry for a given item id that is a thread starter
1658 * We store every public item entry additionally with the user id "0".
1659 * This is used for the community page and for the search.
1660 * It is planned that in the future we will store public item entries only once.
1662 * @param integer $itemid Item ID that should be added
1663 * @throws \Exception
1665 private static function addShadow(int $itemid)
1667 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1668 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1669 $item = Post::selectFirst($fields, $condition);
1671 if (!DBA::isResult($item)) {
1675 // is it already a copy?
1676 if (($itemid == 0) || ($item['uid'] == 0)) {
1680 // Is it a visible public post?
1681 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1685 // is it an entry from a connector? Only add an entry for natively connected networks
1686 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1690 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1694 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1696 if (DBA::isResult($item)) {
1697 // Preparing public shadow (removing user specific data)
1700 unset($item['parent']);
1701 unset($item['wall']);
1702 unset($item['mention']);
1703 unset($item['origin']);
1704 unset($item['starred']);
1705 unset($item['postopts']);
1706 unset($item['inform']);
1707 unset($item['post-reason']);
1708 if ($item['uri-id'] == $item['parent-uri-id']) {
1709 $item['contact-id'] = $item['owner-id'];
1711 $item['contact-id'] = $item['author-id'];
1714 $public_shadow = self::insert($item);
1716 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1721 * Add a shadow entry for a given item id that is a comment
1723 * This function does the same like the function above - but for comments
1725 * @param integer $itemid Item ID that should be added
1726 * @throws \Exception
1728 private static function addShadowPost(int $itemid)
1730 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1731 if (!DBA::isResult($item)) {
1735 // Is it a toplevel post?
1736 if ($item['gravity'] == GRAVITY_PARENT) {
1737 self::addShadow($itemid);
1741 // Is this a shadow entry?
1742 if ($item['uid'] == 0) {
1746 // Is there a shadow parent?
1747 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1751 // Is there already a shadow entry?
1752 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1756 // Save "origin" and "parent" state
1757 $origin = $item['origin'];
1758 $parent = $item['parent'];
1760 // Preparing public shadow (removing user specific data)
1763 unset($item['parent']);
1764 unset($item['wall']);
1765 unset($item['mention']);
1766 unset($item['origin']);
1767 unset($item['starred']);
1768 unset($item['postopts']);
1769 unset($item['inform']);
1770 unset($item['post-reason']);
1771 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1773 $public_shadow = self::insert($item);
1775 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1777 // If this was a comment to a Diaspora post we don't get our comment back.
1778 // This means that we have to distribute the comment by ourselves.
1779 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1780 self::distribute($public_shadow);
1785 * Adds a language specification in a "language" element of given $arr.
1786 * Expects "body" element to exist in $arr.
1788 * @param array $item
1789 * @return string detected language
1790 * @throws \Text_LanguageDetect_Exception
1792 private static function getLanguage(array $item): string
1794 if (!empty($item['language'])) {
1795 return $item['language'];
1798 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1802 // Convert attachments to links
1803 $naked_body = BBCode::removeAttachment($item['body']);
1804 if (empty($naked_body)) {
1808 // Remove links and pictures
1809 $naked_body = BBCode::removeLinks($naked_body);
1811 // Convert the title and the body to plain text
1812 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1814 // Remove possibly remaining links
1815 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1817 if (empty($naked_body)) {
1821 $availableLanguages = DI::l10n()->getAvailableLanguages();
1822 // See https://github.com/friendica/friendica/issues/10511
1823 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1824 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1825 $availableLanguages['fa'] = 'fa';
1827 $ld = new Language(array_keys($availableLanguages));
1828 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1829 if (is_array($languages)) {
1830 return json_encode($languages);
1836 public static function getLanguageMessage(array $item): string
1838 $iso639 = new \Matriphe\ISO639\ISO639;
1840 $used_languages = '';
1841 foreach (json_decode($item['language'], true) as $language => $reliability) {
1842 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1844 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1845 return $used_languages;
1849 * Creates an unique guid out of a given uri.
1850 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1851 * Posts that are created on this system are using System::createUUID.
1852 * Received ActivityPub posts are using Processor::getGUIDByURL.
1854 * @param string $uri uri of an item entry
1855 * @param string|null $host hostname for the GUID prefix
1856 * @return string Unique guid
1858 public static function guidFromUri(string $uri, string $host = null): string
1860 // Our regular guid routine is using this kind of prefix as well
1861 // We have to avoid that different routines could accidentally create the same value
1862 $parsed = parse_url($uri);
1864 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1865 unset($parsed['scheme']);
1867 // Glue it together to be able to make a hash from it
1868 $host_id = implode('/', $parsed);
1870 // Use a mixture of several hashes to provide some GUID like experience
1871 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1875 * generate an unique URI
1877 * @param string $guid An existing GUID (Otherwise it will be generated)
1880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882 public static function newURI(string $guid = ''): string
1885 $guid = System::createUUID();
1888 return DI::baseUrl()->get() . '/objects/' . $guid;
1892 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1894 * This can be used to filter for inactive contacts.
1895 * Only do this for public postings to avoid privacy problems, since poco data is public.
1896 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1898 * @param array $arr Contains the just posted item record
1899 * @throws \Exception
1901 private static function updateContact(array $arr)
1903 // Unarchive the author
1904 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1905 if (DBA::isResult($contact)) {
1906 Contact::unmarkForArchival($contact);
1909 // Unarchive the contact if it's not our own contact
1910 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1911 if (DBA::isResult($contact)) {
1912 Contact::unmarkForArchival($contact);
1915 /// @todo On private posts we could obfuscate the date
1916 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1918 // Is it a forum? Then we don't care about the rules from above
1919 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1920 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1926 // The "self" contact id is used (for example in the connectors) when the contact is unknown
1927 // So we have to ensure to only update the last item when it had been our own post,
1928 // or it had been done by a "regular" contact.
1929 if (!empty($arr['wall'])) {
1930 $condition = ['id' => $arr['contact-id']];
1932 $condition = ['id' => $arr['contact-id'], 'self' => false];
1934 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1936 // Now do the same for the system wide contacts with uid=0
1937 if ($arr['private'] != self::PRIVATE) {
1938 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1939 ['id' => $arr['owner-id']]);
1941 if ($arr['owner-id'] != $arr['author-id']) {
1942 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1943 ['id' => $arr['author-id']]);
1948 public static function setHashtags(string $body): string
1950 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1951 $tags = BBCode::getTags($body);
1954 if (!count($tags)) {
1958 // This sorting is important when there are hashtags that are part of other hashtags
1959 // Otherwise there could be problems with hashtags like #test and #test2
1960 // Because of this we are sorting from the longest to the shortest tag.
1961 usort($tags, function ($a, $b) {
1962 return strlen($b) <=> strlen($a);
1965 $URLSearchString = "^\[\]";
1967 // All hashtags should point to the home server if "local_tags" is activated
1968 if (DI::config()->get('system', 'local_tags')) {
1969 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1970 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1973 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1974 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1976 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1979 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1981 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1984 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1986 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1989 // Repair recursive urls
1990 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1993 foreach ($tags as $tag) {
1994 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
1998 $basetag = str_replace('_', ' ', substr($tag, 1));
1999 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2001 $body = str_replace($tag, $newtag, $body);
2004 // Convert back the masked hashtags
2005 $body = str_replace("#", "#", $body);
2014 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2017 * @param int $item_id
2018 * @return boolean true if item was deleted, else false
2019 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2020 * @throws \ImagickException
2022 private static function tagDeliver(int $uid, int $item_id): bool
2026 $owner = User::getOwnerDataById($uid);
2027 if (!DBA::isResult($owner)) {
2028 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2032 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2033 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2037 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
2038 if (!DBA::isResult($item)) {
2039 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2043 if ($item['gravity'] == GRAVITY_PARENT) {
2044 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2045 foreach ($tags as $tag) {
2046 if (Strings::compareLink($owner['url'], $tag['url'])) {
2048 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']]);
2053 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2054 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2058 $arr = ['item' => $item, 'user' => $owner];
2060 Hook::callAll('tagged', $arr);
2062 $tags = Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2063 foreach ($tags as $tag) {
2064 if (Strings::compareLink($owner['url'], $tag['url'])) {
2066 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']]);
2071 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2076 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2078 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2080 $allow_gid = '<' . Group::FOLLOWERS . '>';
2083 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2085 self::performActivity($item['id'], 'announce', $uid);
2088 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2093 * Automatically reshare the item if the "remote_self" option is selected
2095 * @param array $item
2098 private static function autoReshare(array $item)
2100 if ($item['gravity'] != GRAVITY_PARENT) {
2104 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2108 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2112 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2114 self::performActivity($item['id'], 'announce', $item['uid']);
2117 public static function isRemoteSelf(array $contact, array &$datarray): bool
2119 if (!$contact['remote_self']) {
2123 // Prevent the forwarding of posts that are forwarded
2124 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2125 Logger::info('Already forwarded');
2129 // Prevent to forward already forwarded posts
2130 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2131 Logger::info('Already forwarded (second test)');
2135 // Only forward posts
2136 if ($datarray["verb"] != Activity::POST) {
2137 Logger::info('No post');
2141 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2142 Logger::info('Not public');
2146 $datarray2 = $datarray;
2147 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2148 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2149 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2150 ['uid' => $contact['uid'], 'self' => true]);
2151 if (DBA::isResult($self)) {
2152 $datarray['contact-id'] = $self["id"];
2154 $datarray['owner-name'] = $self["name"];
2155 $datarray['owner-link'] = $self["url"];
2156 $datarray['owner-avatar'] = $self["thumb"];
2158 $datarray['author-name'] = $datarray['owner-name'];
2159 $datarray['author-link'] = $datarray['owner-link'];
2160 $datarray['author-avatar'] = $datarray['owner-avatar'];
2162 unset($datarray['edited']);
2164 unset($datarray['network']);
2165 unset($datarray['owner-id']);
2166 unset($datarray['author-id']);
2169 if ($contact['network'] != Protocol::FEED) {
2170 $old_uri_id = $datarray["uri-id"] ?? 0;
2171 $datarray["guid"] = System::createUUID();
2172 unset($datarray["plink"]);
2173 $datarray["uri"] = self::newURI($datarray["guid"]);
2174 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2175 $datarray["extid"] = Protocol::DFRN;
2176 $urlpart = parse_url($datarray2['author-link']);
2177 $datarray["app"] = $urlpart["host"];
2178 if (!empty($old_uri_id)) {
2179 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2182 unset($datarray["parent-uri"]);
2183 unset($datarray["thr-parent"]);
2185 $datarray['private'] = self::PUBLIC;
2189 if ($contact['network'] != Protocol::FEED) {
2190 // Store the original post
2191 $result = self::insert($datarray2);
2192 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2194 $datarray["app"] = "Feed";
2198 return (bool)$result;
2205 * @param array $item
2208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2209 * @throws \ImagickException
2211 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2213 if (DI::config()->get('system', 'disable_embedded')) {
2217 Logger::info('check for photos');
2218 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2223 $img_start = strpos($orig_body, '[img');
2224 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2225 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2227 while (($img_st_close !== false) && ($img_len !== false)) {
2228 $img_st_close++; // make it point to AFTER the closing bracket
2229 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2231 Logger::info('found photo', ['image' => $image]);
2233 if (stristr($image, $site . '/photo/')) {
2234 // Only embed locally hosted photos
2236 $i = basename($image);
2237 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2238 $x = strpos($i, '-');
2241 $res = substr($i, $x + 1);
2242 $i = substr($i, 0, $x);
2243 $photo = Photo::getPhotoForUser($uid, $i, $res);
2244 if (DBA::isResult($photo)) {
2246 * Check to see if we should replace this photo link with an embedded image
2247 * 1. No need to do so if the photo is public
2248 * 2. If there's a contact-id provided, see if they're in the access list
2249 * for the photo. If so, embed it.
2250 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2251 * permissions, regardless of order but first check to see if they're an exact
2252 * match to save some processing overhead.
2254 if (self::hasPermissions($photo)) {
2256 $recips = self::enumeratePermissions($photo);
2257 if (in_array($cid, $recips)) {
2261 if (self::samePermissions($uid, $item, $photo)) {
2267 $photo_img = Photo::getImageForPhoto($photo);
2268 // If a custom width and height were specified, apply before embedding
2269 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2270 Logger::info('scaling photo');
2272 $width = intval($match[1]);
2273 $height = intval($match[2]);
2275 $photo_img->scaleDown(max($width, $height));
2278 $data = $photo_img->asString();
2279 $type = $photo_img->getType();
2281 Logger::info('replacing photo');
2282 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2283 Logger::debug('replaced', ['image' => $image]);
2289 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2290 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2291 if ($orig_body === false) {
2295 $img_start = strpos($orig_body, '[img');
2296 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2297 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2300 $new_body = $new_body . $orig_body;
2305 private static function hasPermissions(array $obj)
2307 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2308 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2311 // @TODO $uid is unused parameter
2312 private static function samePermissions($uid, array $obj1, array $obj2): bool
2314 // first part is easy. Check that these are exactly the same.
2315 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2316 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2317 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2318 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2322 // This is harder. Parse all the permissions and compare the resulting set.
2323 $recipients1 = self::enumeratePermissions($obj1);
2324 $recipients2 = self::enumeratePermissions($obj2);
2328 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2329 return ($recipients1 == $recipients2);
2333 * Returns an array of contact-ids that are allowed to see this object
2335 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2336 * @param bool $check_dead Prunes unavailable contacts from the result
2338 * @throws \Exception
2340 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2342 $aclFormater = DI::aclFormatter();
2344 $allow_people = $aclFormater->expand($obj['allow_cid']);
2345 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2346 $deny_people = $aclFormater->expand($obj['deny_cid']);
2347 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2348 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2349 $deny = array_unique(array_merge($deny_people, $deny_groups));
2350 $recipients = array_diff($recipients, $deny);
2354 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2356 if (!$uid || ($days < 1)) {
2360 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2361 $uid, GRAVITY_PARENT];
2364 * $expire_network_only = save your own wall posts
2365 * and just expire conversations started by others
2367 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2369 if ($expire_network_only) {
2370 $condition[0] .= " AND NOT `wall`";
2373 if ($network != "") {
2374 $condition[0] .= " AND `network` = ?";
2375 $condition[] = $network;
2378 $condition[0] .= " AND `received` < ?";
2379 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2381 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2383 if (!DBA::isResult($items)) {
2387 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2389 // Forcing expiring of items - but not notes and marked items
2391 $expire_items = true;
2394 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2395 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2396 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2400 $priority = DI::config()->get('system', 'expire-notify-priority');
2402 while ($item = Post::fetch($items)) {
2403 // don't expire filed items
2404 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2408 // Only expire posts, not photos and photo comments
2410 if (!$expire_photos && !empty($item['resource-id'])) {
2412 } elseif (!$expire_starred && intval($item['starred'])) {
2414 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2416 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2420 self::markForDeletionById($item['id'], $priority);
2425 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2428 public static function firstPostDate(int $uid, bool $wall = false)
2430 $user = User::getById($uid, ['register_date']);
2435 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2436 $uid, $wall, $user['register_date']];
2437 $params = ['order' => ['received' => false]];
2438 $thread = Post::selectFirstThread(['received'], $condition, $params);
2439 if (DBA::isResult($thread)) {
2440 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2447 * add/remove activity to an item
2449 * Toggle activities as like,dislike,attend of an item
2451 * @param int $item_id
2452 * @param string $verb
2453 * Activity verb. One of
2454 * like, unlike, dislike, undislike, attendyes, unattendyes,
2455 * attendno, unattendno, attendmaybe, unattendmaybe,
2456 * announce, unannouce
2458 * @param string $allow_cid
2459 * @param string $allow_gid
2460 * @param string $deny_cid
2461 * @param string $deny_gid
2463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2464 * @throws \ImagickException
2465 * @hook 'post_local_end'
2467 * 'post_id' => ID of posted item
2469 public static function performActivity(int $item_id, string $verb, int $uid, string $allow_cid = null, string $allow_gid = null, string $deny_cid = null, string $deny_gid = null): bool
2475 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2477 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2478 if (!DBA::isResult($item)) {
2479 Logger::notice('like: unknown item', ['id' => $item_id]);
2483 $uri_id = $item['uri-id'];
2485 if (!in_array($item['uid'], [0, $uid])) {
2489 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2490 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2491 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2492 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2493 if (!DBA::isResult($item)) {
2494 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2500 // Retrieves the local post owner
2501 $owner = User::getOwnerDataById($uid);
2502 if (empty($owner)) {
2503 Logger::info('Empty owner for user', ['uid' => $uid]);
2507 // Retrieve the current logged in user's public contact
2508 $author_id = Contact::getIdForURL($owner['url']);
2509 if (empty($author_id)) {
2510 Logger::info('Empty public contact');
2518 $activity = Activity::LIKE;
2522 $activity = Activity::DISLIKE;
2526 $activity = Activity::ATTEND;
2530 $activity = Activity::ATTENDNO;
2533 case 'unattendmaybe':
2534 $activity = Activity::ATTENDMAYBE;
2538 $activity = Activity::FOLLOW;
2542 $activity = Activity::ANNOUNCE;
2545 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2549 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2551 // Enable activity toggling instead of on/off
2552 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2554 // Look for an existing verb row
2555 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2556 if ($event_verb_flag) {
2557 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2559 // Translate to the index based activity index
2561 foreach ($verbs as $verb) {
2562 $vids[] = Verb::getID($verb);
2565 $vids = Verb::getID($activity);
2568 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2569 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2570 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2572 if (DBA::isResult($like_item)) {
2574 * Truth table for existing activities
2576 * | Inputs || Outputs |
2577 * |----------------------------||-------------------|
2578 * | Mode | Event | Same verb || Delete? | Return? |
2579 * |--------|-------|-----------||---------|---------|
2580 * | create | Yes | Yes || No | Yes |
2581 * | create | Yes | No || Yes | No |
2582 * | create | No | Yes || No | Yes |
2583 * | create | No | No || N/A†|
2584 * | delete | Yes | Yes || Yes | N/A‡ |
2585 * | delete | Yes | No || No | N/A‡ |
2586 * | delete | No | Yes || Yes | N/A‡ |
2587 * | delete | No | No || N/A†|
2588 * |--------|-------|-----------||---------|---------|
2589 * | A | B | C || A xor C | !B or C |
2591 * †Can't happen: It's impossible to find an existing non-event activity without
2592 * the same verb because we are only looking for this single verb.
2594 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2596 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2597 self::markForDeletionById($like_item['id']);
2600 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2605 // No need to go further if we aren't creating anything
2606 if ($mode == 'delete') {
2610 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2613 'guid' => System::createUUID(),
2614 'uri' => self::newURI(),
2615 'uid' => $item['uid'],
2616 'contact-id' => $owner['id'],
2617 'wall' => $item['wall'],
2619 'network' => Protocol::DFRN,
2620 'protocol' => Conversation::PARCEL_DIRECT,
2621 'direction' => Conversation::PUSH,
2622 'gravity' => GRAVITY_ACTIVITY,
2623 'parent' => $item['id'],
2624 'thr-parent' => $item['uri'],
2625 'owner-id' => $author_id,
2626 'author-id' => $author_id,
2627 'body' => $activity,
2628 'verb' => $activity,
2629 'object-type' => $objtype,
2630 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2631 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2632 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2633 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2638 $signed = Diaspora::createLikeSignature($uid, $new_item);
2639 if (!empty($signed)) {
2640 $new_item['diaspora_signed_text'] = json_encode($signed);
2643 $new_item_id = self::insert($new_item);
2645 // If the parent item isn't visible then set it to visible
2646 if (!$item['visible']) {
2647 self::update(['visible' => true], ['id' => $item['id']]);
2650 $new_item['id'] = $new_item_id;
2652 Hook::callAll('post_local_end', $new_item);
2658 * Fetch the SQL condition for the given user id
2660 * @param integer $owner_id User ID for which the permissions should be fetched
2661 * @return array condition
2663 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2665 $local_user = local_user();
2666 $remote_user = Session::getRemoteContactID($owner_id);
2668 // default permissions - anonymous user
2669 $condition = ["`private` != ?", self::PRIVATE];
2671 if ($local_user && ($local_user == $owner_id)) {
2672 // Profile owner - everything is visible
2674 } elseif ($remote_user) {
2675 // Authenticated visitor - fetch the matching permissionsets
2676 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2678 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2679 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2680 self::PRIVATE, self::PRIVATE];
2681 $condition = array_merge($condition, $permissionSets->column('id'));
2689 * Get a permission SQL string for the given user
2691 * @param int $owner_id
2692 * @param string $table
2695 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2697 $local_user = local_user();
2698 $remote_user = Session::getRemoteContactID($owner_id);
2700 if (!empty($table)) {
2701 $table = DBA::quoteIdentifier($table) . '.';
2705 * Construct permissions
2707 * default permissions - anonymous user
2709 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2711 // Profile owner - everything is visible
2712 if ($local_user && ($local_user == $owner_id)) {
2714 } elseif ($remote_user) {
2716 * Authenticated visitor. Unless pre-verified,
2717 * check that the contact belongs to this $owner_id
2718 * and load the groups the visitor belongs to.
2719 * If pre-verified, the caller is expected to have already
2720 * done this and passed the groups into this function.
2722 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2725 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2730 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2737 * get translated item type
2739 * @param array $item
2740 * @param \Friendica\Core\L10n $l10n
2743 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2745 if (!empty($item['event-id'])) {
2746 return $l10n->t('event');
2747 } elseif (!empty($item['resource-id'])) {
2748 return $l10n->t('photo');
2749 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2750 return $l10n->t('activity');
2751 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2752 return $l10n->t('comment');
2755 return $l10n->t('post');
2759 * Sets the "rendered-html" field of the provided item
2761 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2763 * @param array $item
2765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2766 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2768 private static function putInCache(&$item)
2770 // Save original body to prevent addons to modify it
2771 $body = $item['body'];
2773 $rendered_hash = $item['rendered-hash'] ?? '';
2774 $rendered_html = $item['rendered-html'] ?? '';
2776 if ($rendered_hash == ''
2777 || $rendered_html == ''
2778 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2779 || DI::config()->get('system', 'ignore_cache')
2781 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2782 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2784 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2785 Hook::callAll('put_item_in_cache', $hook_data);
2786 $item['rendered-html'] = $hook_data['rendered-html'];
2787 $item['rendered-hash'] = $hook_data['rendered-hash'];
2790 // Update if the generated values differ from the existing ones
2791 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2794 'rendered-html' => $item['rendered-html'],
2795 'rendered-hash' => $item['rendered-hash']
2797 ['id' => $item['id']]
2802 $item['body'] = $body;
2806 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2807 * If attach is true, also add icons for item attachments.
2809 * @param array $item Record from item table
2810 * @param boolean $attach If true, add icons for item attachments as well
2811 * @param boolean $is_preview Whether this is a preview
2812 * @param boolean $only_cache Whether only cached HTML should be updated
2813 * @return string item body html
2814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2815 * @throws \ImagickException
2816 * @hook prepare_body_init item array before any work
2817 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2818 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2819 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2821 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2824 Hook::callAll('prepare_body_init', $item);
2826 // In order to provide theme developers more possibilities, event items
2827 // are treated differently.
2828 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2829 $ev = Event::getItemHTML($item);
2833 $tags = Tag::populateFromItem($item);
2835 $item['tags'] = $tags['tags'];
2836 $item['hashtags'] = $tags['hashtags'];
2837 $item['mentions'] = $tags['mentions'];
2839 $body = $item['body'] ?? '';
2840 $shared = BBCode::fetchShareAttributes($body);
2841 if (!empty($shared['guid'])) {
2842 $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2843 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2844 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2845 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2846 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2847 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2848 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2849 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2855 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2856 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2858 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2859 self::putInCache($item);
2860 $item['body'] = $body;
2861 $s = $item["rendered-html"];
2867 // Compile eventual content filter reasons
2868 $filter_reasons = [];
2869 if (!$is_preview && public_contact() != $item['author-id']) {
2870 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2871 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2874 $item['attachments'] = $attachments;
2878 'filter_reasons' => $filter_reasons
2880 Hook::callAll('prepare_body_content_filter', $hook_data);
2881 $filter_reasons = $hook_data['filter_reasons'];
2888 'preview' => $is_preview,
2889 'filter_reasons' => $filter_reasons
2891 Hook::callAll('prepare_body', $hook_data);
2892 $s = $hook_data['html'];
2896 // Replace the blockquotes with quotes that are used in mails.
2897 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2898 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2902 if (!empty($shared_attachments)) {
2903 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2904 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2905 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2906 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2909 $s = self::addVisualAttachments($attachments, $item, $s, false);
2910 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2911 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2912 $s = self::addQuestions($item, $s);
2915 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2916 $x = Map::byCoordinates(trim($item['coord']));
2918 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2922 // Replace friendica image url size with theme preference.
2923 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2924 $ps = $a->getThemeInfoValue('item_image_size');
2925 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2928 $s = HTML::applyContentFilter($s, $filter_reasons);
2930 $hook_data = ['item' => $item, 'html' => $s];
2931 Hook::callAll('prepare_body_final', $hook_data);
2933 return $hook_data['html'];
2937 * Check if the body contains a link
2939 * @param string $body
2940 * @param string $url
2944 public static function containsLink(string $body, string $url, int $type = 0): bool
2946 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2947 $urlparts = parse_url($url);
2948 if (!empty($urlparts)) {
2949 unset($urlparts['query']);
2950 unset($urlparts['fragment']);
2951 $url = (string)Uri::fromParts($urlparts);
2956 // Remove media links to only search in embedded content
2957 // @todo Check images for image link, audio for audio links, ...
2958 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2959 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2962 if (strpos($body, $url)) {
2965 foreach ([0, 1, 2] as $size) {
2966 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2967 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2975 * Replace visual attachments in the body
2977 * @param array $attachments
2978 * @param string $body
2979 * @return string modified body
2981 private static function replaceVisualAttachments(array $attachments, string $body): string
2983 DI::profiler()->startRecording('rendering');
2985 foreach ($attachments['visual'] as $attachment) {
2986 if (!empty($attachment['preview'])) {
2987 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2988 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
2989 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
2991 $body = str_replace($search, $replace, $body);
2992 } elseif ($attachment['filetype'] == 'image') {
2993 $proxy = Post\Media::getUrlForId($attachment['id']);
2994 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
2995 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
2997 $body = str_replace($search, $replace, $body);
3000 DI::profiler()->stopRecording();
3005 * Add visual attachments to the content
3007 * @param array $attachments
3008 * @param array $item
3009 * @param string $content
3010 * @return string modified content
3012 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3014 DI::profiler()->startRecording('rendering');
3018 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3019 foreach ($attachments['visual'] as $attachment) {
3020 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3024 if (!empty($attachment['preview'])) {
3025 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3030 if (($attachment['filetype'] == 'video')) {
3031 /// @todo Move the template to /content as well
3032 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3034 'id' => $attachment['id'],
3035 'src' => $attachment['url'],
3036 'name' => $attachment['name'] ?: $attachment['url'],
3037 'preview' => $preview_url,
3038 'mime' => $attachment['mimetype'],
3041 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3044 $trailing .= $media;
3046 } elseif ($attachment['filetype'] == 'audio') {
3047 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3049 'id' => $attachment['id'],
3050 'src' => $attachment['url'],
3051 'name' => $attachment['name'] ?: $attachment['url'],
3052 'mime' => $attachment['mimetype'],
3055 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3058 $trailing .= $media;
3060 } elseif ($attachment['filetype'] == 'image') {
3061 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3063 'src' => Post\Media::getUrlForId($attachment['id']),
3064 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3065 'attachment' => $attachment,
3068 // On Diaspora posts the attached pictures are leading
3069 if ($item['network'] == Protocol::DIASPORA) {
3072 $trailing .= $media;
3078 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3079 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3081 if ($leading != '') {
3082 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3085 if ($trailing != '') {
3086 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3090 DI::profiler()->stopRecording();
3095 * Add link attachment to the content
3097 * @param array $attachments
3098 * @param string $body
3099 * @param string $content
3100 * @param bool $shared
3101 * @param array $ignore_links A list of URLs to ignore
3102 * @return string modified content
3104 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3106 DI::profiler()->startRecording('rendering');
3107 // Don't show a preview when there is a visual attachment (audio or video)
3108 $types = array_column($attachments['visual'], 'type');
3109 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3111 if (!empty($attachments['link'])) {
3112 foreach ($attachments['link'] as $link) {
3114 foreach ($ignore_links as $ignore_link) {
3115 if (Strings::compareLink($link['url'], $ignore_link)) {
3119 // @todo Judge between the links to use the one with most information
3120 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3121 (empty($attachment['name']) && !empty($link['name'])) ||
3122 (empty($attachment['description']) && !empty($link['description'])) ||
3123 (empty($attachment['preview']) && !empty($link['preview'])))) {
3124 $attachment = $link;
3129 if (!empty($attachment)) {
3132 'author_name' => $attachment['author-name'] ?? '',
3133 'author_url' => $attachment['author-url'] ?? '',
3134 'description' => $attachment['description'] ?? '',
3137 'provider_name' => $attachment['publisher-name'] ?? '',
3138 'provider_url' => $attachment['publisher-url'] ?? '',
3140 'title' => $attachment['name'] ?? '',
3142 'url' => $attachment['url']];
3144 if ($preview && !empty($attachment['preview'])) {
3145 if ($attachment['preview-width'] >= 500) {
3146 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3148 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3152 if (!empty($data['description']) && !empty($content)) {
3153 similar_text($data['description'], $content, $percent);
3158 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3159 $data['description'] = '';
3162 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3163 $data['author_name'] = '';
3166 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3167 $data['author_url'] = '';
3169 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3170 $data = BBCode::getAttachmentData($match[1]);
3172 DI::profiler()->stopRecording();
3174 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3175 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3176 $parts = parse_url($data['url']);
3177 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3178 if (empty($data['provider_name'])) {
3179 $data['provider_name'] = $parts['host'];
3181 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3182 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3184 if (!empty($parts['port'])) {
3185 $data['provider_url'] .= ':' . $parts['port'];
3190 // @todo Use a template
3191 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3192 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3193 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3194 '$url' => $data['url'],
3195 '$title' => $data['title'],
3202 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3204 return $content . $rendered;
3211 * Add non visual attachments to the content
3213 * @param array $attachments
3214 * @param array $item
3215 * @param string $content
3216 * @return string modified content
3218 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3220 DI::profiler()->startRecording('rendering');
3222 foreach ($attachments['additional'] as $attachment) {
3223 if (strpos($item['body'], $attachment['url'])) {
3227 $author = ['uid' => 0, 'id' => $item['author-id'],
3228 'network' => $item['author-network'], 'url' => $item['author-link']];
3229 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3231 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3233 if (!empty($attachment['size'])) {
3234 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3237 /// @todo Use a template
3238 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3239 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3242 if ($trailing != '') {
3243 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3246 DI::profiler()->stopRecording();
3250 private static function addQuestions(array $item, string $content): string
3252 DI::profiler()->startRecording('rendering');
3253 if (!empty($item['question-id'])) {
3255 'id' => $item['question-id'],
3256 'multiple' => $item['question-multiple'],
3257 'voters' => $item['question-voters'],
3258 'endtime' => $item['question-end-time']
3261 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3262 foreach ($options as $key => $option) {
3263 $percent = $question['voters'] ? ($option['replies'] / $question['voters'] * 100) : 0;
3265 $options[$key]['percent'] = $percent;
3267 if ($question['voters'] > 0) {
3268 $options[$key]['vote'] = DI::l10n()->t('%s (%d%s, %d votes)', $option['name'], round($percent, 1), '%', $option['replies']);
3270 $options[$key]['vote'] = DI::l10n()->t('%s (%d votes)', $option['name'], $option['replies']);
3274 if (!empty($question['voters']) && !empty($question['endtime'])) {
3275 $summary = DI::l10n()->t('%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3276 } elseif (!empty($question['voters'])) {
3277 $summary = DI::l10n()->t('%d voters.', $question['voters']);
3278 } elseif (!empty($question['endtime'])) {
3279 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3284 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3285 '$question' => $question,
3286 '$options' => $options,
3287 '$summary' => $summary,
3290 DI::profiler()->stopRecording();
3295 * get private link for item
3297 * @param array $item
3298 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3299 * @throws \Exception
3301 public static function getPlink(array $item)
3303 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3304 $plink = $item['plink'];
3305 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3306 $plink = $item['uri'];
3311 'href' => "display/" . $item['guid'],
3312 'orig' => "display/" . $item['guid'],
3313 'title' => DI::l10n()->t('View on separate page'),
3314 'orig_title' => DI::l10n()->t('View on separate page'),
3317 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3318 $author = ['uid' => 0, 'id' => $item['author-id'],
3319 'network' => $item['author-network'], 'url' => $item['author-link']];
3320 $plink = Contact::magicLinkByContact($author, $plink);
3323 if (!empty($plink)) {
3324 $ret['href'] = DI::baseUrl()->remove($plink);
3325 $ret['title'] = DI::l10n()->t('Link to source');
3327 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3331 'title' => DI::l10n()->t('Link to source'),
3332 'orig_title' => DI::l10n()->t('Link to source'),
3342 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3344 * @param int $uri_id
3346 * @return boolean "true" when it is a forum post
3348 public static function isForumPost(int $uri_id): bool
3350 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3351 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3359 * Search item id for given URI or plink
3361 * @param string $uri
3362 * @param integer $uid
3364 * @return integer item id
3366 public static function searchByLink(string $uri, int $uid = 0): int
3368 $ssl_uri = str_replace('http://', 'https://', $uri);
3369 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3371 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3372 if (DBA::isResult($item)) {
3376 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3377 if (DBA::isResult($item)) {
3385 * Return the URI for a link to the post
3387 * @param string $uri URI or link to post
3389 * @return string URI
3391 public static function getURIByLink(string $uri): string
3393 $ssl_uri = str_replace('http://', 'https://', $uri);
3394 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3396 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3397 if (DBA::isResult($item)) {
3398 return $item['uri'];
3401 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3402 if (DBA::isResult($item)) {
3403 return $item['uri'];
3410 * Fetches item for given URI or plink
3412 * @param string $uri
3413 * @param integer $uid
3415 * @return integer item id
3417 public static function fetchByLink(string $uri, int $uid = 0): int
3419 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3420 $item_id = self::searchByLink($uri, $uid);
3421 if (!empty($item_id)) {
3422 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3432 Hook::callAll('item_by_link', $hookData);
3434 if (isset($hookData['item_id'])) {
3435 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3438 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3441 $item_id = self::searchByLink($fetched_uri, $uid);
3443 $item_id = Diaspora::fetchByURL($uri);
3446 if (!empty($item_id)) {
3447 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3451 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3456 * Return share data from an item array (if the item is shared item)
3457 * We are providing the complete Item array, because at some time in the future
3458 * we hopefully will define these values not in the body anymore but in some item fields.
3459 * This function is meant to replace all similar functions in the system.
3461 * @param array $item
3463 * @return array with share information
3465 public static function getShareArray(array $item): array
3467 return BBCode::fetchShareAttributes($item['body']);
3471 * Fetch item information for shared items from the original items and adds it.
3473 * @param array $item
3475 * @return array item array with data from the original item
3477 public static function addShareDataFromOriginal(array $item): array
3479 $shared = self::getShareArray($item);
3480 if (empty($shared)) {
3484 // Real reshares always have got a GUID.
3485 if (empty($shared['guid'])) {
3489 $uid = $item['uid'] ?? 0;
3491 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3492 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3493 if (!DBA::isResult($shared_item)) {
3494 if (empty($shared['link'])) {
3498 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3499 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3501 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3505 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3506 if (!DBA::isResult($shared_item)) {
3509 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3511 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3514 if (!empty($shared_item['title'])) {
3515 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3516 unset($shared_item['title']);
3518 $body = $shared_item['body'];
3521 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3522 unset($shared_item['body']);
3524 return array_merge($item, $shared_item);
3528 * Check a prospective item array against user-level permissions
3530 * @param array $item Expected keys: uri, gravity, and
3531 * author-link if is author-id is set,
3532 * owner-link if is owner-id is set,
3533 * causer-link if is causer-id is set.
3534 * @param int $user_id Local user ID
3536 * @throws \Exception
3538 protected static function isAllowedByUser(array $item, int $user_id): bool
3540 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3541 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3545 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3546 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3550 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3551 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3552 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3556 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3557 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3565 * Improve the data in shared posts
3567 * @param array $item
3568 * @return string body
3570 public static function improveSharedDataInBody(array $item): string
3572 $shared = BBCode::fetchShareAttributes($item['body']);
3573 if (empty($shared['link'])) {
3574 return $item['body'];
3577 $id = self::fetchByLink($shared['link']);
3578 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3580 return $item['body'];
3583 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3584 if (!DBA::isResult($shared_item)) {
3585 return $item['body'];
3588 $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']);
3590 if (!empty($shared_item['title'])) {
3591 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3594 $shared_content .= $shared_item['body'];
3596 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3597 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3598 return $item['body'];