3 * @copyright Copyright (C) 2010-2023, 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\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Network\HTTPException\InternalServerErrorException;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Delivery;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Posting reasons (Why had a post been stored for a user?)
69 const PR_FOLLOWER = 69;
70 const PR_ANNOUNCEMENT = 70;
71 const PR_COMMENT = 71;
75 const PR_FETCHED = 75;
76 const PR_COMPLETION = 76;
78 const PR_ACTIVITY = 78;
79 const PR_DISTRIBUTE = 79;
82 const PR_AUDIENCE = 82;
84 // system.accept_only_sharer setting values
85 const COMPLETION_NONE = 1;
86 const COMPLETION_COMMENT = 0;
87 const COMPLETION_LIKE = 2;
89 // Field list that is used to display the items
90 const DISPLAY_FIELDLIST = [
91 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
92 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
93 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
94 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
95 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
96 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
97 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
98 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
99 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
100 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
101 'writable', 'self', 'cid', 'alias',
102 'event-created', 'event-edited', 'event-start', 'event-finish',
103 'event-summary', 'event-desc', 'event-location', 'event-type',
104 'event-nofinish', 'event-ignore', 'event-id',
105 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
106 'has-categories', 'has-media',
107 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
110 // Field list that is used to deliver items via the protocols
111 const DELIVER_FIELDLIST = [
112 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
113 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
114 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
115 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
116 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
117 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
118 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
119 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
120 'event-created', 'event-edited', 'event-start', 'event-finish',
121 'event-summary', 'event-desc', 'event-location', 'event-type',
122 'event-nofinish', 'event-ignore', 'event-id'
125 // All fields in the item table
126 const ITEM_FIELDLIST = [
127 'id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
128 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
129 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
130 'created', 'edited', 'commented', 'received', 'changed', 'verb',
131 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
132 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
133 'private', 'pubmail', 'visible', 'starred',
134 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
135 'title', 'content-warning', 'body', 'location', 'coord', 'app',
136 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
137 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
138 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'
141 // List of all verbs that don't need additional content data.
142 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
144 Activity::LIKE, Activity::DISLIKE,
145 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
155 // Item weight for query ordering
156 const GRAVITY_PARENT = 0;
157 const GRAVITY_ACTIVITY = 3;
158 const GRAVITY_COMMENT = 6;
159 const GRAVITY_UNKNOWN = 9;
162 * Update existing item entries
164 * @param array $fields The fields that are to be changed
165 * @param array $condition The condition for finding the item entries
167 * In the future we may have to change permissions as well.
168 * Then we had to add the user id as third parameter.
170 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
172 * @return integer|boolean number of affected rows - or "false" if there was an error
173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
175 public static function update(array $fields, array $condition)
177 if (empty($condition) || empty($fields)) {
181 if (isset($fields['extid'])) {
182 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
185 if (!empty($fields['verb'])) {
186 $fields['vid'] = Verb::getID($fields['verb']);
189 if (!empty($fields['edited'])) {
190 $previous = Post::selectFirst(['edited'], $condition);
193 $rows = Post::update($fields, $condition);
194 if (is_bool($rows)) {
198 // We only need to call the line by line update for specific fields
200 empty($fields['body']) && empty($fields['file']) &&
201 empty($fields['attach']) && empty($fields['edited'])
206 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
208 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
212 while ($item = DBA::fetch($items)) {
213 if (!empty($fields['body'])) {
214 if (!empty($item['quote-uri-id'])) {
215 $fields['body'] = BBCode::removeSharedData($fields['body']);
217 if (!empty($fields['raw-body'])) {
218 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
222 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
224 // Remove all media attachments from the body and store them in the post-media table
225 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
226 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
227 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
229 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
231 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
232 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
234 Post\Content::update($item['uri-id'], $content_fields);
237 if (!empty($fields['file'])) {
238 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
241 if (!empty($fields['attach'])) {
242 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
245 // We only need to notify others when it is an original entry from us.
246 // Only call the notifier when the item had been edited and records had been changed.
247 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
248 $notify_items[] = $item['id'];
254 foreach ($notify_items as $notify_item) {
255 $post = Post::selectFirst([], ['id' => $notify_item]);
257 if ($post['gravity'] != self::GRAVITY_PARENT) {
258 $signed = Diaspora::createCommentSignature($post);
259 if (!empty($signed)) {
260 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
264 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
271 * Delete an item and notify others about it - if it was ours
273 * @param array $condition The condition for finding the item entries
274 * @param integer $priority Priority for the notification
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
280 $items = Post::select(['id'], $condition);
281 while ($item = Post::fetch($items)) {
282 self::markForDeletionById($item['id'], $priority);
288 * Delete an item for an user and notify others about it - if it was ours
290 * @param array $condition The condition for finding the item entries
291 * @param integer $uid User who wants to delete this item
293 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 public static function deleteForUser(array $condition, int $uid)
301 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
302 while ($item = Post::fetch($items)) {
303 if (in_array($item['uid'], [$uid, 0])) {
304 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
305 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
308 if ($item['uid'] == $uid) {
309 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
310 } elseif ($item['uid'] != 0) {
311 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
318 * Mark an item for deletion, delete related data and notify others about it - if it was ours
320 * @param integer $item_id
321 * @param integer $priority Priority for the notification
322 * @return boolean success
323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
327 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
328 // locate item to be deleted
330 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
331 'deleted', 'resource-id', 'event-id',
332 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'
334 $item = Post::selectFirst($fields, ['id' => $item_id]);
335 if (!DBA::isResult($item)) {
336 Logger::info('Item not found.', ['id' => $item_id]);
340 if ($item['deleted']) {
341 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
345 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
346 if (!DBA::isResult($parent)) {
347 $parent = ['origin' => false];
350 // clean up categories and tags so they don't end up as orphans
351 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
354 * If item is a link to a photo resource, nuke all the associated photos
355 * (visitors will not have photo resources)
356 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
357 * generate a resource-id and therefore aren't intimately linked to the item.
359 /// @TODO: this should first check if photo is used elsewhere
360 if ($item['resource-id']) {
361 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
364 // If item is a link to an event, delete the event.
365 if (intval($item['event-id'])) {
366 Event::delete($item['event-id']);
369 // If item has attachments, drop them
370 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
371 foreach ($attachments as $attachment) {
372 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
373 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
377 // Set the item to "deleted"
378 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
379 Post::update($item_fields, ['id' => $item['id']]);
381 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
383 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
384 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
387 Post\DeliveryData::delete($item['uri-id']);
389 // If it's the parent of a comment thread, kill all the kids
390 if ($item['gravity'] == self::GRAVITY_PARENT) {
391 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
394 // Is it our comment and/or our thread?
395 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
396 // When we delete the original post we will delete all existing copies on the server as well
397 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
399 // send the notification upstream/downstream
401 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
403 } elseif ($item['uid'] != 0) {
404 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
405 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
408 DI::notify()->deleteForItem($item['uri-id']);
409 DI::notification()->deleteForItem($item['uri-id']);
411 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
417 * Get guid from given item record
419 * @param array $item Item record
420 * @param bool Whether to notify (?)
421 * @return string Guid
423 public static function guid(array $item, bool $notify): string
425 if (!empty($item['guid'])) {
426 return trim($item['guid']);
430 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
431 // We add the hash of our own host because our host is the original creator of the post.
432 $prefix_host = DI::baseUrl()->getHost();
436 // We are only storing the post so we create a GUID from the original hostname.
437 if (!empty($item['author-link'])) {
438 $parsed = parse_url($item['author-link']);
439 if (!empty($parsed['host'])) {
440 $prefix_host = $parsed['host'];
444 if (empty($prefix_host) && !empty($item['plink'])) {
445 $parsed = parse_url($item['plink']);
446 if (!empty($parsed['host'])) {
447 $prefix_host = $parsed['host'];
451 if (empty($prefix_host) && !empty($item['uri'])) {
452 $parsed = parse_url($item['uri']);
453 if (!empty($parsed['host'])) {
454 $prefix_host = $parsed['host'];
458 // Is it in the format data@host.tld? - Used for mail contacts
459 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
460 $mailparts = explode('@', $item['author-link']);
461 $prefix_host = array_pop($mailparts);
465 if (!empty($item['plink'])) {
466 $guid = self::guidFromUri($item['plink'], $prefix_host);
467 } elseif (!empty($item['uri'])) {
468 $guid = self::guidFromUri($item['uri'], $prefix_host);
470 $guid = System::createUUID(hash('crc32', $prefix_host));
477 * Returns contact id from given item record
479 * @param array $item Item record
480 * @return int Contact id
482 private static function contactId(array $item): int
484 if ($item['uid'] == 0) {
485 return $item['owner-id'];
488 if ($item['origin']) {
489 $owner = User::getOwnerDataById($item['uid']);
493 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
494 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
495 if (!empty($cdata['user'])) {
496 return $cdata['user'];
500 foreach (['owner-link', 'author-link', 'causer-link'] as $field) {
501 if (empty($item[$field])) {
504 if (Contact::isSharingByURL($item[$field], $item['uid'], true)) {
505 $contact_id = Contact::getIdForURL($item[$field], $item['uid']);
507 $contact_id = Contact::getIdForURL($item[$field]);
509 if (!empty($contact_id)) {
514 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
515 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
520 * Write an item array into a spool file to be inserted later.
521 * This command is called whenever there are issues storing an item.
523 * @param array $item The item fields that are to be inserted
526 private static function spool(array $item)
528 // Now we store the data in the spool directory
529 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
530 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
532 $spoolpath = System::getSpoolPath();
533 if ($spoolpath != '') {
534 $spool = $spoolpath . '/' . $file;
536 file_put_contents($spool, json_encode($item));
537 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
542 * Check if the item array is a duplicate
544 * @param array $item Item record
545 * @return boolean is it a duplicate?
547 private static function isDuplicate(array $item): bool
549 // Checking if there is already an item with the same guid
550 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
551 if (Post::exists($condition)) {
552 Logger::notice('Found already existing item', $condition);
557 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
558 'network' => [$item['network'], Protocol::DFRN]
560 if (Post::exists($condition)) {
561 Logger::notice('duplicated item with the same uri found.', $condition);
565 // On Friendica and Diaspora the GUID is unique
566 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
567 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
568 if (Post::exists($condition)) {
569 Logger::notice('duplicated item with the same guid found.', $condition);
572 } elseif ($item['network'] == Protocol::OSTATUS) {
573 // Check for an existing post with the same content. There seems to be a problem with OStatus.
575 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
576 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
578 if (Post::exists($condition)) {
579 Logger::notice('duplicated item with the same body found.', $item);
585 * Check for already added items.
586 * There is a timing issue here that sometimes creates double postings.
587 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
589 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
590 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
598 * Check if the item array is valid
600 * @param array $item Item record
601 * @return boolean item is valid
603 public static function isValid(array $item): bool
605 // When there is no content then we don't post it
606 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
607 Logger::notice('No body, no title.');
611 if (!empty($item['uid'])) {
612 $owner = User::getOwnerDataById($item['uid'], false);
614 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
618 if ($owner['account_expired'] || $owner['account_removed']) {
619 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']]);
624 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
625 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
629 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
630 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
634 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
635 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
639 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
640 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
644 if ($item['verb'] == Activity::FOLLOW) {
645 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
646 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
647 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
652 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
653 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
655 if (Post::exists($condition)) {
656 // It happens that we receive multiple follow requests by the same author - we only store one.
657 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
666 * Check if the item array is too old
668 * @param array $item Item record
669 * @return boolean item is too old
671 public static function isTooOld(array $item): bool
673 // check for create date and expire time
674 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
676 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
677 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
678 $expire_interval = $user['expire'];
681 if (($expire_interval > 0) && !empty($item['created'])) {
682 $expire_date = time() - ($expire_interval * 86400);
683 $created_date = strtotime($item['created']);
684 if ($created_date < $expire_date) {
685 Logger::notice('Item created before expiration interval.', [
686 'created' => date('c', $created_date),
687 'expired' => date('c', $expire_date),
698 * Return the id of the given item array if it has been stored before
700 * @param array $item Item record
701 * @return integer Item id or zero on error
703 private static function getDuplicateID(array $item): int
705 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
707 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
710 Protocol::ACTIVITYPUB,
715 $existing = Post::selectFirst(['id', 'network'], $condition);
716 if (DBA::isResult($existing)) {
717 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
718 if ($item['uid'] != 0) {
719 Logger::notice('Item already existed for user', [
720 'uri-id' => $item['uri-id'],
721 'uid' => $item['uid'],
722 'network' => $item['network'],
723 'existing_id' => $existing['id'],
724 'existing_network' => $existing['network']
728 return $existing['id'];
735 * Fetch the uri-id of the parent for the given uri-id
737 * @param integer $uriid
740 public static function getParent(int $uriid): int
742 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
743 if (empty($thread_parent)) {
747 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
751 return self::getParent($thread_parent['thr-parent-id']);
755 * Fetch top-level parent data for the given item array
758 * @return array item array with parent data
761 private static function getTopLevelParent(array $item): array
764 'uid', 'uri', 'parent-uri', 'id', 'deleted',
765 'uri-id', 'parent-uri-id',
766 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
767 'wall', 'private', 'origin', 'author-id'
769 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
770 $params = ['order' => ['id' => false]];
771 $parent = Post::selectFirst($fields, $condition, $params);
773 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
774 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
775 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
776 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
779 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
780 $parent = Post::selectFirst($fields, $condition, $params);
784 if (!DBA::isResult($parent)) {
785 Logger::notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'callstack' => System::callstack(20)]);
789 if ($parent['uri-id'] == $parent['parent-uri-id']) {
794 'uri-id' => $parent['parent-uri-id'],
795 'parent-uri-id' => $parent['parent-uri-id'],
796 'uid' => $parent['uid']
798 $params = ['order' => ['id' => false]];
799 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
801 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
802 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
803 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
804 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
807 if (!DBA::isResult($toplevel_parent)) {
808 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
812 return $toplevel_parent;
816 * Get the gravity for the given item array
819 * @return integer gravity
821 private static function getGravity(array $item): int
823 $activity = DI::activity();
825 if (isset($item['gravity'])) {
826 return intval($item['gravity']);
827 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
828 return self::GRAVITY_PARENT;
829 } elseif ($activity->match($item['verb'], Activity::POST)) {
830 return self::GRAVITY_COMMENT;
831 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
832 return self::GRAVITY_ACTIVITY;
833 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
834 return self::GRAVITY_ACTIVITY;
837 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
838 return self::GRAVITY_UNKNOWN; // Should not happen
841 private static function prepareOriginPost(array $item): array
843 $item = DI::contentItem()->initializePost($item);
844 $item = DI::contentItem()->finalizePost($item);
850 * Inserts item record
852 * @param array $item Item array to be inserted
853 * @param int $notify Notification (type?)
854 * @param bool $post_local (???)
855 * @return int Zero means error, otherwise primary key (id) is being returned
857 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
861 $priority = Worker::PRIORITY_HIGH;
863 // If it is a posting where users should get notifications, then define it as wall posting
865 $item = self::prepareOriginPost($item);
867 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
871 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
874 $uid = intval($item['uid']);
876 $item['guid'] = self::guid($item, $notify);
877 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
880 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
882 // Backward compatibility: parent-uri used to be the direct parent uri.
883 // If it is provided without a thr-parent, it probably is the old behavior.
884 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
885 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
886 $item['parent-uri'] = $item['thr-parent'];
889 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
890 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
892 // Store conversation data
893 $source = $item['source'] ?? '';
894 unset($item['conversation-uri']);
895 unset($item['conversation-href']);
896 unset($item['source']);
899 * Do we already have this item?
900 * We have to check several networks since Friendica posts could be repeated
901 * via OStatus (maybe Diaspora as well)
903 $duplicate = self::getDuplicateID($item);
908 // Additional duplicate checks
909 /// @todo Check why the first duplication check returns the item number and the second a 0
910 if (self::isDuplicate($item)) {
914 if (!isset($item['post-type'])) {
915 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
918 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
920 $item['wall'] = intval($item['wall'] ?? 0);
921 $item['extid'] = trim($item['extid'] ?? '');
922 $item['author-name'] = trim($item['author-name'] ?? '');
923 $item['author-link'] = trim($item['author-link'] ?? '');
924 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
925 $item['owner-name'] = trim($item['owner-name'] ?? '');
926 $item['owner-link'] = trim($item['owner-link'] ?? '');
927 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
928 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
929 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
930 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
931 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
932 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
933 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
934 $item['location'] = trim($item['location'] ?? '');
935 $item['coord'] = trim($item['coord'] ?? '');
936 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
937 $item['deleted'] = 0;
938 $item['verb'] = trim($item['verb'] ?? '');
939 $item['object-type'] = trim($item['object-type'] ?? '');
940 $item['object'] = trim($item['object'] ?? '');
941 $item['target-type'] = trim($item['target-type'] ?? '');
942 $item['target'] = trim($item['target'] ?? '');
943 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
944 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
945 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
946 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
947 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
948 $item['private'] = intval($item['private'] ?? self::PUBLIC);
949 $item['body'] = trim($item['body'] ?? '');
950 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
951 $item['app'] = trim($item['app'] ?? '');
952 $item['origin'] = intval($item['origin'] ?? 0);
953 $item['postopts'] = trim($item['postopts'] ?? '');
954 $item['resource-id'] = trim($item['resource-id'] ?? '');
955 $item['event-id'] = intval($item['event-id'] ?? 0);
956 $item['inform'] = trim($item['inform'] ?? '');
957 $item['file'] = trim($item['file'] ?? '');
959 // Communities aren't working with the Diaspora protocol
960 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
961 $user = User::getById($uid, ['account-type']);
962 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
963 Logger::info('Community posts are not supported via Diaspora');
968 // Items cannot be stored before they happen ...
969 if ($item['created'] > DateTimeFormat::utcNow()) {
970 $item['created'] = DateTimeFormat::utcNow();
973 // We haven't invented time travel by now.
974 if ($item['edited'] > DateTimeFormat::utcNow()) {
975 $item['edited'] = DateTimeFormat::utcNow();
978 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
980 $item['gravity'] = self::getGravity($item);
983 'url' => $item['author-link'], 'name' => $item['author-name'],
984 'photo' => $item['author-avatar'], 'network' => $item['network']
986 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
989 'url' => $item['owner-link'], 'name' => $item['owner-name'],
990 'photo' => $item['owner-avatar'], 'network' => $item['network']
992 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
994 $item['post-reason'] = self::getPostReason($item);
996 // Ensure that there is an avatar cache
997 Contact::checkAvatarCache($item['author-id']);
998 Contact::checkAvatarCache($item['owner-id']);
1000 $item['contact-id'] = self::contactId($item);
1003 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1004 empty($item['origin']) && self::isTooOld($item)
1006 Logger::info('Item is too old', ['item' => $item]);
1010 if (!self::isValid($item)) {
1014 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1015 $toplevel_parent = self::getTopLevelParent($item);
1016 if (empty($toplevel_parent)) {
1020 $parent_id = $toplevel_parent['id'];
1021 $item['parent-uri'] = $toplevel_parent['uri'];
1022 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1023 $item['deleted'] = $toplevel_parent['deleted'];
1024 $item['wall'] = $toplevel_parent['wall'];
1026 // Reshares have to keep their permissions to allow groups to work
1027 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1028 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1029 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1030 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1031 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1034 $parent_origin = $toplevel_parent['origin'];
1036 // Don't federate received participation messages
1037 if ($item['verb'] != Activity::FOLLOW) {
1038 $item['wall'] = $toplevel_parent['wall'];
1040 $item['wall'] = false;
1041 // Participations are technical messages, so they are set to "seen" automatically
1042 $item['unseen'] = false;
1046 * If the parent is private, force privacy for the entire conversation
1047 * This differs from the above settings as it subtly allows comments from
1048 * email correspondents to be private even if the overall thread is not.
1050 if (!$defined_permissions && $toplevel_parent['private']) {
1051 $item['private'] = $toplevel_parent['private'];
1054 // If its a post that originated here then tag the thread as "mention"
1055 if ($item['origin'] && $item['uid']) {
1056 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1057 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1060 // Update the contact relations
1061 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1064 $parent_origin = $item['origin'];
1066 if ($item['wall'] && empty($item['conversation'])) {
1067 $item['conversation'] = $item['parent-uri'] . '#context';
1071 if ($item['origin']) {
1072 if (Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])) {
1073 $item['object-type'] = Activity\ObjectType::IMAGE;
1076 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1079 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1080 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1082 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1083 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1086 // Is this item available in the global items (with uid=0)?
1087 if ($item['uid'] == 0) {
1088 $item['global'] = true;
1090 // Set the global flag on all items if this was a global item entry
1091 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1093 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1097 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1098 $item['private'] = self::PRIVATE;
1101 if ($notify && $post_local) {
1102 $item['edit'] = false;
1103 $item['parent'] = $parent_id;
1105 // Trigger automatic reactions for addons
1106 if (!isset($item['api_source'])) {
1107 $item['api_source'] = true;
1110 // We have to tell the hooks who we are - this really should be improved
1111 if (!DI::userSession()->getLocalUserId()) {
1112 $_SESSION['authenticated'] = true;
1113 $_SESSION['uid'] = $uid;
1114 $dummy_session = true;
1116 $dummy_session = false;
1119 Hook::callAll('post_local', $item);
1121 if ($dummy_session) {
1122 unset($_SESSION['authenticated']);
1123 unset($_SESSION['uid']);
1125 } elseif (!$notify) {
1126 Hook::callAll('post_remote', $item);
1129 if (!empty($item['cancel'])) {
1130 Logger::notice('post cancelled by addon.');
1134 if (empty($item['vid']) && !empty($item['verb'])) {
1135 $item['vid'] = Verb::getID($item['verb']);
1138 // Creates or assigns the permission set
1139 $item['psid'] = DI::permissionSet()->selectOrCreate(
1140 DI::permissionSetFactory()->createFromString(
1149 if (!empty($item['extid'])) {
1150 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1153 if ($item['verb'] == Activity::ANNOUNCE) {
1154 self::setOwnerforResharedItem($item);
1157 if (isset($item['attachments'])) {
1158 foreach ($item['attachments'] as $attachment) {
1159 $attachment['uri-id'] = $item['uri-id'];
1160 Post\Media::insert($attachment);
1162 unset($item['attachments']);
1165 if (empty($item['quote-uri-id'])) {
1166 $quote_id = self::getQuoteUriId($item['body']);
1167 if (!empty($quote_id)) {
1168 // This is one of these "should not happen" situations.
1169 // The protocol implementations should already have done this job.
1170 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1171 $item['quote-uri-id'] = $quote_id;
1175 if (!empty($item['quote-uri-id'])) {
1176 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1177 $item['body'] = BBCode::removeSharedData($item['body']);
1180 // Remove all media attachments from the body and store them in the post-media table
1181 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1182 $item['raw-body'] = self::setHashtags($item['raw-body']);
1184 $author = Contact::getById($item['author-id'], ['network']);
1185 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1187 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1188 $item['body'] = BBCode::removeAttachment($item['body']);
1189 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1191 // Check for hashtags in the body and repair or add hashtag links
1192 $item['body'] = self::setHashtags($item['body']);
1194 $item['language'] = self::getLanguage($item);
1196 $notify_type = Delivery::POST;
1198 // Filling item related side tables
1199 if (!empty($item['attach'])) {
1200 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1203 if (empty($item['event-id'])) {
1204 unset($item['event-id']);
1206 $ev = Event::fromBBCode($item['body']);
1207 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1208 Logger::info('Event found.');
1209 $ev['cid'] = $item['contact-id'];
1210 $ev['uid'] = $item['uid'];
1211 $ev['uri'] = $item['uri'];
1212 $ev['edited'] = $item['edited'];
1213 $ev['private'] = $item['private'];
1214 $ev['guid'] = $item['guid'];
1215 $ev['plink'] = $item['plink'];
1216 $ev['network'] = $item['network'];
1217 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1218 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1219 $ev['source'] = $item['source'] ?? '';
1221 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1222 if (DBA::isResult($event)) {
1223 $ev['id'] = $event['id'];
1226 $event_id = Event::store($ev);
1227 $item = Event::getItemArrayForImportedId($event_id, $item);
1229 Logger::info('Event was stored', ['id' => $event_id]);
1233 if (empty($item['causer-id'])) {
1234 unset($item['causer-id']);
1237 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1238 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1239 if (!empty($content_warning) && empty($item['content-warning'])) {
1240 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1244 Post::insert($item['uri-id'], $item);
1246 if ($item['gravity'] == self::GRAVITY_PARENT) {
1247 Post\Thread::insert($item['uri-id'], $item);
1250 // The content of activities normally doesn't matter - except for likes from Misskey
1251 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1252 Post\Content::insert($item['uri-id'], $item);
1255 $item['parent'] = $parent_id;
1257 // Create Diaspora signature
1258 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1259 $signed = Diaspora::createCommentSignature($item);
1260 if (!empty($signed)) {
1261 $item['diaspora_signed_text'] = json_encode($signed);
1265 if (!empty($item['diaspora_signed_text'])) {
1266 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1269 // Attached file links
1270 if (!empty($item['file'])) {
1271 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1274 // Delivery relevant data
1275 $delivery_data = Post\DeliveryData::extractFields($item);
1277 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1278 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1281 // Store tags from the body if this hadn't been handled previously in the protocol classes
1282 if (!Tag::existsForPost($item['uri-id'])) {
1283 Tag::storeFromBody($item['uri-id'], $item['body']);
1286 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1287 if (Post::exists($condition)) {
1288 Logger::notice('Item is already inserted - aborting', $condition);
1292 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1293 if (!$post_user_id) {
1294 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1298 if ($item['gravity'] == self::GRAVITY_PARENT) {
1299 $item['post-user-id'] = $post_user_id;
1300 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1303 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1305 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1306 if (!DBA::isResult($posted_item)) {
1307 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1308 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1309 self::spool($orig_item);
1313 // update the commented timestamp on the parent
1314 if (DI::config()->get('system', 'like_no_comment')) {
1315 // Update when it is a comment
1316 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1318 // Update when it isn't a follow or tag verb
1319 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1322 if ($update_commented) {
1323 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1325 $fields = ['changed' => DateTimeFormat::utcNow()];
1328 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1330 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1331 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1332 // Get the user information for the logging
1333 $user = User::getById($uid);
1335 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1340 DI::contentItem()->postProcessPost($posted_item);
1342 Hook::callAll('post_remote_end', $posted_item);
1345 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1346 self::addShadow($post_user_id);
1348 self::addShadowPost($post_user_id);
1351 self::updateContact($posted_item);
1353 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1355 // Distribute items to users who subscribed to their tags
1356 self::distributeByTags($posted_item);
1358 // Automatically reshare the item if the "remote_self" option is selected
1359 self::autoReshare($posted_item);
1361 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1364 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1365 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1368 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1369 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1372 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1373 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1377 // Don't relay participation messages
1378 if (($posted_item['verb'] == Activity::FOLLOW) &&
1379 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1381 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1386 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1387 Post\Activity::insert($item['uri-id'], $source);
1391 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1394 // Fill the cache with the rendered content.
1395 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1396 self::updateDisplayCache($posted_item['uri-id']);
1399 return $post_user_id;
1403 * Fetch the post reason for a given item array
1405 * @param array $item
1409 public static function getPostReason(array $item): int
1411 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1412 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1413 return self::PR_FOLLOWER;
1416 if (!empty($item['origin']) && empty($item['post-reason'])) {
1417 return self::PR_LOCAL;
1420 return $item['post-reason'] ?? self::PR_NONE;
1424 * Update the display cache
1426 * @param integer $uri_id
1428 * @throws InternalServerErrorException
1429 * @throws \ImagickException
1431 public static function updateDisplayCache(int $uri_id)
1433 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1438 self::prepareBody($item, false, false, true);
1442 * Change the owner of a parent item if it had been shared by a group
1444 * (public) group posts in the new format consist of the regular post by the author
1445 * followed by an announce message sent from the group account.
1446 * Changing the owner helps in grouping group posts.
1448 * @param array $item
1451 private static function setOwnerforResharedItem(array $item)
1453 $parent = Post::selectFirst(
1454 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1455 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1457 if (!DBA::isResult($parent)) {
1458 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1462 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1463 if (!DBA::isResult($author)) {
1464 Logger::error('Author not found', ['id' => $item['author-id']]);
1468 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1469 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1471 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1472 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1473 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1477 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1478 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1479 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']]);
1483 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1484 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1489 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1490 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1494 * Distribute the given item to users who subscribed to their tags
1496 * @param array $item Processed item
1498 private static function distributeByTags(array $item)
1500 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1504 $uids = Tag::getUIDListByURIId($item['uri-id']);
1505 foreach ($uids as $uid) {
1506 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1507 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1512 * Distributes public items to the receivers
1514 * @param integer $itemid Item ID that should be added
1515 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1516 * @throws \Exception
1518 public static function distribute(int $itemid, string $signed_text = '')
1520 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1521 $parent = Post::selectFirst(['owner-id'], $condition);
1522 if (!DBA::isResult($parent)) {
1523 Logger::warning('Item not found', ['condition' => $condition]);
1527 // Only distribute public items from native networks
1529 'id' => $itemid, 'uid' => 0,
1530 'network' => array_merge(Protocol::FEDERATED, ['']),
1531 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1533 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1534 if (!DBA::isResult($item)) {
1535 Logger::warning('Item not found', ['condition' => $condition]);
1539 $origin = $item['origin'];
1543 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1544 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1545 if (!DBA::isResult($owner)) {
1549 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1550 $contacts = DBA::select('contact', ['uid'], $condition);
1551 while ($contact = DBA::fetch($contacts)) {
1552 if ($contact['uid'] == 0) {
1556 $users[$contact['uid']] = $contact['uid'];
1558 DBA::close($contacts);
1560 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1561 $contacts = DBA::select('contact', ['uid'], $condition);
1562 while ($contact = DBA::fetch($contacts)) {
1563 if ($contact['uid'] == 0) {
1567 $users[$contact['uid']] = $contact['uid'];
1569 DBA::close($contacts);
1571 if (!empty($owner['alias'])) {
1572 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1573 $contacts = DBA::select('contact', ['uid'], $condition);
1574 while ($contact = DBA::fetch($contacts)) {
1575 if ($contact['uid'] == 0) {
1579 $users[$contact['uid']] = $contact['uid'];
1581 DBA::close($contacts);
1586 if ($item['uri-id'] != $item['parent-uri-id']) {
1587 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1588 while ($parent = Post::fetch($parents)) {
1589 $users[$parent['uid']] = $parent['uid'];
1590 if ($parent['origin'] && !$origin) {
1591 $origin_uid = $parent['uid'];
1594 DBA::close($parents);
1597 foreach ($users as $uid) {
1598 if ($origin_uid == $uid) {
1599 $item['diaspora_signed_text'] = $signed_text;
1601 $item['post-reason'] = self::PR_DISTRIBUTE;
1602 self::storeForUser($item, $uid);
1607 * Store a public item defined by their URI-ID for the given users
1609 * @param integer $uri_id URI-ID of the given item
1610 * @param integer $uid The user that will receive the item entry
1611 * @param array $fields Additional fields to be stored
1612 * @param integer $source_uid User id of the source post
1613 * @return integer stored item id
1615 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1617 if ($uid == $source_uid) {
1618 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1622 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1623 if (!DBA::isResult($item)) {
1624 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1628 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1629 $owner = User::getOwnerDataById($uid);
1630 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1631 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1636 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1637 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']]);
1641 $item['post-reason'] = self::PR_STORED;
1643 $item = array_merge($item, $fields);
1645 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1646 $item['post-reason'] = self::PR_FOLLOWER;
1649 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1651 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1652 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1653 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1655 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id, 'post-reason' => $item['post-reason']]);
1659 $causer = $item['causer-id'] ?: $item['author-id'];
1661 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1662 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1663 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1666 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1667 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1668 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1669 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1672 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1675 $stored = self::storeForUser($item, $uid);
1676 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1681 * Fetch the parent with the given uri-id
1683 * @param integer $uri_id
1684 * @param integer $uid
1685 * @param integer $causer
1689 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1691 // Fetch the origin user for the post
1692 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1693 if (is_null($origin_uid)) {
1694 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1698 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1702 * Returns the origin uid of a post if the given user is allowed to see it.
1708 private static function GetOriginUidForUriId(int $uriid, int $uid)
1710 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1714 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1715 if (!empty($post)) {
1716 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1717 return $post['uid'];
1720 $pcid = Contact::getPublicIdByUserId($uid);
1725 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1726 if ($receiver == $pcid) {
1727 return $post['uid'];
1734 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1738 // When the post belongs to a a group then all group users are allowed to access it
1739 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1740 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1741 $target_uid = User::getIdForURL($tag['url']);
1742 if (!empty($target_uid)) {
1752 * Store a public item array for the given users
1754 * @param array $item The item entry that will be stored
1755 * @param integer $uid The user that will receive the item entry
1756 * @return integer stored item id
1757 * @throws \Exception
1759 private static function storeForUser(array $item, int $uid): int
1761 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1762 if (!empty($post['id'])) {
1763 if (!empty($item['event-id'])) {
1764 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1765 if (!empty($event_post['event-id'])) {
1766 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1767 if (!empty($event)) {
1768 // We aren't using "Event::store" here, since we don't want to trigger any further action
1769 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1770 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1774 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1778 // Data from the "post-user" table
1780 unset($item['mention']);
1781 unset($item['starred']);
1782 unset($item['unseen']);
1783 unset($item['psid']);
1784 unset($item['pinned']);
1785 unset($item['ignored']);
1786 unset($item['pubmail']);
1787 unset($item['event-id']);
1788 unset($item['hidden']);
1789 unset($item['notification-type']);
1791 // Data from the "post-delivery-data" table
1792 unset($item['postopts']);
1793 unset($item['inform']);
1795 $item['uid'] = $uid;
1796 $item['origin'] = 0;
1800 if ($item['gravity'] == self::GRAVITY_PARENT) {
1801 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1802 if (DBA::isResult($contact)) {
1803 $notify = self::isRemoteSelf($contact, $item);
1804 $item['wall'] = (bool)$notify;
1808 $item['contact-id'] = self::contactId($item);
1809 $distributed = self::insert($item, $notify);
1811 if (!$distributed) {
1812 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1814 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1816 return $distributed;
1820 * Add a shadow entry for a given item id that is a thread starter
1822 * We store every public item entry additionally with the user id "0".
1823 * This is used for the community page and for the search.
1824 * It is planned that in the future we will store public item entries only once.
1826 * @param integer $itemid Item ID that should be added
1827 * @throws \Exception
1829 private static function addShadow(int $itemid)
1831 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1832 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1833 $item = Post::selectFirst($fields, $condition);
1835 if (!DBA::isResult($item)) {
1839 // is it already a copy?
1840 if (($itemid == 0) || ($item['uid'] == 0)) {
1844 // Is it a visible public post?
1845 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1849 // is it an entry from a connector? Only add an entry for natively connected networks
1850 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1854 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1858 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1860 if (DBA::isResult($item)) {
1861 // Preparing public shadow (removing user specific data)
1864 unset($item['parent']);
1865 unset($item['wall']);
1866 unset($item['mention']);
1867 unset($item['origin']);
1868 unset($item['starred']);
1869 unset($item['postopts']);
1870 unset($item['inform']);
1871 unset($item['post-reason']);
1872 if ($item['uri-id'] == $item['parent-uri-id']) {
1873 $item['contact-id'] = $item['owner-id'];
1875 $item['contact-id'] = $item['author-id'];
1878 $public_shadow = self::insert($item);
1880 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1885 * Add a shadow entry for a given item id that is a comment
1887 * This function does the same like the function above - but for comments
1889 * @param integer $itemid Item ID that should be added
1890 * @throws \Exception
1892 private static function addShadowPost(int $itemid)
1894 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1895 if (!DBA::isResult($item)) {
1899 // Is it a toplevel post?
1900 if ($item['gravity'] == self::GRAVITY_PARENT) {
1901 self::addShadow($itemid);
1905 // Is this a shadow entry?
1906 if ($item['uid'] == 0) {
1910 // Is there a shadow parent?
1911 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1915 // Is there already a shadow entry?
1916 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1920 // Save "origin" and "parent" state
1921 $origin = $item['origin'];
1922 $parent = $item['parent'];
1924 // Preparing public shadow (removing user specific data)
1927 unset($item['parent']);
1928 unset($item['wall']);
1929 unset($item['mention']);
1930 unset($item['origin']);
1931 unset($item['starred']);
1932 unset($item['postopts']);
1933 unset($item['inform']);
1934 unset($item['post-reason']);
1935 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1937 $public_shadow = self::insert($item);
1939 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1941 // If this was a comment to a Diaspora post we don't get our comment back.
1942 // This means that we have to distribute the comment by ourselves.
1943 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1944 self::distribute($public_shadow);
1949 * Adds a language specification in a "language" element of given $arr.
1950 * Expects "body" element to exist in $arr.
1952 * @param array $item
1953 * @return string detected language
1954 * @throws \Text_LanguageDetect_Exception
1956 private static function getLanguage(array $item): string
1958 if (!empty($item['language'])) {
1959 return $item['language'];
1962 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1966 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1967 if (empty($languages)) {
1971 return json_encode($languages);
1975 * Get a language array from a given text
1977 * @param string $body
1978 * @param integer $count
1981 public static function getLanguageArray(string $body, int $count): array
1983 // Convert attachments to links
1984 $naked_body = BBCode::removeAttachment($body);
1985 if (empty($naked_body)) {
1989 // Remove links and pictures
1990 $naked_body = BBCode::removeLinks($naked_body);
1992 // Convert the title and the body to plain text
1993 $naked_body = BBCode::toPlaintext($naked_body);
1995 // Remove possibly remaining links
1996 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1998 if (empty($naked_body)) {
2002 $naked_body = self::getDominantLanguage($naked_body);
2004 $availableLanguages = DI::l10n()->getAvailableLanguages();
2005 // See https://github.com/friendica/friendica/issues/10511
2006 // Persian is manually added to language detection until a persian translation is provided for the interface, at
2007 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
2008 $availableLanguages['fa'] = 'fa';
2010 $ld = new Language(array_keys($availableLanguages));
2011 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
2015 * Check if latin or non latin are dominant in the body and only return the dominant one
2017 * @param string $body
2020 private static function getDominantLanguage(string $body): string
2024 for ($i = 0; $i < mb_strlen($body); $i++) {
2025 $character = mb_substr($body, $i, 1);
2026 $ord = mb_ord($character);
2028 // We add the most common characters to both strings.
2029 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2030 $latin .= $character;
2031 $non_latin .= $character;
2032 } elseif ($ord < 768) {
2033 $latin .= $character;
2035 $non_latin .= $character;
2038 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2041 public static function getLanguageMessage(array $item): string
2043 $iso639 = new \Matriphe\ISO639\ISO639;
2045 $used_languages = '';
2046 foreach (json_decode($item['language'], true) as $language => $reliability) {
2047 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2049 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2050 return $used_languages;
2054 * Creates an unique guid out of a given uri.
2055 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2056 * Posts that are created on this system are using System::createUUID.
2057 * Received ActivityPub posts are using Processor::getGUIDByURL.
2059 * @param string $uri uri of an item entry
2060 * @param string|null $host hostname for the GUID prefix
2061 * @return string Unique guid
2062 * @throws \Exception
2064 public static function guidFromUri(string $uri, string $host = null): string
2066 // Our regular guid routine is using this kind of prefix as well
2067 // We have to avoid that different routines could accidentally create the same value
2068 $parsed = parse_url($uri);
2070 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2071 unset($parsed['scheme']);
2073 $hostPart = $host ?: $parsed['host'] ?? '';
2075 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2078 // Glue it together to be able to make a hash from it
2079 if (!empty($parsed)) {
2080 $host_id = implode('/', $parsed);
2085 // Use a mixture of several hashes to provide some GUID like experience
2086 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2090 * generate an unique URI
2092 * @param string $guid An existing GUID (Otherwise it will be generated)
2095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2097 public static function newURI(string $guid = ''): string
2100 $guid = System::createUUID();
2103 return DI::baseUrl() . '/objects/' . $guid;
2107 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2109 * This can be used to filter for inactive contacts.
2110 * Only do this for public postings to avoid privacy problems, since poco data is public.
2111 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2113 * @param array $arr Contains the just posted item record
2114 * @throws \Exception
2116 private static function updateContact(array $arr)
2118 // Unarchive the author
2119 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2120 if (DBA::isResult($contact)) {
2121 Contact::unmarkForArchival($contact);
2124 // Unarchive the contact if it's not our own contact
2125 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2126 if (DBA::isResult($contact)) {
2127 Contact::unmarkForArchival($contact);
2130 /// @todo On private posts we could obfuscate the date
2131 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2133 // Is it a group? Then we don't care about the rules from above
2134 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2135 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2141 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2142 // So we have to ensure to only update the last item when it had been our own post,
2143 // or it had been done by a "regular" contact.
2144 if (!empty($arr['wall'])) {
2145 $condition = ['id' => $arr['contact-id']];
2147 $condition = ['id' => $arr['contact-id'], 'self' => false];
2149 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2151 // Now do the same for the system wide contacts with uid=0
2152 if ($arr['private'] != self::PRIVATE) {
2154 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2155 ['id' => $arr['owner-id']]
2158 if ($arr['owner-id'] != $arr['author-id']) {
2160 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2161 ['id' => $arr['author-id']]
2167 public static function setHashtags(string $body): string
2169 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2170 $tags = BBCode::getTags($body);
2173 if (!count($tags)) {
2177 // This sorting is important when there are hashtags that are part of other hashtags
2178 // Otherwise there could be problems with hashtags like #test and #test2
2179 // Because of this we are sorting from the longest to the shortest tag.
2180 usort($tags, function ($a, $b) {
2181 return strlen($b) <=> strlen($a);
2184 $URLSearchString = "^\[\]";
2186 // All hashtags should point to the home server if "local_tags" is activated
2187 if (DI::config()->get('system', 'local_tags')) {
2188 $body = preg_replace(
2189 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2190 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2195 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2196 $body = preg_replace_callback(
2197 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2199 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2204 $body = preg_replace_callback(
2205 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2207 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2212 $body = preg_replace_callback(
2213 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2215 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2220 // Repair recursive urls
2221 $body = preg_replace(
2222 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2227 foreach ($tags as $tag) {
2228 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2232 $basetag = str_replace('_', ' ', substr($tag, 1));
2233 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2235 $body = str_replace($tag, $newtag, $body);
2238 // Convert back the masked hashtags
2239 $body = str_replace("#", "#", $body);
2248 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2251 * @param int $item_id
2252 * @return boolean true if item was deleted, else false
2253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2254 * @throws \ImagickException
2256 private static function tagDeliver(int $uid, int $item_id): bool
2258 $owner = User::getOwnerDataById($uid);
2259 if (!DBA::isResult($owner)) {
2260 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2264 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2265 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2269 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2270 if (!DBA::isResult($item)) {
2271 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2275 if ($item['gravity'] == self::GRAVITY_PARENT) {
2276 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2277 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2279 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2280 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2284 $arr = ['item' => $item, 'user' => $owner];
2286 Hook::callAll('tagged', $arr);
2288 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2289 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2291 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2296 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2298 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2300 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2303 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2305 self::performActivity($item['id'], 'announce', $uid);
2308 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2313 * Automatically reshare the item if the "remote_self" option is selected
2315 * @param array $item
2318 private static function autoReshare(array $item)
2320 if ($item['gravity'] != self::GRAVITY_PARENT) {
2324 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2325 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2329 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2330 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2334 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2338 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2342 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2344 self::performActivity($item['id'], 'announce', $item['uid']);
2347 public static function isRemoteSelf(array $contact, array &$datarray): bool
2349 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2353 // Prevent the forwarding of posts that are forwarded
2354 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2355 Logger::info('Already forwarded');
2359 // Prevent to forward already forwarded posts
2360 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2361 Logger::info('Already forwarded (second test)');
2365 // Only forward posts
2366 if ($datarray['verb'] != Activity::POST) {
2367 Logger::info('No post');
2371 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2372 Logger::info('Not public');
2376 $datarray2 = $datarray;
2377 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2379 $self = DBA::selectFirst(
2381 ['id', 'name', 'url', 'thumb'],
2382 ['uid' => $contact['uid'], 'self' => true]
2384 if (!DBA::isResult($self)) {
2385 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2389 $datarray['contact-id'] = $self['id'];
2391 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2392 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2393 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2395 unset($datarray['edited']);
2397 unset($datarray['network']);
2398 unset($datarray['owner-id']);
2399 unset($datarray['author-id']);
2401 if ($contact['network'] != Protocol::FEED) {
2402 $old_uri_id = $datarray['uri-id'] ?? 0;
2403 $datarray['guid'] = System::createUUID();
2404 unset($datarray['plink']);
2405 $datarray['uri'] = self::newURI($datarray['guid']);
2406 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2407 $datarray['extid'] = Protocol::DFRN;
2408 $urlpart = parse_url($datarray2['author-link']);
2409 $datarray['app'] = $urlpart['host'];
2410 if (!empty($old_uri_id)) {
2411 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2414 unset($datarray['parent-uri']);
2415 unset($datarray['thr-parent']);
2417 // Store the original post
2418 $result = self::insert($datarray2);
2419 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2421 $datarray['private'] = self::PUBLIC;
2422 $datarray['app'] = 'Feed';
2426 return (bool)$result;
2433 * @param array $item
2436 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2437 * @throws \ImagickException
2439 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2441 if (DI::config()->get('system', 'disable_embedded')) {
2445 Logger::info('check for photos');
2446 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2451 $img_start = strpos($orig_body, '[img');
2452 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2453 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2455 while (($img_st_close !== false) && ($img_len !== false)) {
2456 $img_st_close++; // make it point to AFTER the closing bracket
2457 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2459 Logger::info('found photo', ['image' => $image]);
2461 if (stristr($image, $site . '/photo/')) {
2462 // Only embed locally hosted photos
2464 $i = basename($image);
2465 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2466 $x = strpos($i, '-');
2469 $res = substr($i, $x + 1);
2470 $i = substr($i, 0, $x);
2471 $photo = Photo::getPhotoForUser($uid, $i, $res);
2472 if (DBA::isResult($photo)) {
2474 * Check to see if we should replace this photo link with an embedded image
2475 * 1. No need to do so if the photo is public
2476 * 2. If there's a contact-id provided, see if they're in the access list
2477 * for the photo. If so, embed it.
2478 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2479 * permissions, regardless of order but first check to see if they're an exact
2480 * match to save some processing overhead.
2482 if (self::hasPermissions($photo)) {
2484 $recips = self::enumeratePermissions($photo);
2485 if (in_array($cid, $recips)) {
2489 if (self::samePermissions($uid, $item, $photo)) {
2495 $photo_img = Photo::getImageForPhoto($photo);
2496 // If a custom width and height were specified, apply before embedding
2497 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2498 Logger::info('scaling photo');
2500 $width = intval($match[1]);
2501 $height = intval($match[2]);
2503 $photo_img->scaleDown(max($width, $height));
2506 $data = $photo_img->asString();
2507 $type = $photo_img->getType();
2509 Logger::info('replacing photo');
2510 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2511 Logger::debug('replaced', ['image' => $image]);
2517 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2518 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2519 if ($orig_body === false) {
2523 $img_start = strpos($orig_body, '[img');
2524 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2525 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2528 $new_body = $new_body . $orig_body;
2533 private static function hasPermissions(array $obj)
2535 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2536 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2539 // @TODO $uid is unused parameter
2540 private static function samePermissions($uid, array $obj1, array $obj2): bool
2542 // first part is easy. Check that these are exactly the same.
2543 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2544 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2545 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2546 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2551 // This is harder. Parse all the permissions and compare the resulting set.
2552 $recipients1 = self::enumeratePermissions($obj1);
2553 $recipients2 = self::enumeratePermissions($obj2);
2557 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2558 return ($recipients1 == $recipients2);
2562 * Returns an array of contact-ids that are allowed to see this object
2564 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2565 * @param bool $check_dead Prunes unavailable contacts from the result
2566 * @param bool $expand_followers Expand the list of followers
2568 * @throws \Exception
2570 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2572 $aclFormatter = DI::aclFormatter();
2574 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2575 $expand_followers = true;
2578 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2579 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2580 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2581 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2582 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2583 $deny = array_unique(array_merge($deny_people, $deny_circles));
2584 $recipients = array_diff($recipients, $deny);
2588 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2590 if (!$uid || ($days < 1)) {
2595 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2596 $uid, self::GRAVITY_PARENT
2600 * $expire_network_only = save your own wall posts
2601 * and just expire conversations started by others
2603 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2605 if ($expire_network_only) {
2606 $condition[0] .= " AND NOT `wall`";
2609 if ($network != "") {
2610 $condition[0] .= " AND `network` = ?";
2611 $condition[] = $network;
2614 $condition[0] .= " AND `received` < ?";
2615 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2617 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2619 if (!DBA::isResult($items)) {
2623 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2625 // Forcing expiring of items - but not notes and marked items
2627 $expire_items = true;
2630 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2631 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2632 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2636 $priority = DI::config()->get('system', 'expire-notify-priority');
2638 while ($item = Post::fetch($items)) {
2639 // don't expire filed items
2640 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2644 // Only expire posts, not photos and photo comments
2646 if (!$expire_photos && !empty($item['resource-id'])) {
2648 } elseif (!$expire_starred && intval($item['starred'])) {
2650 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2652 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2656 self::markForDeletionById($item['id'], $priority);
2661 Logger::notice('Expired', ['user' => $uid, 'days' => $days, 'network' => $network, 'force' => $force, 'expired' => $expired, 'expire items' => $expire_items, 'expire notes' => $expire_notes, 'expire starred' => $expire_starred, 'expire photos' => $expire_photos, 'condition' => $condition]);
2664 public static function firstPostDate(int $uid, bool $wall = false)
2666 $user = User::getById($uid, ['register_date']);
2672 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2673 $uid, $wall, $user['register_date']
2675 $params = ['order' => ['received' => false]];
2676 $thread = Post::selectFirstThread(['received'], $condition, $params);
2677 if (DBA::isResult($thread)) {
2678 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2685 * add/remove activity to an item
2687 * Toggle activities as like,dislike,attend of an item
2689 * @param int $item_id
2690 * @param string $verb
2691 * Activity verb. One of
2692 * like, unlike, dislike, undislike, attendyes, unattendyes,
2693 * attendno, unattendno, attendmaybe, unattendmaybe,
2694 * announce, unannounce
2696 * @param string $allow_cid
2697 * @param string $allow_gid
2698 * @param string $deny_cid
2699 * @param string $deny_gid
2701 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2702 * @throws \ImagickException
2703 * @hook 'post_local_end'
2705 * 'post_id' => ID of posted item
2707 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
2713 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2715 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2716 if (!DBA::isResult($item)) {
2717 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2721 $uri_id = $item['uri-id'];
2723 if (!in_array($item['uid'], [0, $uid])) {
2727 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2728 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2729 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2730 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2731 if (!DBA::isResult($item)) {
2732 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2738 // Retrieves the local post owner
2739 $owner = User::getOwnerDataById($uid);
2740 if (empty($owner)) {
2741 Logger::info('Empty owner for user', ['uid' => $uid]);
2745 // Retrieve the current logged in user's public contact
2746 $author_id = Contact::getPublicIdByUserId($uid);
2747 if (empty($author_id)) {
2748 Logger::info('Empty public contact');
2756 $activity = Activity::LIKE;
2760 $activity = Activity::DISLIKE;
2764 $activity = Activity::ATTEND;
2768 $activity = Activity::ATTENDNO;
2771 case 'unattendmaybe':
2772 $activity = Activity::ATTENDMAYBE;
2776 $activity = Activity::FOLLOW;
2780 $activity = Activity::ANNOUNCE;
2783 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2787 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2789 // Enable activity toggling instead of on/off
2790 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2792 // Look for an existing verb row
2793 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2794 if ($event_verb_flag) {
2795 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2797 // Translate to the index based activity index
2799 foreach ($verbs as $verb) {
2800 $vids[] = Verb::getID($verb);
2803 $vids = Verb::getID($activity);
2807 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2808 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
2810 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2812 if (DBA::isResult($like_item)) {
2814 * Truth table for existing activities
2816 * | Inputs || Outputs |
2817 * |----------------------------||-------------------|
2818 * | Mode | Event | Same verb || Delete? | Return? |
2819 * |--------|-------|-----------||---------|---------|
2820 * | create | Yes | Yes || No | Yes |
2821 * | create | Yes | No || Yes | No |
2822 * | create | No | Yes || No | Yes |
2823 * | create | No | No || N/A†|
2824 * | delete | Yes | Yes || Yes | N/A‡ |
2825 * | delete | Yes | No || No | N/A‡ |
2826 * | delete | No | Yes || Yes | N/A‡ |
2827 * | delete | No | No || N/A†|
2828 * |--------|-------|-----------||---------|---------|
2829 * | A | B | C || A xor C | !B or C |
2831 * †Can't happen: It's impossible to find an existing non-event activity without
2832 * the same verb because we are only looking for this single verb.
2834 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2836 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2837 self::markForDeletionById($like_item['id']);
2840 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2845 // No need to go further if we aren't creating anything
2846 if ($mode == 'delete') {
2850 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2853 'guid' => System::createUUID(),
2854 'uri' => self::newURI(),
2856 'contact-id' => $owner['id'],
2857 'wall' => $item['wall'],
2859 'network' => Protocol::DFRN,
2860 'protocol' => Conversation::PARCEL_DIRECT,
2861 'direction' => Conversation::PUSH,
2862 'gravity' => self::GRAVITY_ACTIVITY,
2863 'parent' => $item['id'],
2864 'thr-parent' => $item['uri'],
2865 'owner-id' => $author_id,
2866 'author-id' => $author_id,
2867 'body' => $activity,
2868 'verb' => $activity,
2869 'object-type' => $objtype,
2870 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2871 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2872 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2873 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2878 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2879 $signed = Diaspora::createLikeSignature($uid, $new_item);
2880 if (!empty($signed)) {
2881 $new_item['diaspora_signed_text'] = json_encode($signed);
2885 self::insert($new_item, true);
2887 // If the parent item isn't visible then set it to visible
2888 // @todo Check if this is still needed
2889 if (!$item['visible']) {
2890 self::update(['visible' => true], ['id' => $item['id']]);
2896 * Fetch the SQL condition for the given user id
2898 * @param integer $owner_id User ID for which the permissions should be fetched
2899 * @return array condition
2901 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2903 $local_user = DI::userSession()->getLocalUserId();
2904 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2906 // default permissions - anonymous user
2907 $condition = ["`private` != ?", self::PRIVATE];
2909 if ($local_user && ($local_user == $owner_id)) {
2910 // Profile owner - everything is visible
2912 } elseif ($remote_user) {
2913 // Authenticated visitor - fetch the matching permissionsets
2914 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2917 "(`private` != ? OR (`private` = ? AND `wall`
2918 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2919 self::PRIVATE, self::PRIVATE
2921 $condition = array_merge($condition, $permissionSets->column('id'));
2929 * Get a permission SQL string for the given user
2931 * @param int $owner_id
2932 * @param string $table
2935 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2937 $local_user = DI::userSession()->getLocalUserId();
2938 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2940 if (!empty($table)) {
2941 $table = DBA::quoteIdentifier($table) . '.';
2945 * Construct permissions
2947 * default permissions - anonymous user
2949 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2951 // Profile owner - everything is visible
2952 if ($local_user && ($local_user == $owner_id)) {
2954 } elseif ($remote_user) {
2956 * Authenticated visitor. Unless pre-verified,
2957 * check that the contact belongs to this $owner_id
2958 * and load the circles the visitor belongs to.
2959 * If pre-verified, the caller is expected to have already
2960 * done this and passed the circles into this function.
2962 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2965 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2970 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2977 * get translated item type
2979 * @param array $item
2980 * @param \Friendica\Core\L10n $l10n
2983 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2985 if (!empty($item['event-id'])) {
2986 return $l10n->t('event');
2987 } elseif (!empty($item['resource-id'])) {
2988 return $l10n->t('photo');
2989 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2990 return $l10n->t('activity');
2991 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2992 return $l10n->t('comment');
2995 return $l10n->t('post');
2999 * Sets the "rendered-html" field of the provided item
3001 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3003 * @param array $item
3005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3006 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3008 private static function putInCache(&$item)
3010 // Save original body to prevent addons to modify it
3011 $body = $item['body'];
3013 $rendered_hash = $item['rendered-hash'] ?? '';
3014 $rendered_html = $item['rendered-html'] ?? '';
3017 $rendered_hash == ''
3018 || $rendered_html == ''
3019 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3020 || DI::config()->get('system', 'ignore_cache')
3022 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3023 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3025 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3026 Hook::callAll('put_item_in_cache', $hook_data);
3027 $item['rendered-html'] = $hook_data['rendered-html'];
3028 $item['rendered-hash'] = $hook_data['rendered-hash'];
3031 // Update if the generated values differ from the existing ones
3032 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3035 'rendered-html' => $item['rendered-html'],
3036 'rendered-hash' => $item['rendered-hash']
3038 ['id' => $item['id']]
3043 $item['body'] = $body;
3047 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3048 * If attach is true, also add icons for item attachments.
3050 * @param array $item Record from item table
3051 * @param boolean $attach If true, add icons for item attachments as well
3052 * @param boolean $is_preview Whether this is a preview
3053 * @param boolean $only_cache Whether only cached HTML should be updated
3054 * @return string item body html
3055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3056 * @throws \ImagickException
3057 * @hook prepare_body_init item array before any work
3058 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3059 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3060 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3062 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3065 Hook::callAll('prepare_body_init', $item);
3068 // In order to provide theme developers more possibilities, event items
3069 // are treated differently.
3070 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3071 $ev = Event::getItemHTML($item);
3075 $tags = Tag::populateFromItem($item);
3077 $item['tags'] = $tags['tags'];
3078 $item['hashtags'] = $tags['hashtags'];
3079 $item['mentions'] = $tags['mentions'];
3082 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3083 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3084 $item['body'] = Post\Media::replaceImage($item['body']);
3087 $body = $item['body'];
3089 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3092 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3096 $quote_shared_links = [];
3098 $shared = DI::contentItem()->getSharedPost($item, $fields);
3099 if (!empty($shared['post'])) {
3100 $shared_item = $shared['post'];
3101 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3102 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3103 $quote_uri_id = $shared['post']['uri-id'];
3104 $shared_links[] = strtolower($shared['post']['uri']);
3105 $item['body'] = BBCode::removeSharedData($item['body']);
3106 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3107 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3108 if (!empty($media)) {
3109 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3110 if (empty($shared_item['uri-id'])) {
3111 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3112 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3113 $shared_links[] = strtolower($media[0]['url']);
3116 if (empty($shared_item['uri-id'])) {
3117 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3118 $shared_links[] = strtolower($media[0]['url']);
3121 if (!empty($shared_item['uri-id'])) {
3122 $data = BBCode::getAttachmentData($shared_item['body']);
3123 if (!empty($data['url'])) {
3124 $quote_shared_links[] = $data['url'];
3127 $quote_uri_id = $shared_item['uri-id'];
3132 if (!empty($quote_uri_id)) {
3133 if (isset($shared_item['plink'])) {
3134 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3136 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3140 if (!empty($shared_item['uri-id'])) {
3141 $shared_uri_id = $shared_item['uri-id'];
3142 $shared_links[] = strtolower($shared_item['plink']);
3143 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3144 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3145 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3146 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3147 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3150 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3151 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3153 self::putInCache($item);
3154 $item['body'] = $body;
3155 $s = $item["rendered-html"];
3161 // Compile eventual content filter reasons
3162 $filter_reasons = [];
3163 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3164 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3165 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3166 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3167 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3168 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3169 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3172 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3173 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3176 $item['attachments'] = $attachments;
3180 'filter_reasons' => $filter_reasons
3182 Hook::callAll('prepare_body_content_filter', $hook_data);
3183 $filter_reasons = $hook_data['filter_reasons'];
3190 'preview' => $is_preview,
3191 'filter_reasons' => $filter_reasons
3193 Hook::callAll('prepare_body', $hook_data);
3194 $s = $hook_data['html'];
3199 // Replace the blockquotes with quotes that are used in mails.
3200 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3201 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3205 if (!empty($shared_attachments)) {
3206 $s = self::addGallery($s, $shared_attachments, $item['uri-id']);
3207 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3208 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, $quote_shared_links);
3209 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3210 $body = BBCode::removeSharedData($body);
3213 $s = self::addGallery($s, $attachments, $item['uri-id']);
3214 $s = self::addVisualAttachments($attachments, $item, $s, false);
3215 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3216 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3217 $s = self::addQuestions($item, $s);
3220 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3221 $x = Map::byCoordinates(trim($item['coord']));
3223 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3227 // Replace friendica image url size with theme preference.
3228 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3229 $ps = $a->getThemeInfoValue('item_image_size');
3230 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3233 $s = HTML::applyContentFilter($s, $filter_reasons);
3235 $hook_data = ['item' => $item, 'html' => $s];
3236 Hook::callAll('prepare_body_final', $hook_data);
3237 return $hook_data['html'];
3241 * @param array $images
3243 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3245 private static function makeImageGrid(array $images): string
3247 // Image for first column (fc) and second column (sc)
3251 for ($i = 0; $i < count($images); $i++) {
3252 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3255 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3264 * Modify links to pictures to links for the "Fancybox" gallery
3267 * @param array $attachments
3268 * @param integer $uri_id
3271 private static function addGallery(string $s, array $attachments, int $uri_id): string
3273 foreach ($attachments['visual'] as $attachment) {
3274 if (empty($attachment['preview']) || ($attachment['type'] != Post\Media::IMAGE)) {
3277 $s = str_replace('<a href="' . $attachment['url'] . '"', '<a data-fancybox="' . $uri_id . '" href="' . $attachment['url'] . '"', $s);
3283 * Check if the body contains a link
3285 * @param string $body
3286 * @param string $url
3290 public static function containsLink(string $body, string $url, int $type = 0): bool
3292 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3293 $urlparts = parse_url($url);
3294 if (empty($urlparts)) {
3298 unset($urlparts['query']);
3299 unset($urlparts['fragment']);
3302 $url = (string)Uri::fromParts($urlparts);
3303 } catch (\InvalidArgumentException $e) {
3304 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3305 /* See https://github.com/friendica/friendica/issues/12113
3306 * Malformed URLs will result in a Fatal Error
3311 // Remove media links to only search in embedded content
3312 // @todo Check images for image link, audio for audio links, ...
3313 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3314 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3317 if (strpos($body, $url)) {
3321 foreach ([0, 1, 2] as $size) {
3323 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3324 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3334 * Replace visual attachments in the body
3336 * @param array $attachments
3337 * @param string $body
3338 * @return string modified body
3340 private static function replaceVisualAttachments(array $attachments, string $body): string
3342 DI::profiler()->startRecording('rendering');
3344 foreach ($attachments['visual'] as $attachment) {
3345 if (!empty($attachment['preview'])) {
3346 if (Network::isLocalLink($attachment['preview'])) {
3349 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3350 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3351 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3353 $body = str_replace($search, $replace, $body);
3354 } elseif ($attachment['filetype'] == 'image') {
3355 if (Network::isLocalLink($attachment['url'])) {
3358 $proxy = Post\Media::getUrlForId($attachment['id']);
3359 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3360 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3362 $body = str_replace($search, $replace, $body);
3365 DI::profiler()->stopRecording();
3370 * Add visual attachments to the content
3372 * @param array $attachments
3373 * @param array $item
3374 * @param string $content
3375 * @return string modified content
3377 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3379 DI::profiler()->startRecording('rendering');
3384 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3385 foreach ($attachments['visual'] as $attachment) {
3386 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3390 if ($attachment['filetype'] == 'image') {
3391 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3392 } elseif (!empty($attachment['preview'])) {
3393 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3398 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3402 if (($attachment['filetype'] == 'video')) {
3403 /// @todo Move the template to /content as well
3404 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3406 'id' => $attachment['id'],
3407 'src' => $attachment['url'],
3408 'name' => $attachment['name'] ?: $attachment['url'],
3409 'preview' => $preview_url,
3410 'mime' => $attachment['mimetype'],
3413 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3416 $trailing .= $media;
3418 } elseif ($attachment['filetype'] == 'audio') {
3419 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3421 'id' => $attachment['id'],
3422 'src' => $attachment['url'],
3423 'name' => $attachment['name'] ?: $attachment['url'],
3424 'mime' => $attachment['mimetype'],
3427 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3430 $trailing .= $media;
3432 } elseif ($attachment['filetype'] == 'image') {
3433 $src_url = Post\Media::getUrlForId($attachment['id']);
3434 if (self::containsLink($item['body'], $src_url)) {
3437 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment, 'uri_id' => $item['uri-id']];
3442 if (count($images) > 1) {
3443 $media = self::makeImageGrid($images);
3444 } elseif (count($images) == 1) {
3445 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3446 '$image' => $images[0],
3450 // On Diaspora posts the attached pictures are leading
3451 if ($item['network'] == Protocol::DIASPORA) {
3454 $trailing .= $media;
3458 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3459 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3461 if ($leading != '') {
3462 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3465 if ($trailing != '') {
3466 $content .= '<div class="body-attach">' . $trailing . '</div>';
3470 DI::profiler()->stopRecording();
3475 * Add link attachment to the content
3477 * @param array $attachments
3478 * @param string $body
3479 * @param string $content
3480 * @param bool $shared
3481 * @param array $ignore_links A list of URLs to ignore
3482 * @return string modified content
3484 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3486 DI::profiler()->startRecording('rendering');
3487 // Don't show a preview when there is a visual attachment (audio or video)
3488 $types = array_column($attachments['visual'], 'type');
3489 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3491 if (!empty($attachments['link'])) {
3492 foreach ($attachments['link'] as $link) {
3494 foreach ($ignore_links as $ignore_link) {
3495 if (Strings::compareLink($link['url'], $ignore_link)) {
3499 // @todo Judge between the links to use the one with most information
3500 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3501 (empty($attachment['name']) && !empty($link['name'])) ||
3502 (empty($attachment['description']) && !empty($link['description'])) ||
3503 (empty($attachment['preview']) && !empty($link['preview'])))) {
3504 $attachment = $link;
3509 if (!empty($attachment)) {
3512 'author_name' => $attachment['author-name'] ?? '',
3513 'author_url' => $attachment['author-url'] ?? '',
3514 'description' => $attachment['description'] ?? '',
3517 'provider_name' => $attachment['publisher-name'] ?? '',
3518 'provider_url' => $attachment['publisher-url'] ?? '',
3520 'title' => $attachment['name'] ?? '',
3522 'url' => $attachment['url']
3525 if ($preview && !empty($attachment['preview'])) {
3526 if ($attachment['preview-width'] >= 500) {
3527 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3529 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3533 if (!empty($data['description']) && !empty($content)) {
3534 similar_text($data['description'], $content, $percent);
3539 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3540 $data['description'] = '';
3543 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3544 $data['author_name'] = '';
3547 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3548 $data['author_url'] = '';
3550 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3551 $data = BBCode::getAttachmentData($match[1]);
3553 DI::profiler()->stopRecording();
3555 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3556 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3557 $parts = parse_url($data['url']);
3558 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3559 if (empty($data['provider_name'])) {
3560 $data['provider_name'] = $parts['host'];
3562 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3563 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3565 if (!empty($parts['port'])) {
3566 $data['provider_url'] .= ':' . $parts['port'];
3571 // @todo Use a template
3572 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3573 if ($preview_mode != BBCode::PREVIEW_NONE) {
3574 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3578 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3579 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3580 '$url' => $data['url'],
3581 '$title' => $data['title'],
3588 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3590 return $content . $rendered;
3597 * Add non visual attachments to the content
3599 * @param array $attachments
3600 * @param array $item
3601 * @param string $content
3602 * @return string modified content
3604 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3606 DI::profiler()->startRecording('rendering');
3608 foreach ($attachments['additional'] as $attachment) {
3609 if (strpos($item['body'], $attachment['url'])) {
3615 'id' => $item['author-id'],
3616 'network' => $item['author-network'],
3617 'url' => $item['author-link'],
3618 'alias' => $item['author-alias']
3620 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3622 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3624 if (!empty($attachment['size'])) {
3625 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3628 /// @todo Use a template
3629 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3630 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3633 if ($trailing != '') {
3634 $content .= '<div class="body-attach">' . $trailing . '</div>';
3637 DI::profiler()->stopRecording();
3641 private static function addQuestions(array $item, string $content): string
3643 DI::profiler()->startRecording('rendering');
3644 if (!empty($item['question-id'])) {
3646 'id' => $item['question-id'],
3647 'multiple' => $item['question-multiple'],
3648 'voters' => $item['question-voters'],
3649 'endtime' => $item['question-end-time']
3652 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3653 foreach ($options as $key => $option) {
3654 if ($question['voters'] > 0) {
3655 $percent = $option['replies'] / $question['voters'] * 100;
3656 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%3$d%%, %1$d vote)', '%2$s (%3$d%%, %1$d votes)', $option['replies'], $option['name'], round($percent, 1));
3658 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3662 if (!empty($question['voters']) && !empty($question['endtime'])) {
3663 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3664 } elseif (!empty($question['voters'])) {
3665 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3666 } elseif (!empty($question['endtime'])) {
3667 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3672 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3673 '$question' => $question,
3674 '$options' => $options,
3675 '$summary' => $summary,
3678 DI::profiler()->stopRecording();
3683 * get private link for item
3685 * @param array $item
3686 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3687 * @throws \Exception
3689 public static function getPlink(array $item)
3691 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3692 $plink = $item['plink'];
3693 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3694 $plink = $item['uri'];
3697 if (DI::userSession()->getLocalUserId()) {
3699 'href' => "display/" . $item['guid'],
3700 'orig' => "display/" . $item['guid'],
3701 'title' => DI::l10n()->t('View on separate page'),
3702 'orig_title' => DI::l10n()->t('View on separate page'),
3705 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3708 'id' => $item['author-id'],
3709 'network' => $item['author-network'],
3710 'url' => $item['author-link'],
3711 'alias' => $item['author-alias'],
3713 $plink = Contact::magicLinkByContact($author, $plink);
3716 if (!empty($plink)) {
3717 $ret['href'] = DI::baseUrl()->remove($plink);
3718 $ret['title'] = DI::l10n()->t('Link to source');
3720 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3724 'title' => DI::l10n()->t('Link to source'),
3725 'orig_title' => DI::l10n()->t('Link to source'),
3735 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3736 * This does not apply to posts that are sent only in parallel to a group.
3738 * @param int $uri_id
3740 * @return boolean "true" when it is a group post
3742 public static function isGroupPost(int $uri_id): bool
3744 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3748 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3749 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3750 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3751 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3759 * Search item id for given URI or plink
3761 * @param string $uri
3762 * @param integer $uid
3764 * @return integer item id
3766 public static function searchByLink(string $uri, int $uid = 0): int
3768 $ssl_uri = str_replace('http://', 'https://', $uri);
3769 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3771 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3772 if (DBA::isResult($item)) {
3776 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3777 if (DBA::isResult($item)) {
3785 * Return the URI for a link to the post
3787 * @param string $uri URI or link to post
3789 * @return string URI
3791 public static function getURIByLink(string $uri): string
3793 $ssl_uri = str_replace('http://', 'https://', $uri);
3794 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3796 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3797 if (DBA::isResult($item)) {
3798 return $item['uri'];
3801 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3802 if (DBA::isResult($item)) {
3803 return $item['uri'];
3810 * Fetches item for given URI or plink
3812 * @param string $uri
3813 * @param integer $uid
3815 * @return integer item id
3817 public static function fetchByLink(string $uri, int $uid = 0): int
3819 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3820 $item_id = self::searchByLink($uri, $uid);
3821 if (!empty($item_id)) {
3822 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3832 Hook::callAll('item_by_link', $hookData);
3834 if (isset($hookData['item_id'])) {
3835 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3838 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3841 $item_id = self::searchByLink($fetched_uri, $uid);
3843 $item_id = Diaspora::fetchByURL($uri);
3846 if (!empty($item_id)) {
3847 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3851 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3856 * Fetch the uri-id of a quote
3858 * @param string $body
3861 public static function getQuoteUriId(string $body, int $uid = 0): int
3863 $shared = BBCode::fetchShareAttributes($body);
3864 if (empty($shared['guid']) && empty($shared['message_id'])) {
3868 if (empty($shared['link']) && empty($shared['message_id'])) {
3869 Logger::notice('Invalid share block.', ['share' => $shared]);
3873 if (!empty($shared['guid'])) {
3874 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3875 if (!empty($shared_item['uri-id'])) {
3876 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3877 return $shared_item['uri-id'];
3881 if (!empty($shared['message_id'])) {
3882 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3883 if (!empty($shared_item['uri-id'])) {
3884 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3885 return $shared_item['uri-id'];
3889 if (!empty($shared['link'])) {
3890 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3891 if (!empty($shared_item['uri-id'])) {
3892 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3893 return $shared_item['uri-id'];
3897 $url = $shared['message_id'] ?: $shared['link'];
3898 $id = self::fetchByLink($url);
3900 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3904 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3905 if (!empty($shared_item['uri-id'])) {
3906 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3907 return $shared_item['uri-id'];
3910 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);