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-alias', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
98 'owner-id', 'owner-link', 'owner-alias', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
99 'causer-id', 'causer-link', 'causer-alias', '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']);
494 $user_contact_id = 0;
495 foreach (['group-link', 'causer-link', 'owner-link', 'author-link'] as $field) {
496 if (empty($item[$field])) {
499 if (!$user_contact_id && Contact::isSharingByURL($item[$field], $item['uid'], true)) {
500 $user_contact_id = Contact::getIdForURL($item[$field], $item['uid']);
501 } elseif (!$contact_id) {
502 $contact_id = Contact::getIdForURL($item[$field]);
506 if ($user_contact_id) {
507 return $user_contact_id;
510 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
511 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
512 if (!empty($cdata['user'])) {
513 return $cdata['user'];
521 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
522 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
527 * Write an item array into a spool file to be inserted later.
528 * This command is called whenever there are issues storing an item.
530 * @param array $item The item fields that are to be inserted
533 private static function spool(array $item)
535 // Now we store the data in the spool directory
536 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
537 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
539 $spoolpath = System::getSpoolPath();
540 if ($spoolpath != '') {
541 $spool = $spoolpath . '/' . $file;
543 file_put_contents($spool, json_encode($item));
544 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
549 * Check if the item array is a duplicate
551 * @param array $item Item record
552 * @return boolean is it a duplicate?
554 private static function isDuplicate(array $item): bool
556 // Checking if there is already an item with the same guid
557 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
558 if (Post::exists($condition)) {
559 Logger::notice('Found already existing item', $condition);
564 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
565 'network' => [$item['network'], Protocol::DFRN]
567 if (Post::exists($condition)) {
568 Logger::notice('duplicated item with the same uri found.', $condition);
572 // On Friendica and Diaspora the GUID is unique
573 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
574 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
575 if (Post::exists($condition)) {
576 Logger::notice('duplicated item with the same guid found.', $condition);
579 } elseif ($item['network'] == Protocol::OSTATUS) {
580 // Check for an existing post with the same content. There seems to be a problem with OStatus.
582 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
583 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
585 if (Post::exists($condition)) {
586 Logger::notice('duplicated item with the same body found.', $item);
592 * Check for already added items.
593 * There is a timing issue here that sometimes creates double postings.
594 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
596 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
597 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
605 * Check if the item array is valid
607 * @param array $item Item record
608 * @return boolean item is valid
610 public static function isValid(array $item): bool
612 // When there is no content then we don't post it
613 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
614 Logger::notice('No body, no title.');
618 if (!empty($item['uid'])) {
619 $owner = User::getOwnerDataById($item['uid'], false);
621 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
625 if ($owner['account_expired'] || $owner['account_removed']) {
626 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']]);
631 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
632 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
636 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
637 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
641 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
642 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
646 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
647 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
651 if ($item['verb'] == Activity::FOLLOW) {
652 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
653 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
654 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
659 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
660 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
662 if (Post::exists($condition)) {
663 // It happens that we receive multiple follow requests by the same author - we only store one.
664 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
673 * Check if the item array is too old
675 * @param array $item Item record
676 * @return boolean item is too old
678 public static function isTooOld(array $item): bool
680 // check for create date and expire time
681 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
683 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
684 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
685 $expire_interval = $user['expire'];
688 if (($expire_interval > 0) && !empty($item['created'])) {
689 $expire_date = time() - ($expire_interval * 86400);
690 $created_date = strtotime($item['created']);
691 if ($created_date < $expire_date) {
692 Logger::notice('Item created before expiration interval.', [
693 'created' => date('c', $created_date),
694 'expired' => date('c', $expire_date),
705 * Return the id of the given item array if it has been stored before
707 * @param array $item Item record
708 * @return integer Item id or zero on error
710 private static function getDuplicateID(array $item): int
712 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
714 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
717 Protocol::ACTIVITYPUB,
722 $existing = Post::selectFirst(['id', 'network'], $condition);
723 if (DBA::isResult($existing)) {
724 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
725 if ($item['uid'] != 0) {
726 Logger::notice('Item already existed for user', [
727 'uri-id' => $item['uri-id'],
728 'uid' => $item['uid'],
729 'network' => $item['network'],
730 'existing_id' => $existing['id'],
731 'existing_network' => $existing['network']
735 return $existing['id'];
742 * Fetch the uri-id of the parent for the given uri-id
744 * @param integer $uriid
747 public static function getParent(int $uriid): int
749 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
750 if (empty($thread_parent)) {
754 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
758 return self::getParent($thread_parent['thr-parent-id']);
762 * Fetch top-level parent data for the given item array
765 * @return array item array with parent data
768 private static function getTopLevelParent(array $item): array
771 'uid', 'uri', 'parent-uri', 'id', 'deleted',
772 'uri-id', 'parent-uri-id',
773 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
774 'wall', 'private', 'origin', 'author-id'
776 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
777 $params = ['order' => ['id' => false]];
778 $parent = Post::selectFirst($fields, $condition, $params);
780 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
781 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
782 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
783 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
786 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
787 $parent = Post::selectFirst($fields, $condition, $params);
791 if (!DBA::isResult($parent)) {
792 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)]);
796 if ($parent['uri-id'] == $parent['parent-uri-id']) {
801 'uri-id' => $parent['parent-uri-id'],
802 'parent-uri-id' => $parent['parent-uri-id'],
803 'uid' => $parent['uid']
805 $params = ['order' => ['id' => false]];
806 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
808 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
809 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
810 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
811 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
814 if (!DBA::isResult($toplevel_parent)) {
815 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
819 return $toplevel_parent;
823 * Get the gravity for the given item array
826 * @return integer gravity
828 private static function getGravity(array $item): int
830 $activity = DI::activity();
832 if (isset($item['gravity'])) {
833 return intval($item['gravity']);
834 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
835 return self::GRAVITY_PARENT;
836 } elseif ($activity->match($item['verb'], Activity::POST)) {
837 return self::GRAVITY_COMMENT;
838 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
839 return self::GRAVITY_ACTIVITY;
840 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
841 return self::GRAVITY_ACTIVITY;
844 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
845 return self::GRAVITY_UNKNOWN; // Should not happen
848 private static function prepareOriginPost(array $item): array
850 $item = DI::contentItem()->initializePost($item);
851 $item = DI::contentItem()->finalizePost($item);
857 * Inserts item record
859 * @param array $item Item array to be inserted
860 * @param int $notify Notification (type?)
861 * @param bool $post_local (???)
862 * @return int Zero means error, otherwise primary key (id) is being returned
864 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
868 $priority = Worker::PRIORITY_HIGH;
870 // If it is a posting where users should get notifications, then define it as wall posting
872 $item = self::prepareOriginPost($item);
874 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
878 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
881 $uid = intval($item['uid']);
883 $item['guid'] = self::guid($item, $notify);
884 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
887 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
889 // Backward compatibility: parent-uri used to be the direct parent uri.
890 // If it is provided without a thr-parent, it probably is the old behavior.
891 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
892 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
893 $item['parent-uri'] = $item['thr-parent'];
896 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
897 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
899 // Store conversation data
900 $source = $item['source'] ?? '';
901 unset($item['conversation-uri']);
902 unset($item['conversation-href']);
903 unset($item['source']);
906 * Do we already have this item?
907 * We have to check several networks since Friendica posts could be repeated
908 * via OStatus (maybe Diaspora as well)
910 $duplicate = self::getDuplicateID($item);
915 // Additional duplicate checks
916 /// @todo Check why the first duplication check returns the item number and the second a 0
917 if (self::isDuplicate($item)) {
921 if (!isset($item['post-type'])) {
922 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
925 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
927 $item['wall'] = intval($item['wall'] ?? 0);
928 $item['extid'] = trim($item['extid'] ?? '');
929 $item['author-name'] = trim($item['author-name'] ?? '');
930 $item['author-link'] = trim($item['author-link'] ?? '');
931 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
932 $item['owner-name'] = trim($item['owner-name'] ?? '');
933 $item['owner-link'] = trim($item['owner-link'] ?? '');
934 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
935 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
936 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
937 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
938 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
939 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
940 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
941 $item['location'] = trim($item['location'] ?? '');
942 $item['coord'] = trim($item['coord'] ?? '');
943 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
944 $item['deleted'] = 0;
945 $item['verb'] = trim($item['verb'] ?? '');
946 $item['object-type'] = trim($item['object-type'] ?? '');
947 $item['object'] = trim($item['object'] ?? '');
948 $item['target-type'] = trim($item['target-type'] ?? '');
949 $item['target'] = trim($item['target'] ?? '');
950 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
951 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
952 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
953 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
954 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
955 $item['private'] = intval($item['private'] ?? self::PUBLIC);
956 $item['body'] = trim($item['body'] ?? '');
957 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
958 $item['app'] = trim($item['app'] ?? '');
959 $item['origin'] = intval($item['origin'] ?? 0);
960 $item['postopts'] = trim($item['postopts'] ?? '');
961 $item['resource-id'] = trim($item['resource-id'] ?? '');
962 $item['event-id'] = intval($item['event-id'] ?? 0);
963 $item['inform'] = trim($item['inform'] ?? '');
964 $item['file'] = trim($item['file'] ?? '');
966 // Communities aren't working with the Diaspora protocol
967 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
968 $user = User::getById($uid, ['account-type']);
969 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
970 Logger::info('Community posts are not supported via Diaspora');
975 // Items cannot be stored before they happen ...
976 if ($item['created'] > DateTimeFormat::utcNow()) {
977 $item['created'] = DateTimeFormat::utcNow();
980 // We haven't invented time travel by now.
981 if ($item['edited'] > DateTimeFormat::utcNow()) {
982 $item['edited'] = DateTimeFormat::utcNow();
985 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
987 $item['gravity'] = self::getGravity($item);
990 'url' => $item['author-link'], 'name' => $item['author-name'],
991 'photo' => $item['author-avatar'], 'network' => $item['network']
993 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
996 'url' => $item['owner-link'], 'name' => $item['owner-name'],
997 'photo' => $item['owner-avatar'], 'network' => $item['network']
999 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1001 $item['post-reason'] = self::getPostReason($item);
1003 // Ensure that there is an avatar cache
1004 Contact::checkAvatarCache($item['author-id']);
1005 Contact::checkAvatarCache($item['owner-id']);
1007 $item['contact-id'] = self::contactId($item);
1010 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1011 empty($item['origin']) && self::isTooOld($item)
1013 Logger::info('Item is too old', ['item' => $item]);
1017 if (!self::isValid($item)) {
1021 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1022 $toplevel_parent = self::getTopLevelParent($item);
1023 if (empty($toplevel_parent)) {
1027 $parent_id = $toplevel_parent['id'];
1028 $item['parent-uri'] = $toplevel_parent['uri'];
1029 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1030 $item['deleted'] = $toplevel_parent['deleted'];
1031 $item['wall'] = $toplevel_parent['wall'];
1033 // Reshares have to keep their permissions to allow groups to work
1034 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1035 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1036 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1037 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1038 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1041 $parent_origin = $toplevel_parent['origin'];
1043 // Don't federate received participation messages
1044 if ($item['verb'] != Activity::FOLLOW) {
1045 $item['wall'] = $toplevel_parent['wall'];
1047 $item['wall'] = false;
1048 // Participations are technical messages, so they are set to "seen" automatically
1049 $item['unseen'] = false;
1053 * If the parent is private, force privacy for the entire conversation
1054 * This differs from the above settings as it subtly allows comments from
1055 * email correspondents to be private even if the overall thread is not.
1057 if (!$defined_permissions && $toplevel_parent['private']) {
1058 $item['private'] = $toplevel_parent['private'];
1061 // If its a post that originated here then tag the thread as "mention"
1062 if ($item['origin'] && $item['uid']) {
1063 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1064 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1067 // Update the contact relations
1068 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1071 $parent_origin = $item['origin'];
1073 if ($item['wall'] && empty($item['conversation'])) {
1074 $item['conversation'] = $item['parent-uri'] . '#context';
1078 if ($item['origin']) {
1079 if (Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])) {
1080 $item['object-type'] = Activity\ObjectType::IMAGE;
1083 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1086 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1087 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1089 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1090 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1093 // Is this item available in the global items (with uid=0)?
1094 if ($item['uid'] == 0) {
1095 $item['global'] = true;
1097 // Set the global flag on all items if this was a global item entry
1098 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1100 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1104 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1105 $item['private'] = self::PRIVATE;
1108 if ($notify && $post_local) {
1109 $item['edit'] = false;
1110 $item['parent'] = $parent_id;
1112 // Trigger automatic reactions for addons
1113 if (!isset($item['api_source'])) {
1114 $item['api_source'] = true;
1117 // We have to tell the hooks who we are - this really should be improved
1118 if (!DI::userSession()->getLocalUserId()) {
1119 $_SESSION['authenticated'] = true;
1120 $_SESSION['uid'] = $uid;
1121 $dummy_session = true;
1123 $dummy_session = false;
1126 Hook::callAll('post_local', $item);
1128 if ($dummy_session) {
1129 unset($_SESSION['authenticated']);
1130 unset($_SESSION['uid']);
1132 } elseif (!$notify) {
1133 Hook::callAll('post_remote', $item);
1136 if (!empty($item['cancel'])) {
1137 Logger::notice('post cancelled by addon.');
1141 if (empty($item['vid']) && !empty($item['verb'])) {
1142 $item['vid'] = Verb::getID($item['verb']);
1145 // Creates or assigns the permission set
1146 $item['psid'] = DI::permissionSet()->selectOrCreate(
1147 DI::permissionSetFactory()->createFromString(
1156 if (!empty($item['extid'])) {
1157 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1160 if ($item['verb'] == Activity::ANNOUNCE) {
1161 self::setOwnerforResharedItem($item);
1164 if (isset($item['attachments'])) {
1165 foreach ($item['attachments'] as $attachment) {
1166 $attachment['uri-id'] = $item['uri-id'];
1167 Post\Media::insert($attachment);
1169 unset($item['attachments']);
1172 if (empty($item['quote-uri-id'])) {
1173 $quote_id = self::getQuoteUriId($item['body']);
1174 if (!empty($quote_id)) {
1175 // This is one of these "should not happen" situations.
1176 // The protocol implementations should already have done this job.
1177 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1178 $item['quote-uri-id'] = $quote_id;
1182 if (!empty($item['quote-uri-id'])) {
1183 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1184 $item['body'] = BBCode::removeSharedData($item['body']);
1187 // Remove all media attachments from the body and store them in the post-media table
1188 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1189 $item['raw-body'] = self::setHashtags($item['raw-body']);
1191 $author = Contact::getById($item['author-id'], ['network']);
1192 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1194 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1195 $item['body'] = BBCode::removeAttachment($item['body']);
1196 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1198 // Check for hashtags in the body and repair or add hashtag links
1199 $item['body'] = self::setHashtags($item['body']);
1201 $item['language'] = self::getLanguage($item);
1203 $notify_type = Delivery::POST;
1205 // Filling item related side tables
1206 if (!empty($item['attach'])) {
1207 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1210 if (empty($item['event-id'])) {
1211 unset($item['event-id']);
1213 $ev = Event::fromBBCode($item['body']);
1214 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1215 Logger::info('Event found.');
1216 $ev['cid'] = $item['contact-id'];
1217 $ev['uid'] = $item['uid'];
1218 $ev['uri'] = $item['uri'];
1219 $ev['edited'] = $item['edited'];
1220 $ev['private'] = $item['private'];
1221 $ev['guid'] = $item['guid'];
1222 $ev['plink'] = $item['plink'];
1223 $ev['network'] = $item['network'];
1224 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1225 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1226 $ev['source'] = $item['source'] ?? '';
1228 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1229 if (DBA::isResult($event)) {
1230 $ev['id'] = $event['id'];
1233 $event_id = Event::store($ev);
1234 $item = Event::getItemArrayForImportedId($event_id, $item);
1236 Logger::info('Event was stored', ['id' => $event_id]);
1240 if (empty($item['causer-id'])) {
1241 unset($item['causer-id']);
1244 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1245 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1246 if (!empty($content_warning) && empty($item['content-warning'])) {
1247 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1251 Post::insert($item['uri-id'], $item);
1253 if ($item['gravity'] == self::GRAVITY_PARENT) {
1254 Post\Thread::insert($item['uri-id'], $item);
1257 // The content of activities normally doesn't matter - except for likes from Misskey
1258 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1259 Post\Content::insert($item['uri-id'], $item);
1262 $item['parent'] = $parent_id;
1264 // Create Diaspora signature
1265 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1266 $signed = Diaspora::createCommentSignature($item);
1267 if (!empty($signed)) {
1268 $item['diaspora_signed_text'] = json_encode($signed);
1272 if (!empty($item['diaspora_signed_text'])) {
1273 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1276 // Attached file links
1277 if (!empty($item['file'])) {
1278 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1281 // Delivery relevant data
1282 $delivery_data = Post\DeliveryData::extractFields($item);
1284 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1285 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1288 // Store tags from the body if this hadn't been handled previously in the protocol classes
1289 if (!Tag::existsForPost($item['uri-id'])) {
1290 Tag::storeFromBody($item['uri-id'], $item['body']);
1293 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1294 if (Post::exists($condition)) {
1295 Logger::notice('Item is already inserted - aborting', $condition);
1299 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1300 if (!$post_user_id) {
1301 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1305 if ($item['gravity'] == self::GRAVITY_PARENT) {
1306 $item['post-user-id'] = $post_user_id;
1307 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1310 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1312 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1313 if (!DBA::isResult($posted_item)) {
1314 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1315 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1316 self::spool($orig_item);
1320 // update the commented timestamp on the parent
1321 if (DI::config()->get('system', 'like_no_comment')) {
1322 // Update when it is a comment
1323 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1325 // Update when it isn't a follow or tag verb
1326 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1329 if ($update_commented) {
1330 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1332 $fields = ['changed' => DateTimeFormat::utcNow()];
1335 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1337 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1338 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1339 // Get the user information for the logging
1340 $user = User::getById($uid);
1342 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1347 DI::contentItem()->postProcessPost($posted_item);
1349 Hook::callAll('post_remote_end', $posted_item);
1352 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1353 self::addShadow($post_user_id);
1355 self::addShadowPost($post_user_id);
1358 self::updateContact($posted_item);
1360 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1362 // Distribute items to users who subscribed to their tags
1363 self::distributeByTags($posted_item);
1365 // Automatically reshare the item if the "remote_self" option is selected
1366 self::autoReshare($posted_item);
1368 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1371 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1372 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1375 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1376 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1379 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1380 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1384 // Don't relay participation messages
1385 if (($posted_item['verb'] == Activity::FOLLOW) &&
1386 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1388 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1393 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1394 Post\Activity::insert($item['uri-id'], $source);
1398 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1401 // Fill the cache with the rendered content.
1402 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1403 self::updateDisplayCache($posted_item['uri-id']);
1406 return $post_user_id;
1410 * Fetch the post reason for a given item array
1412 * @param array $item
1416 public static function getPostReason(array $item): int
1418 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1419 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1420 return self::PR_FOLLOWER;
1423 if (!empty($item['origin']) && empty($item['post-reason'])) {
1424 return self::PR_LOCAL;
1427 return $item['post-reason'] ?? self::PR_NONE;
1431 * Update the display cache
1433 * @param integer $uri_id
1435 * @throws InternalServerErrorException
1436 * @throws \ImagickException
1438 public static function updateDisplayCache(int $uri_id)
1440 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1445 self::prepareBody($item, false, false, true);
1449 * Change the owner of a parent item if it had been shared by a group
1451 * (public) group posts in the new format consist of the regular post by the author
1452 * followed by an announce message sent from the group account.
1453 * Changing the owner helps in grouping group posts.
1455 * @param array $item
1458 private static function setOwnerforResharedItem(array $item)
1460 $parent = Post::selectFirst(
1461 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1462 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1464 if (!DBA::isResult($parent)) {
1465 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1469 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1470 if (!DBA::isResult($author)) {
1471 Logger::error('Author not found', ['id' => $item['author-id']]);
1475 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1476 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1478 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1479 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1480 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1484 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1485 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1486 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']]);
1490 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1491 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1496 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1497 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1501 * Distribute the given item to users who subscribed to their tags
1503 * @param array $item Processed item
1505 private static function distributeByTags(array $item)
1507 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1511 $uids = Tag::getUIDListByURIId($item['uri-id']);
1512 foreach ($uids as $uid) {
1513 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1514 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1519 * Distributes public items to the receivers
1521 * @param integer $itemid Item ID that should be added
1522 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1523 * @throws \Exception
1525 public static function distribute(int $itemid, string $signed_text = '')
1527 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1528 $parent = Post::selectFirst(['owner-id'], $condition);
1529 if (!DBA::isResult($parent)) {
1530 Logger::warning('Item not found', ['condition' => $condition]);
1534 // Only distribute public items from native networks
1536 'id' => $itemid, 'uid' => 0,
1537 'network' => array_merge(Protocol::FEDERATED, ['']),
1538 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1540 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1541 if (!DBA::isResult($item)) {
1542 Logger::warning('Item not found', ['condition' => $condition]);
1546 $origin = $item['origin'];
1550 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1551 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1552 if (!DBA::isResult($owner)) {
1556 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1557 $contacts = DBA::select('contact', ['uid'], $condition);
1558 while ($contact = DBA::fetch($contacts)) {
1559 if ($contact['uid'] == 0) {
1563 $users[$contact['uid']] = $contact['uid'];
1565 DBA::close($contacts);
1567 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1568 $contacts = DBA::select('contact', ['uid'], $condition);
1569 while ($contact = DBA::fetch($contacts)) {
1570 if ($contact['uid'] == 0) {
1574 $users[$contact['uid']] = $contact['uid'];
1576 DBA::close($contacts);
1578 if (!empty($owner['alias'])) {
1579 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1580 $contacts = DBA::select('contact', ['uid'], $condition);
1581 while ($contact = DBA::fetch($contacts)) {
1582 if ($contact['uid'] == 0) {
1586 $users[$contact['uid']] = $contact['uid'];
1588 DBA::close($contacts);
1593 if ($item['uri-id'] != $item['parent-uri-id']) {
1594 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1595 while ($parent = Post::fetch($parents)) {
1596 $users[$parent['uid']] = $parent['uid'];
1597 if ($parent['origin'] && !$origin) {
1598 $origin_uid = $parent['uid'];
1601 DBA::close($parents);
1604 foreach ($users as $uid) {
1605 if ($origin_uid == $uid) {
1606 $item['diaspora_signed_text'] = $signed_text;
1608 $item['post-reason'] = self::PR_DISTRIBUTE;
1609 self::storeForUser($item, $uid);
1614 * Store a public item defined by their URI-ID for the given users
1616 * @param integer $uri_id URI-ID of the given item
1617 * @param integer $uid The user that will receive the item entry
1618 * @param array $fields Additional fields to be stored
1619 * @param integer $source_uid User id of the source post
1620 * @return integer stored item id
1622 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1624 if ($uid == $source_uid) {
1625 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1629 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1630 if (!DBA::isResult($item)) {
1631 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1635 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1636 $owner = User::getOwnerDataById($uid);
1637 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1638 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1643 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1644 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']]);
1648 $item['post-reason'] = self::PR_STORED;
1650 $item = array_merge($item, $fields);
1652 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1653 $item['post-reason'] = self::PR_FOLLOWER;
1656 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1658 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1659 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1660 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1662 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']]);
1666 $causer = $item['causer-id'] ?: $item['author-id'];
1668 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1669 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1670 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1673 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1674 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1675 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1676 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1679 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1682 $stored = self::storeForUser($item, $uid);
1683 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1688 * Fetch the parent with the given uri-id
1690 * @param integer $uri_id
1691 * @param integer $uid
1692 * @param integer $causer
1696 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1698 // Fetch the origin user for the post
1699 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1700 if (is_null($origin_uid)) {
1701 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1705 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1709 * Returns the origin uid of a post if the given user is allowed to see it.
1715 private static function GetOriginUidForUriId(int $uriid, int $uid)
1717 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1721 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1722 if (!empty($post)) {
1723 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1724 return $post['uid'];
1727 $pcid = Contact::getPublicIdByUserId($uid);
1732 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1733 if ($receiver == $pcid) {
1734 return $post['uid'];
1741 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1745 // When the post belongs to a a group then all group users are allowed to access it
1746 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1747 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1748 $target_uid = User::getIdForURL($tag['url']);
1749 if (!empty($target_uid)) {
1759 * Store a public item array for the given users
1761 * @param array $item The item entry that will be stored
1762 * @param integer $uid The user that will receive the item entry
1763 * @return integer stored item id
1764 * @throws \Exception
1766 private static function storeForUser(array $item, int $uid): int
1768 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1769 if (!empty($post['id'])) {
1770 if (!empty($item['event-id'])) {
1771 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1772 if (!empty($event_post['event-id'])) {
1773 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1774 if (!empty($event)) {
1775 // We aren't using "Event::store" here, since we don't want to trigger any further action
1776 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1777 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1781 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1785 // Data from the "post-user" table
1787 unset($item['mention']);
1788 unset($item['starred']);
1789 unset($item['unseen']);
1790 unset($item['psid']);
1791 unset($item['pinned']);
1792 unset($item['ignored']);
1793 unset($item['pubmail']);
1794 unset($item['event-id']);
1795 unset($item['hidden']);
1796 unset($item['notification-type']);
1798 // Data from the "post-delivery-data" table
1799 unset($item['postopts']);
1800 unset($item['inform']);
1802 $item['uid'] = $uid;
1803 $item['origin'] = 0;
1807 if ($item['gravity'] == self::GRAVITY_PARENT) {
1808 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1809 if (DBA::isResult($contact)) {
1810 $notify = self::isRemoteSelf($contact, $item);
1811 $item['wall'] = (bool)$notify;
1815 $item['contact-id'] = self::contactId($item);
1816 $distributed = self::insert($item, $notify);
1818 if (!$distributed) {
1819 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1821 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1823 return $distributed;
1827 * Add a shadow entry for a given item id that is a thread starter
1829 * We store every public item entry additionally with the user id "0".
1830 * This is used for the community page and for the search.
1831 * It is planned that in the future we will store public item entries only once.
1833 * @param integer $itemid Item ID that should be added
1834 * @throws \Exception
1836 private static function addShadow(int $itemid)
1838 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1839 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1840 $item = Post::selectFirst($fields, $condition);
1842 if (!DBA::isResult($item)) {
1846 // is it already a copy?
1847 if (($itemid == 0) || ($item['uid'] == 0)) {
1851 // Is it a visible public post?
1852 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1856 // is it an entry from a connector? Only add an entry for natively connected networks
1857 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1861 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1865 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1867 if (DBA::isResult($item)) {
1868 // Preparing public shadow (removing user specific data)
1871 unset($item['parent']);
1872 unset($item['wall']);
1873 unset($item['mention']);
1874 unset($item['origin']);
1875 unset($item['starred']);
1876 unset($item['postopts']);
1877 unset($item['inform']);
1878 unset($item['post-reason']);
1879 if ($item['uri-id'] == $item['parent-uri-id']) {
1880 $item['contact-id'] = $item['owner-id'];
1882 $item['contact-id'] = $item['author-id'];
1885 $public_shadow = self::insert($item);
1887 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1892 * Add a shadow entry for a given item id that is a comment
1894 * This function does the same like the function above - but for comments
1896 * @param integer $itemid Item ID that should be added
1897 * @throws \Exception
1899 private static function addShadowPost(int $itemid)
1901 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1902 if (!DBA::isResult($item)) {
1906 // Is it a toplevel post?
1907 if ($item['gravity'] == self::GRAVITY_PARENT) {
1908 self::addShadow($itemid);
1912 // Is this a shadow entry?
1913 if ($item['uid'] == 0) {
1917 // Is there a shadow parent?
1918 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1922 // Is there already a shadow entry?
1923 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1927 // Save "origin" and "parent" state
1928 $origin = $item['origin'];
1929 $parent = $item['parent'];
1931 // Preparing public shadow (removing user specific data)
1934 unset($item['parent']);
1935 unset($item['wall']);
1936 unset($item['mention']);
1937 unset($item['origin']);
1938 unset($item['starred']);
1939 unset($item['postopts']);
1940 unset($item['inform']);
1941 unset($item['post-reason']);
1942 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1944 $public_shadow = self::insert($item);
1946 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1948 // If this was a comment to a Diaspora post we don't get our comment back.
1949 // This means that we have to distribute the comment by ourselves.
1950 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1951 self::distribute($public_shadow);
1956 * Adds a language specification in a "language" element of given $arr.
1957 * Expects "body" element to exist in $arr.
1959 * @param array $item
1960 * @return string detected language
1961 * @throws \Text_LanguageDetect_Exception
1963 private static function getLanguage(array $item): string
1965 if (!empty($item['language'])) {
1966 return $item['language'];
1969 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1973 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1974 if (empty($languages)) {
1978 return json_encode($languages);
1982 * Get a language array from a given text
1984 * @param string $body
1985 * @param integer $count
1988 public static function getLanguageArray(string $body, int $count): array
1990 // Convert attachments to links
1991 $naked_body = BBCode::removeAttachment($body);
1992 if (empty($naked_body)) {
1996 // Remove links and pictures
1997 $naked_body = BBCode::removeLinks($naked_body);
1999 // Convert the title and the body to plain text
2000 $naked_body = BBCode::toPlaintext($naked_body);
2002 // Remove possibly remaining links
2003 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
2005 if (empty($naked_body)) {
2009 $naked_body = self::getDominantLanguage($naked_body);
2011 $availableLanguages = DI::l10n()->getAvailableLanguages();
2012 // See https://github.com/friendica/friendica/issues/10511
2013 // Persian is manually added to language detection until a persian translation is provided for the interface, at
2014 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
2015 $availableLanguages['fa'] = 'fa';
2017 $ld = new Language(array_keys($availableLanguages));
2018 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
2022 * Check if latin or non latin are dominant in the body and only return the dominant one
2024 * @param string $body
2027 private static function getDominantLanguage(string $body): string
2031 for ($i = 0; $i < mb_strlen($body); $i++) {
2032 $character = mb_substr($body, $i, 1);
2033 $ord = mb_ord($character);
2035 // We add the most common characters to both strings.
2036 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2037 $latin .= $character;
2038 $non_latin .= $character;
2039 } elseif ($ord < 768) {
2040 $latin .= $character;
2042 $non_latin .= $character;
2045 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2048 public static function getLanguageMessage(array $item): string
2050 $iso639 = new \Matriphe\ISO639\ISO639;
2052 $used_languages = '';
2053 foreach (json_decode($item['language'], true) as $language => $reliability) {
2054 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2056 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2057 return $used_languages;
2061 * Creates an unique guid out of a given uri.
2062 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2063 * Posts that are created on this system are using System::createUUID.
2064 * Received ActivityPub posts are using Processor::getGUIDByURL.
2066 * @param string $uri uri of an item entry
2067 * @param string|null $host hostname for the GUID prefix
2068 * @return string Unique guid
2069 * @throws \Exception
2071 public static function guidFromUri(string $uri, string $host = null): string
2073 // Our regular guid routine is using this kind of prefix as well
2074 // We have to avoid that different routines could accidentally create the same value
2075 $parsed = parse_url($uri);
2077 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2078 unset($parsed['scheme']);
2080 $hostPart = $host ?: $parsed['host'] ?? '';
2082 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2085 // Glue it together to be able to make a hash from it
2086 if (!empty($parsed)) {
2087 $host_id = implode('/', $parsed);
2092 // Use a mixture of several hashes to provide some GUID like experience
2093 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2097 * generate an unique URI
2099 * @param string $guid An existing GUID (Otherwise it will be generated)
2102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2104 public static function newURI(string $guid = ''): string
2107 $guid = System::createUUID();
2110 return DI::baseUrl() . '/objects/' . $guid;
2114 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2116 * This can be used to filter for inactive contacts.
2117 * Only do this for public postings to avoid privacy problems, since poco data is public.
2118 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2120 * @param array $arr Contains the just posted item record
2121 * @throws \Exception
2123 private static function updateContact(array $arr)
2125 // Unarchive the author
2126 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2127 if (DBA::isResult($contact)) {
2128 Contact::unmarkForArchival($contact);
2131 // Unarchive the contact if it's not our own contact
2132 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2133 if (DBA::isResult($contact)) {
2134 Contact::unmarkForArchival($contact);
2137 /// @todo On private posts we could obfuscate the date
2138 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2140 // Is it a group? Then we don't care about the rules from above
2141 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2142 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2148 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2149 // So we have to ensure to only update the last item when it had been our own post,
2150 // or it had been done by a "regular" contact.
2151 if (!empty($arr['wall'])) {
2152 $condition = ['id' => $arr['contact-id']];
2154 $condition = ['id' => $arr['contact-id'], 'self' => false];
2156 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2158 // Now do the same for the system wide contacts with uid=0
2159 if ($arr['private'] != self::PRIVATE) {
2161 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2162 ['id' => $arr['owner-id']]
2165 if ($arr['owner-id'] != $arr['author-id']) {
2167 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2168 ['id' => $arr['author-id']]
2174 public static function setHashtags(string $body): string
2176 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2177 $tags = BBCode::getTags($body);
2180 if (!count($tags)) {
2184 // This sorting is important when there are hashtags that are part of other hashtags
2185 // Otherwise there could be problems with hashtags like #test and #test2
2186 // Because of this we are sorting from the longest to the shortest tag.
2187 usort($tags, function ($a, $b) {
2188 return strlen($b) <=> strlen($a);
2191 $URLSearchString = "^\[\]";
2193 // All hashtags should point to the home server if "local_tags" is activated
2194 if (DI::config()->get('system', 'local_tags')) {
2195 $body = preg_replace(
2196 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2197 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2202 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2203 $body = preg_replace_callback(
2204 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2206 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2211 $body = preg_replace_callback(
2212 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2214 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2219 $body = preg_replace_callback(
2220 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2222 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2227 // Repair recursive urls
2228 $body = preg_replace(
2229 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2234 foreach ($tags as $tag) {
2235 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2239 $basetag = str_replace('_', ' ', substr($tag, 1));
2240 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2242 $body = str_replace($tag, $newtag, $body);
2245 // Convert back the masked hashtags
2246 $body = str_replace("#", "#", $body);
2255 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2258 * @param int $item_id
2259 * @return boolean true if item was deleted, else false
2260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2261 * @throws \ImagickException
2263 private static function tagDeliver(int $uid, int $item_id): bool
2265 $owner = User::getOwnerDataById($uid);
2266 if (!DBA::isResult($owner)) {
2267 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2271 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2272 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2276 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2277 if (!DBA::isResult($item)) {
2278 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2282 if ($item['gravity'] == self::GRAVITY_PARENT) {
2283 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2284 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2286 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2287 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2291 $arr = ['item' => $item, 'user' => $owner];
2293 Hook::callAll('tagged', $arr);
2295 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2296 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2298 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2303 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2305 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2307 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2310 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2312 self::performActivity($item['id'], 'announce', $uid);
2315 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2320 * Automatically reshare the item if the "remote_self" option is selected
2322 * @param array $item
2325 private static function autoReshare(array $item)
2327 if ($item['gravity'] != self::GRAVITY_PARENT) {
2331 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2332 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2336 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2337 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2341 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2345 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2349 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2351 self::performActivity($item['id'], 'announce', $item['uid']);
2354 public static function isRemoteSelf(array $contact, array &$datarray): bool
2356 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2360 // Prevent the forwarding of posts that are forwarded
2361 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2362 Logger::info('Already forwarded');
2366 // Prevent to forward already forwarded posts
2367 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2368 Logger::info('Already forwarded (second test)');
2372 // Only forward posts
2373 if ($datarray['verb'] != Activity::POST) {
2374 Logger::info('No post');
2378 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2379 Logger::info('Not public');
2383 $datarray2 = $datarray;
2384 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2386 $self = DBA::selectFirst(
2388 ['id', 'name', 'url', 'thumb'],
2389 ['uid' => $contact['uid'], 'self' => true]
2391 if (!DBA::isResult($self)) {
2392 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2396 $datarray['contact-id'] = $self['id'];
2398 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2399 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2400 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2402 unset($datarray['edited']);
2404 unset($datarray['network']);
2405 unset($datarray['owner-id']);
2406 unset($datarray['author-id']);
2408 if ($contact['network'] != Protocol::FEED) {
2409 $old_uri_id = $datarray['uri-id'] ?? 0;
2410 $datarray['guid'] = System::createUUID();
2411 unset($datarray['plink']);
2412 $datarray['uri'] = self::newURI($datarray['guid']);
2413 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2414 $datarray['extid'] = Protocol::DFRN;
2415 $urlpart = parse_url($datarray2['author-link']);
2416 $datarray['app'] = $urlpart['host'];
2417 if (!empty($old_uri_id)) {
2418 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2421 unset($datarray['parent-uri']);
2422 unset($datarray['thr-parent']);
2424 // Store the original post
2425 $result = self::insert($datarray2);
2426 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2428 $datarray['private'] = self::PUBLIC;
2429 $datarray['app'] = 'Feed';
2433 return (bool)$result;
2440 * @param array $item
2443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2444 * @throws \ImagickException
2446 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2448 if (DI::config()->get('system', 'disable_embedded')) {
2452 Logger::info('check for photos');
2453 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2458 $img_start = strpos($orig_body, '[img');
2459 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2460 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2462 while (($img_st_close !== false) && ($img_len !== false)) {
2463 $img_st_close++; // make it point to AFTER the closing bracket
2464 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2466 Logger::info('found photo', ['image' => $image]);
2468 if (stristr($image, $site . '/photo/')) {
2469 // Only embed locally hosted photos
2471 $i = basename($image);
2472 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2473 $x = strpos($i, '-');
2476 $res = substr($i, $x + 1);
2477 $i = substr($i, 0, $x);
2478 $photo = Photo::getPhotoForUser($uid, $i, $res);
2479 if (DBA::isResult($photo)) {
2481 * Check to see if we should replace this photo link with an embedded image
2482 * 1. No need to do so if the photo is public
2483 * 2. If there's a contact-id provided, see if they're in the access list
2484 * for the photo. If so, embed it.
2485 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2486 * permissions, regardless of order but first check to see if they're an exact
2487 * match to save some processing overhead.
2489 if (self::hasPermissions($photo)) {
2491 $recips = self::enumeratePermissions($photo);
2492 if (in_array($cid, $recips)) {
2496 if (self::samePermissions($uid, $item, $photo)) {
2502 $photo_img = Photo::getImageForPhoto($photo);
2503 // If a custom width and height were specified, apply before embedding
2504 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2505 Logger::info('scaling photo');
2507 $width = intval($match[1]);
2508 $height = intval($match[2]);
2510 $photo_img->scaleDown(max($width, $height));
2513 $data = $photo_img->asString();
2514 $type = $photo_img->getType();
2516 Logger::info('replacing photo');
2517 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2518 Logger::debug('replaced', ['image' => $image]);
2524 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2525 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2526 if ($orig_body === false) {
2530 $img_start = strpos($orig_body, '[img');
2531 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2532 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2535 $new_body = $new_body . $orig_body;
2540 private static function hasPermissions(array $obj)
2542 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2543 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2546 // @TODO $uid is unused parameter
2547 private static function samePermissions($uid, array $obj1, array $obj2): bool
2549 // first part is easy. Check that these are exactly the same.
2550 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2551 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2552 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2553 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2558 // This is harder. Parse all the permissions and compare the resulting set.
2559 $recipients1 = self::enumeratePermissions($obj1);
2560 $recipients2 = self::enumeratePermissions($obj2);
2564 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2565 return ($recipients1 == $recipients2);
2569 * Returns an array of contact-ids that are allowed to see this object
2571 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2572 * @param bool $check_dead Prunes unavailable contacts from the result
2573 * @param bool $expand_followers Expand the list of followers
2575 * @throws \Exception
2577 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2579 $aclFormatter = DI::aclFormatter();
2581 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2582 $expand_followers = true;
2585 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2586 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2587 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2588 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2589 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2590 $deny = array_unique(array_merge($deny_people, $deny_circles));
2591 $recipients = array_diff($recipients, $deny);
2595 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2597 if (!$uid || ($days < 1)) {
2602 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2603 $uid, self::GRAVITY_PARENT
2607 * $expire_network_only = save your own wall posts
2608 * and just expire conversations started by others
2610 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2612 if ($expire_network_only) {
2613 $condition[0] .= " AND NOT `wall`";
2616 if ($network != "") {
2617 $condition[0] .= " AND `network` = ?";
2618 $condition[] = $network;
2621 $condition[0] .= " AND `received` < ?";
2622 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2624 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2626 if (!DBA::isResult($items)) {
2630 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2632 // Forcing expiring of items - but not notes and marked items
2634 $expire_items = true;
2637 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2638 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2639 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2643 $priority = DI::config()->get('system', 'expire-notify-priority');
2645 while ($item = Post::fetch($items)) {
2646 // don't expire filed items
2647 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2651 // Only expire posts, not photos and photo comments
2653 if (!$expire_photos && !empty($item['resource-id'])) {
2655 } elseif (!$expire_starred && intval($item['starred'])) {
2657 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2659 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2663 self::markForDeletionById($item['id'], $priority);
2668 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]);
2671 public static function firstPostDate(int $uid, bool $wall = false)
2673 $user = User::getById($uid, ['register_date']);
2679 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2680 $uid, $wall, $user['register_date']
2682 $params = ['order' => ['received' => false]];
2683 $thread = Post::selectFirstThread(['received'], $condition, $params);
2684 if (DBA::isResult($thread)) {
2685 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2692 * add/remove activity to an item
2694 * Toggle activities as like,dislike,attend of an item
2696 * @param int $item_id
2697 * @param string $verb
2698 * Activity verb. One of
2699 * like, unlike, dislike, undislike, attendyes, unattendyes,
2700 * attendno, unattendno, attendmaybe, unattendmaybe,
2701 * announce, unannounce
2703 * @param string $allow_cid
2704 * @param string $allow_gid
2705 * @param string $deny_cid
2706 * @param string $deny_gid
2708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2709 * @throws \ImagickException
2710 * @hook 'post_local_end'
2712 * 'post_id' => ID of posted item
2714 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
2720 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2722 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2723 if (!DBA::isResult($item)) {
2724 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2728 $uri_id = $item['uri-id'];
2730 if (!in_array($item['uid'], [0, $uid])) {
2734 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2735 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2736 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2737 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2738 if (!DBA::isResult($item)) {
2739 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2745 // Retrieves the local post owner
2746 $owner = User::getOwnerDataById($uid);
2747 if (empty($owner)) {
2748 Logger::info('Empty owner for user', ['uid' => $uid]);
2752 // Retrieve the current logged in user's public contact
2753 $author_id = Contact::getPublicIdByUserId($uid);
2754 if (empty($author_id)) {
2755 Logger::info('Empty public contact');
2763 $activity = Activity::LIKE;
2767 $activity = Activity::DISLIKE;
2771 $activity = Activity::ATTEND;
2775 $activity = Activity::ATTENDNO;
2778 case 'unattendmaybe':
2779 $activity = Activity::ATTENDMAYBE;
2783 $activity = Activity::FOLLOW;
2787 $activity = Activity::ANNOUNCE;
2790 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2794 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2796 // Enable activity toggling instead of on/off
2797 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2799 // Look for an existing verb row
2800 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2801 if ($event_verb_flag) {
2802 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2804 // Translate to the index based activity index
2806 foreach ($verbs as $verb) {
2807 $vids[] = Verb::getID($verb);
2810 $vids = Verb::getID($activity);
2814 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2815 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
2817 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2819 if (DBA::isResult($like_item)) {
2821 * Truth table for existing activities
2823 * | Inputs || Outputs |
2824 * |----------------------------||-------------------|
2825 * | Mode | Event | Same verb || Delete? | Return? |
2826 * |--------|-------|-----------||---------|---------|
2827 * | create | Yes | Yes || No | Yes |
2828 * | create | Yes | No || Yes | No |
2829 * | create | No | Yes || No | Yes |
2830 * | create | No | No || N/A†|
2831 * | delete | Yes | Yes || Yes | N/A‡ |
2832 * | delete | Yes | No || No | N/A‡ |
2833 * | delete | No | Yes || Yes | N/A‡ |
2834 * | delete | No | No || N/A†|
2835 * |--------|-------|-----------||---------|---------|
2836 * | A | B | C || A xor C | !B or C |
2838 * †Can't happen: It's impossible to find an existing non-event activity without
2839 * the same verb because we are only looking for this single verb.
2841 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2843 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2844 self::markForDeletionById($like_item['id']);
2847 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2852 // No need to go further if we aren't creating anything
2853 if ($mode == 'delete') {
2857 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2860 'guid' => System::createUUID(),
2861 'uri' => self::newURI(),
2863 'contact-id' => $owner['id'],
2864 'wall' => $item['wall'],
2866 'network' => Protocol::DFRN,
2867 'protocol' => Conversation::PARCEL_DIRECT,
2868 'direction' => Conversation::PUSH,
2869 'gravity' => self::GRAVITY_ACTIVITY,
2870 'parent' => $item['id'],
2871 'thr-parent' => $item['uri'],
2872 'owner-id' => $author_id,
2873 'author-id' => $author_id,
2874 'body' => $activity,
2875 'verb' => $activity,
2876 'object-type' => $objtype,
2877 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2878 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2879 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2880 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2885 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2886 $signed = Diaspora::createLikeSignature($uid, $new_item);
2887 if (!empty($signed)) {
2888 $new_item['diaspora_signed_text'] = json_encode($signed);
2892 self::insert($new_item, true);
2894 // If the parent item isn't visible then set it to visible
2895 // @todo Check if this is still needed
2896 if (!$item['visible']) {
2897 self::update(['visible' => true], ['id' => $item['id']]);
2903 * Fetch the SQL condition for the given user id
2905 * @param integer $owner_id User ID for which the permissions should be fetched
2906 * @return array condition
2908 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2910 $local_user = DI::userSession()->getLocalUserId();
2911 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2913 // default permissions - anonymous user
2914 $condition = ["`private` != ?", self::PRIVATE];
2916 if ($local_user && ($local_user == $owner_id)) {
2917 // Profile owner - everything is visible
2919 } elseif ($remote_user) {
2920 // Authenticated visitor - fetch the matching permissionsets
2921 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2924 "(`private` != ? OR (`private` = ? AND `wall`
2925 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2926 self::PRIVATE, self::PRIVATE
2928 $condition = array_merge($condition, $permissionSets->column('id'));
2936 * Get a permission SQL string for the given user
2938 * @param int $owner_id
2939 * @param string $table
2942 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2944 $local_user = DI::userSession()->getLocalUserId();
2945 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2947 if (!empty($table)) {
2948 $table = DBA::quoteIdentifier($table) . '.';
2952 * Construct permissions
2954 * default permissions - anonymous user
2956 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2958 // Profile owner - everything is visible
2959 if ($local_user && ($local_user == $owner_id)) {
2961 } elseif ($remote_user) {
2963 * Authenticated visitor. Unless pre-verified,
2964 * check that the contact belongs to this $owner_id
2965 * and load the circles the visitor belongs to.
2966 * If pre-verified, the caller is expected to have already
2967 * done this and passed the circles into this function.
2969 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2972 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2977 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2984 * get translated item type
2986 * @param array $item
2987 * @param \Friendica\Core\L10n $l10n
2990 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2992 if (!empty($item['event-id'])) {
2993 return $l10n->t('event');
2994 } elseif (!empty($item['resource-id'])) {
2995 return $l10n->t('photo');
2996 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2997 return $l10n->t('activity');
2998 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2999 return $l10n->t('comment');
3002 return $l10n->t('post');
3006 * Sets the "rendered-html" field of the provided item
3008 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3010 * @param array $item
3012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3013 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3015 private static function putInCache(&$item)
3017 // Save original body to prevent addons to modify it
3018 $body = $item['body'];
3020 $rendered_hash = $item['rendered-hash'] ?? '';
3021 $rendered_html = $item['rendered-html'] ?? '';
3024 $rendered_hash == ''
3025 || $rendered_html == ''
3026 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3027 || DI::config()->get('system', 'ignore_cache')
3029 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3030 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3032 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3033 Hook::callAll('put_item_in_cache', $hook_data);
3034 $item['rendered-html'] = $hook_data['rendered-html'];
3035 $item['rendered-hash'] = $hook_data['rendered-hash'];
3038 // Update if the generated values differ from the existing ones
3039 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3042 'rendered-html' => $item['rendered-html'],
3043 'rendered-hash' => $item['rendered-hash']
3045 ['id' => $item['id']]
3050 $item['body'] = $body;
3054 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3055 * If attach is true, also add icons for item attachments.
3057 * @param array $item Record from item table
3058 * @param boolean $attach If true, add icons for item attachments as well
3059 * @param boolean $is_preview Whether this is a preview
3060 * @param boolean $only_cache Whether only cached HTML should be updated
3061 * @return string item body html
3062 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3063 * @throws \ImagickException
3064 * @hook prepare_body_init item array before any work
3065 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3066 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3067 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3069 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3072 Hook::callAll('prepare_body_init', $item);
3075 // In order to provide theme developers more possibilities, event items
3076 // are treated differently.
3077 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3078 $ev = Event::getItemHTML($item);
3082 $tags = Tag::populateFromItem($item);
3084 $item['tags'] = $tags['tags'];
3085 $item['hashtags'] = $tags['hashtags'];
3086 $item['mentions'] = $tags['mentions'];
3089 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3090 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3091 $item['body'] = Post\Media::replaceImage($item['body']);
3094 $body = $item['body'];
3096 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3099 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3103 $quote_shared_links = [];
3105 $shared = DI::contentItem()->getSharedPost($item, $fields);
3106 if (!empty($shared['post'])) {
3107 $shared_item = $shared['post'];
3108 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3109 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3110 $quote_uri_id = $shared['post']['uri-id'];
3111 $shared_links[] = strtolower($shared['post']['uri']);
3112 $item['body'] = BBCode::removeSharedData($item['body']);
3113 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3114 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3115 if (!empty($media)) {
3116 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3117 if (empty($shared_item['uri-id'])) {
3118 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3119 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3120 $shared_links[] = strtolower($media[0]['url']);
3123 if (empty($shared_item['uri-id'])) {
3124 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3125 $shared_links[] = strtolower($media[0]['url']);
3128 if (!empty($shared_item['uri-id'])) {
3129 $data = BBCode::getAttachmentData($shared_item['body']);
3130 if (!empty($data['url'])) {
3131 $quote_shared_links[] = $data['url'];
3134 $quote_uri_id = $shared_item['uri-id'];
3139 if (!empty($quote_uri_id)) {
3140 if (isset($shared_item['plink'])) {
3141 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item, false, true);
3143 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3147 if (!empty($shared_item['uri-id'])) {
3148 $shared_uri_id = $shared_item['uri-id'];
3149 $shared_links[] = strtolower($shared_item['plink']);
3150 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3151 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3152 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3153 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3154 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3157 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3158 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3160 self::putInCache($item);
3161 $item['body'] = $body;
3162 $s = $item["rendered-html"];
3168 // Compile eventual content filter reasons
3169 $filter_reasons = [];
3170 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3171 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3172 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3173 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3174 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3175 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3176 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3179 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3180 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3183 $item['attachments'] = $attachments;
3187 'filter_reasons' => $filter_reasons
3189 Hook::callAll('prepare_body_content_filter', $hook_data);
3190 $filter_reasons = $hook_data['filter_reasons'];
3197 'preview' => $is_preview,
3198 'filter_reasons' => $filter_reasons
3200 Hook::callAll('prepare_body', $hook_data);
3201 $s = $hook_data['html'];
3206 // Replace the blockquotes with quotes that are used in mails.
3207 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3208 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3212 if (!empty($shared_attachments)) {
3213 $s = self::addGallery($s, $shared_attachments, $item['uri-id']);
3214 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3215 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, $quote_shared_links);
3216 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3217 $body = BBCode::removeSharedData($body);
3220 $pos = strpos($s, BBCode::SHARED_ANCHOR);
3222 $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR));
3223 $s = substr($s, 0, $pos);
3226 $s = self::addGallery($s, $attachments, $item['uri-id']);
3227 $s = self::addVisualAttachments($attachments, $item, $s, false);
3228 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3229 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3230 $s = self::addQuestions($item, $s);
3233 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3234 $x = Map::byCoordinates(trim($item['coord']));
3236 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3240 // Replace friendica image url size with theme preference.
3241 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3242 $ps = $a->getThemeInfoValue('item_image_size');
3243 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3246 if (!empty($shared_html)) {
3250 $s = HTML::applyContentFilter($s, $filter_reasons);
3252 $hook_data = ['item' => $item, 'html' => $s];
3253 Hook::callAll('prepare_body_final', $hook_data);
3254 return $hook_data['html'];
3258 * @param array $images
3260 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3262 private static function makeImageGrid(array $images): string
3264 // Image for first column (fc) and second column (sc)
3268 for ($i = 0; $i < count($images); $i++) {
3269 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3272 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3281 * Modify links to pictures to links for the "Fancybox" gallery
3284 * @param array $attachments
3285 * @param integer $uri_id
3288 private static function addGallery(string $s, array $attachments, int $uri_id): string
3290 foreach ($attachments['visual'] as $attachment) {
3291 if (empty($attachment['preview']) || ($attachment['type'] != Post\Media::IMAGE)) {
3294 $s = str_replace('<a href="' . $attachment['url'] . '"', '<a data-fancybox="' . $uri_id . '" href="' . $attachment['url'] . '"', $s);
3300 * Check if the body contains a link
3302 * @param string $body
3303 * @param string $url
3307 public static function containsLink(string $body, string $url, int $type = 0): bool
3309 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3310 $urlparts = parse_url($url);
3311 if (empty($urlparts)) {
3315 unset($urlparts['query']);
3316 unset($urlparts['fragment']);
3319 $url = (string)Uri::fromParts($urlparts);
3320 } catch (\InvalidArgumentException $e) {
3321 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3322 /* See https://github.com/friendica/friendica/issues/12113
3323 * Malformed URLs will result in a Fatal Error
3328 // Remove media links to only search in embedded content
3329 // @todo Check images for image link, audio for audio links, ...
3330 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3331 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3334 if (strpos($body, $url)) {
3338 foreach ([0, 1, 2] as $size) {
3340 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3341 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3351 * Replace visual attachments in the body
3353 * @param array $attachments
3354 * @param string $body
3355 * @return string modified body
3357 private static function replaceVisualAttachments(array $attachments, string $body): string
3359 DI::profiler()->startRecording('rendering');
3361 foreach ($attachments['visual'] as $attachment) {
3362 if (!empty($attachment['preview'])) {
3363 if (Network::isLocalLink($attachment['preview'])) {
3366 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3367 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3368 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3370 $body = str_replace($search, $replace, $body);
3371 } elseif ($attachment['filetype'] == 'image') {
3372 if (Network::isLocalLink($attachment['url'])) {
3375 $proxy = Post\Media::getUrlForId($attachment['id']);
3376 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3377 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3379 $body = str_replace($search, $replace, $body);
3382 DI::profiler()->stopRecording();
3387 * Add visual attachments to the content
3389 * @param array $attachments
3390 * @param array $item
3391 * @param string $content
3392 * @return string modified content
3394 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3396 DI::profiler()->startRecording('rendering');
3401 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3402 foreach ($attachments['visual'] as $attachment) {
3403 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3407 if ($attachment['filetype'] == 'image') {
3408 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3409 } elseif (!empty($attachment['preview'])) {
3410 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3415 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3419 if (($attachment['filetype'] == 'video')) {
3420 /// @todo Move the template to /content as well
3421 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3423 'id' => $attachment['id'],
3424 'src' => $attachment['url'],
3425 'name' => $attachment['name'] ?: $attachment['url'],
3426 'preview' => $preview_url,
3427 'mime' => $attachment['mimetype'],
3430 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3433 $trailing .= $media;
3435 } elseif ($attachment['filetype'] == 'audio') {
3436 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3438 'id' => $attachment['id'],
3439 'src' => $attachment['url'],
3440 'name' => $attachment['name'] ?: $attachment['url'],
3441 'mime' => $attachment['mimetype'],
3444 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3447 $trailing .= $media;
3449 } elseif ($attachment['filetype'] == 'image') {
3450 $src_url = Post\Media::getUrlForId($attachment['id']);
3451 if (self::containsLink($item['body'], $src_url)) {
3454 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment, 'uri_id' => $item['uri-id']];
3459 if (count($images) > 1) {
3460 $media = self::makeImageGrid($images);
3461 } elseif (count($images) == 1) {
3462 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3463 '$image' => $images[0],
3467 // On Diaspora posts the attached pictures are leading
3468 if ($item['network'] == Protocol::DIASPORA) {
3471 $trailing .= $media;
3475 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3476 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3478 if ($leading != '') {
3479 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3482 if ($trailing != '') {
3483 $content .= '<div class="body-attach">' . $trailing . '</div>';
3487 DI::profiler()->stopRecording();
3492 * Add link attachment to the content
3494 * @param array $attachments
3495 * @param string $body
3496 * @param string $content
3497 * @param bool $shared
3498 * @param array $ignore_links A list of URLs to ignore
3499 * @return string modified content
3501 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3503 DI::profiler()->startRecording('rendering');
3504 // Don't show a preview when there is a visual attachment (audio or video)
3505 $types = array_column($attachments['visual'], 'type');
3506 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3508 if (!empty($attachments['link'])) {
3509 foreach ($attachments['link'] as $link) {
3511 foreach ($ignore_links as $ignore_link) {
3512 if (Strings::compareLink($link['url'], $ignore_link)) {
3516 // @todo Judge between the links to use the one with most information
3517 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3518 (empty($attachment['name']) && !empty($link['name'])) ||
3519 (empty($attachment['description']) && !empty($link['description'])) ||
3520 (empty($attachment['preview']) && !empty($link['preview'])))) {
3521 $attachment = $link;
3526 if (!empty($attachment)) {
3529 'author_name' => $attachment['author-name'] ?? '',
3530 'author_url' => $attachment['author-url'] ?? '',
3531 'description' => $attachment['description'] ?? '',
3534 'provider_name' => $attachment['publisher-name'] ?? '',
3535 'provider_url' => $attachment['publisher-url'] ?? '',
3537 'title' => $attachment['name'] ?? '',
3539 'url' => $attachment['url']
3542 if ($preview && !empty($attachment['preview'])) {
3543 if ($attachment['preview-width'] >= 500) {
3544 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3546 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3550 if (!empty($data['description']) && !empty($content)) {
3551 similar_text($data['description'], $content, $percent);
3556 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3557 $data['description'] = '';
3560 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3561 $data['author_name'] = '';
3564 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3565 $data['author_url'] = '';
3567 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3568 $data = BBCode::getAttachmentData($match[1]);
3570 DI::profiler()->stopRecording();
3572 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3573 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3574 $parts = parse_url($data['url']);
3575 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3576 if (empty($data['provider_name'])) {
3577 $data['provider_name'] = $parts['host'];
3579 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3580 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3582 if (!empty($parts['port'])) {
3583 $data['provider_url'] .= ':' . $parts['port'];
3588 // @todo Use a template
3589 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3590 if ($preview_mode != BBCode::PREVIEW_NONE) {
3591 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3595 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3596 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3597 '$url' => $data['url'],
3598 '$title' => $data['title'],
3605 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3607 return $content . $rendered;
3614 * Add non visual attachments to the content
3616 * @param array $attachments
3617 * @param array $item
3618 * @param string $content
3619 * @return string modified content
3621 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3623 DI::profiler()->startRecording('rendering');
3625 foreach ($attachments['additional'] as $attachment) {
3626 if (strpos($item['body'], $attachment['url'])) {
3632 'id' => $item['author-id'],
3633 'network' => $item['author-network'],
3634 'url' => $item['author-link'],
3635 'alias' => $item['author-alias']
3637 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3639 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3641 if (!empty($attachment['size'])) {
3642 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3645 /// @todo Use a template
3646 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3647 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3650 if ($trailing != '') {
3651 $content .= '<div class="body-attach">' . $trailing . '</div>';
3654 DI::profiler()->stopRecording();
3658 private static function addQuestions(array $item, string $content): string
3660 DI::profiler()->startRecording('rendering');
3661 if (!empty($item['question-id'])) {
3663 'id' => $item['question-id'],
3664 'multiple' => $item['question-multiple'],
3665 'voters' => $item['question-voters'],
3666 'endtime' => $item['question-end-time']
3669 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3670 foreach ($options as $key => $option) {
3671 if ($question['voters'] > 0) {
3672 $percent = $option['replies'] / $question['voters'] * 100;
3673 $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));
3675 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3679 if (!empty($question['voters']) && !empty($question['endtime'])) {
3680 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3681 } elseif (!empty($question['voters'])) {
3682 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3683 } elseif (!empty($question['endtime'])) {
3684 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3689 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3690 '$question' => $question,
3691 '$options' => $options,
3692 '$summary' => $summary,
3695 DI::profiler()->stopRecording();
3700 * get private link for item
3702 * @param array $item
3703 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3704 * @throws \Exception
3706 public static function getPlink(array $item)
3708 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3709 $plink = $item['plink'];
3710 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3711 $plink = $item['uri'];
3714 if (DI::userSession()->getLocalUserId()) {
3716 'href' => "display/" . $item['guid'],
3717 'orig' => "display/" . $item['guid'],
3718 'title' => DI::l10n()->t('View on separate page'),
3719 'orig_title' => DI::l10n()->t('View on separate page'),
3722 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3725 'id' => $item['author-id'],
3726 'network' => $item['author-network'],
3727 'url' => $item['author-link'],
3728 'alias' => $item['author-alias'],
3730 $plink = Contact::magicLinkByContact($author, $plink);
3733 if (!empty($plink)) {
3734 $ret['href'] = DI::baseUrl()->remove($plink);
3735 $ret['title'] = DI::l10n()->t('Link to source');
3737 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3741 'title' => DI::l10n()->t('Link to source'),
3742 'orig_title' => DI::l10n()->t('Link to source'),
3752 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3753 * This does apply to posts that are sent via ! and not in parallel to a group via @
3755 * @param int $uri_id
3757 * @return boolean "true" when it is a group post
3759 public static function isGroupPost(int $uri_id): bool
3761 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3765 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3766 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3767 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3768 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3776 * Search item id for given URI or plink
3778 * @param string $uri
3779 * @param integer $uid
3781 * @return integer item id
3783 public static function searchByLink(string $uri, int $uid = 0): int
3785 $ssl_uri = str_replace('http://', 'https://', $uri);
3786 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3788 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3789 if (DBA::isResult($item)) {
3793 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3794 if (DBA::isResult($item)) {
3802 * Return the URI for a link to the post
3804 * @param string $uri URI or link to post
3806 * @return string URI
3808 public static function getURIByLink(string $uri): string
3810 $ssl_uri = str_replace('http://', 'https://', $uri);
3811 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3813 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3814 if (DBA::isResult($item)) {
3815 return $item['uri'];
3818 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3819 if (DBA::isResult($item)) {
3820 return $item['uri'];
3827 * Fetches item for given URI or plink
3829 * @param string $uri
3830 * @param integer $uid
3832 * @return integer item id
3834 public static function fetchByLink(string $uri, int $uid = 0): int
3836 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3837 $item_id = self::searchByLink($uri, $uid);
3838 if (!empty($item_id)) {
3839 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3849 Hook::callAll('item_by_link', $hookData);
3851 if (isset($hookData['item_id'])) {
3852 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3855 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3858 $item_id = self::searchByLink($fetched_uri, $uid);
3860 $item_id = Diaspora::fetchByURL($uri);
3863 if (!empty($item_id)) {
3864 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3868 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3873 * Fetch the uri-id of a quote
3875 * @param string $body
3878 public static function getQuoteUriId(string $body, int $uid = 0): int
3880 $shared = BBCode::fetchShareAttributes($body);
3881 if (empty($shared['guid']) && empty($shared['message_id'])) {
3885 if (empty($shared['link']) && empty($shared['message_id'])) {
3886 Logger::notice('Invalid share block.', ['share' => $shared]);
3890 if (!empty($shared['guid'])) {
3891 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3892 if (!empty($shared_item['uri-id'])) {
3893 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3894 return $shared_item['uri-id'];
3898 if (!empty($shared['message_id'])) {
3899 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3900 if (!empty($shared_item['uri-id'])) {
3901 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3902 return $shared_item['uri-id'];
3906 if (!empty($shared['link'])) {
3907 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3908 if (!empty($shared_item['uri-id'])) {
3909 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3910 return $shared_item['uri-id'];
3914 $url = $shared['message_id'] ?: $shared['link'];
3915 $id = self::fetchByLink($url);
3917 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3921 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3922 if (!empty($shared_item['uri-id'])) {
3923 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3924 return $shared_item['uri-id'];
3927 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);