3 * @copyright Copyright (C) 2010-2024, 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\Contact\LocalRelationship\Entity\LocalRelationship;
25 use Friendica\Content\Image;
26 use Friendica\Content\Post\Collection\PostMedias;
27 use Friendica\Content\Post\Entity\PostMedia;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Post\Category;
39 use Friendica\Network\HTTPException\InternalServerErrorException;
40 use Friendica\Network\HTTPException\ServiceUnavailableException;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Protocol\Delivery;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
50 use Friendica\Util\Temporal;
51 use GuzzleHttp\Psr7\Uri;
52 use LanguageDetection\Language;
56 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
63 const PT_DOCUMENT = 19;
66 const PT_PERSONAL_NOTE = 128;
68 // Posting reasons (Why had a post been stored for a user?)
75 const PR_FOLLOWER = 69;
76 const PR_ANNOUNCEMENT = 70;
77 const PR_COMMENT = 71;
81 const PR_FETCHED = 75;
82 const PR_COMPLETION = 76;
84 const PR_ACTIVITY = 78;
85 const PR_DISTRIBUTE = 79;
88 const PR_AUDIENCE = 82;
90 // system.accept_only_sharer setting values
91 const COMPLETION_NONE = 1;
92 const COMPLETION_COMMENT = 0;
93 const COMPLETION_LIKE = 2;
95 // Field list that is used to display the items
96 const DISPLAY_FIELDLIST = [
97 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
98 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
99 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
100 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
101 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
102 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
103 'author-id', 'author-link', 'author-alias', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-baseurl', 'author-addr', 'author-uri-id',
104 'owner-id', 'owner-link', 'owner-alias', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated', 'owner-gsid',
105 'causer-id', 'causer-link', 'causer-alias', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network', 'causer-gsid',
106 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
107 'writable', 'self', 'cid', 'alias',
108 'event-created', 'event-edited', 'event-start', 'event-finish',
109 'event-summary', 'event-desc', 'event-location', 'event-type',
110 'event-nofinish', 'event-ignore', 'event-id',
111 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
112 'has-categories', 'has-media',
113 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
116 // Field list that is used to deliver items via the protocols
117 const DELIVER_FIELDLIST = [
118 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
119 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
120 'private', 'title', 'body', 'raw-body', 'language', 'location', 'coord', 'app',
121 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
122 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
123 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
124 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
125 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
126 'event-created', 'event-edited', 'event-start', 'event-finish',
127 'event-summary', 'event-desc', 'event-location', 'event-type',
128 'event-nofinish', 'event-ignore', 'event-id'
131 // All fields in the item table
132 const ITEM_FIELDLIST = [
133 'id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
134 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
135 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
136 'created', 'edited', 'commented', 'received', 'changed', 'verb',
137 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
138 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
139 'private', 'pubmail', 'visible', 'starred',
140 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
141 'title', 'content-warning', 'body', 'language', 'location', 'coord', 'app',
142 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
143 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
144 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'
147 // List of all verbs that don't need additional content data.
148 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
150 Activity::LIKE, Activity::DISLIKE,
151 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
161 // Item weight for query ordering
162 const GRAVITY_PARENT = 0;
163 const GRAVITY_ACTIVITY = 3;
164 const GRAVITY_COMMENT = 6;
165 const GRAVITY_UNKNOWN = 9;
168 * Update existing item entries
170 * @param array $fields The fields that are to be changed
171 * @param array $condition The condition for finding the item entries
173 * In the future we may have to change permissions as well.
174 * Then we had to add the user id as third parameter.
176 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
178 * @return integer|boolean number of affected rows - or "false" if there was an error
179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
181 public static function update(array $fields, array $condition)
183 if (empty($condition) || empty($fields)) {
187 if (isset($fields['extid'])) {
188 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
191 if (!empty($fields['verb'])) {
192 $fields['vid'] = Verb::getID($fields['verb']);
195 if (!empty($fields['edited'])) {
196 $previous = Post::selectFirst(['edited'], $condition);
199 if (!empty($fields['body'])) {
200 $fields['body'] = self::setHashtags($fields['body']);
203 $rows = Post::update($fields, $condition);
204 if (is_bool($rows)) {
208 // We only need to call the line by line update for specific fields
210 empty($fields['body']) && empty($fields['file']) &&
211 empty($fields['attach']) && empty($fields['edited'])
216 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
218 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
222 while ($item = DBA::fetch($items)) {
223 if (!empty($fields['body'])) {
224 if (!empty($item['quote-uri-id'])) {
225 $fields['body'] = BBCode::removeSharedData($fields['body']);
227 if (!empty($fields['raw-body'])) {
228 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
232 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
234 // Remove all media attachments from the body and store them in the post-media table
235 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
236 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
237 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
239 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
241 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
242 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
244 Post\Content::update($item['uri-id'], $content_fields);
247 if (!empty($fields['file'])) {
248 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
251 if (!empty($fields['attach'])) {
252 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
255 // We only need to notify others when it is an original entry from us.
256 // Only call the notifier when the item had been edited and records had been changed.
257 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
258 $notify_items[] = $item['id'];
264 foreach ($notify_items as $notify_item) {
265 $post = Post::selectFirst([], ['id' => $notify_item]);
267 if ($post['gravity'] != self::GRAVITY_PARENT) {
268 $signed = Diaspora::createCommentSignature($post);
269 if (!empty($signed)) {
270 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
274 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
281 * Delete an item and notify others about it - if it was ours
283 * @param array $condition The condition for finding the item entries
284 * @param integer $priority Priority for the notification
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
290 $items = Post::select(['id'], $condition);
291 while ($item = Post::fetch($items)) {
292 self::markForDeletionById($item['id'], $priority);
298 * Delete an item for an user and notify others about it - if it was ours
300 * @param array $condition The condition for finding the item entries
301 * @param integer $uid User who wants to delete this item
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 public static function deleteForUser(array $condition, int $uid)
311 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
312 while ($item = Post::fetch($items)) {
313 if (in_array($item['uid'], [$uid, 0])) {
314 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
315 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
318 if ($item['uid'] == $uid) {
319 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
320 } elseif ($item['uid'] != 0) {
321 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
328 * Mark an item for deletion, delete related data and notify others about it - if it was ours
330 * @param integer $item_id
331 * @param integer $priority Priority for the notification
332 * @return boolean success
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
335 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
337 Logger::info('Mark item for deletion by id', ['id' => $item_id]);
338 // locate item to be deleted
340 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
341 'thr-parent-id', 'deleted', 'resource-id', 'event-id', 'vid', 'body',
342 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'
344 $item = Post::selectFirst($fields, ['id' => $item_id]);
345 if (!DBA::isResult($item)) {
346 Logger::info('Item not found.', ['id' => $item_id]);
350 if ($item['deleted']) {
351 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
355 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
356 if (!DBA::isResult($parent)) {
357 $parent = ['origin' => false];
360 // clean up categories and tags so they don't end up as orphans
361 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
364 * If item is a link to a photo resource, nuke all the associated photos
365 * (visitors will not have photo resources)
366 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
367 * generate a resource-id and therefore aren't intimately linked to the item.
369 /// @TODO: this should first check if photo is used elsewhere
370 if ($item['resource-id']) {
371 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
374 // If item is a link to an event, delete the event.
375 if (intval($item['event-id'])) {
376 Event::delete($item['event-id']);
379 // If item has attachments, drop them
380 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
381 foreach ($attachments as $attachment) {
382 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
383 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
387 // Set the item to "deleted"
388 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
389 Post::update($item_fields, ['id' => $item['id']]);
391 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
393 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
394 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
397 Post\DeliveryData::delete($item['uri-id']);
399 // If it's the parent of a comment thread, kill all the kids
400 if ($item['gravity'] == self::GRAVITY_PARENT) {
401 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
404 // Is it our comment and/or our thread?
405 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
406 // When we delete the original post we will delete all existing copies on the server as well
407 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
409 // send the notification upstream/downstream
411 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
413 } elseif ($item['uid'] != 0) {
414 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
415 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
418 DI::notify()->deleteForItem($item['uri-id']);
419 DI::notification()->deleteForItem($item['uri-id']);
421 if (in_array($item['gravity'], [self::GRAVITY_ACTIVITY, self::GRAVITY_COMMENT])) {
422 Post\Counts::update($item['thr-parent-id'], $item['parent-uri-id'], $item['vid'], $item['verb'], $item['body']);
425 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
431 * Get guid from given item record
433 * @param array $item Item record
434 * @param bool Whether to notify (?)
435 * @return string Guid
437 public static function guid(array $item, bool $notify): string
439 if (!empty($item['guid'])) {
440 return trim($item['guid']);
444 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
445 // We add the hash of our own host because our host is the original creator of the post.
446 $prefix_host = DI::baseUrl()->getHost();
450 // We are only storing the post so we create a GUID from the original hostname.
451 if (!empty($item['author-link'])) {
452 $parsed = parse_url($item['author-link']);
453 if (!empty($parsed['host'])) {
454 $prefix_host = $parsed['host'];
458 if (empty($prefix_host) && !empty($item['plink'])) {
459 $parsed = parse_url($item['plink']);
460 if (!empty($parsed['host'])) {
461 $prefix_host = $parsed['host'];
465 if (empty($prefix_host) && !empty($item['uri'])) {
466 $parsed = parse_url($item['uri']);
467 if (!empty($parsed['host'])) {
468 $prefix_host = $parsed['host'];
472 // Is it in the format data@host.tld? - Used for mail contacts
473 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
474 $mailparts = explode('@', $item['author-link']);
475 $prefix_host = array_pop($mailparts);
479 if (!empty($item['plink'])) {
480 $guid = self::guidFromUri($item['plink'], $prefix_host);
481 } elseif (!empty($item['uri'])) {
482 $guid = self::guidFromUri($item['uri'], $prefix_host);
484 $guid = System::createUUID(hash('crc32', $prefix_host));
491 * Returns contact id from given item record
493 * @param array $item Item record
494 * @return int Contact id
496 private static function contactId(array $item): int
498 if ($item['uid'] == 0) {
499 return $item['owner-id'];
502 if ($item['origin']) {
503 $owner = User::getOwnerDataById($item['uid']);
508 $user_contact_id = 0;
509 foreach (['group-link', 'causer-link', 'owner-link', 'author-link'] as $field) {
510 if (empty($item[$field])) {
513 if (!$user_contact_id && Contact::isSharingByURL($item[$field], $item['uid'], true)) {
514 $user_contact_id = Contact::getIdForURL($item[$field], $item['uid']);
515 } elseif (!$contact_id) {
516 $contact_id = Contact::getIdForURL($item[$field]);
520 if ($user_contact_id) {
521 return $user_contact_id;
524 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
525 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
526 if (!empty($cdata['user'])) {
527 return $cdata['user'];
535 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
536 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
541 * Write an item array into a spool file to be inserted later.
542 * This command is called whenever there are issues storing an item.
544 * @param array $item The item fields that are to be inserted
547 private static function spool(array $item)
549 // Now we store the data in the spool directory
550 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
551 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
553 $spoolpath = System::getSpoolPath();
554 if ($spoolpath != '') {
555 $spool = $spoolpath . '/' . $file;
557 file_put_contents($spool, json_encode($item));
558 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
563 * Check if the item array is a duplicate
565 * @param array $item Item record
566 * @return boolean is it a duplicate?
568 private static function isDuplicate(array $item): bool
570 // Checking if there is already an item with the same guid
571 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
572 if (Post::exists($condition)) {
573 Logger::notice('Found already existing item', $condition);
578 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
579 'network' => [$item['network'], Protocol::DFRN]
581 if (Post::exists($condition)) {
582 Logger::notice('duplicated item with the same uri found.', $condition);
586 // On Friendica and Diaspora the GUID is unique
587 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
588 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
589 if (Post::exists($condition)) {
590 Logger::notice('duplicated item with the same guid found.', $condition);
593 } elseif ($item['network'] == Protocol::OSTATUS) {
594 // Check for an existing post with the same content. There seems to be a problem with OStatus.
596 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
597 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
599 if (Post::exists($condition)) {
600 Logger::notice('duplicated item with the same body found.', $item);
606 * Check for already added items.
607 * There is a timing issue here that sometimes creates double postings.
608 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
610 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
611 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
619 * Check if the item array is valid
621 * @param array $item Item record
622 * @return boolean item is valid
624 public static function isValid(array $item): bool
626 // When there is no content then we don't post it
627 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
628 Logger::notice('No body, no title.');
632 if (!empty($item['uid'])) {
633 $owner = User::getOwnerDataById($item['uid'], false);
635 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
639 if ($owner['account_expired'] || $owner['account_removed']) {
640 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']]);
645 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
646 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
650 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
651 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
655 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
656 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
660 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
661 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
665 if ($item['verb'] == Activity::FOLLOW) {
666 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
667 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
668 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
673 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
674 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
676 if (Post::exists($condition)) {
677 // It happens that we receive multiple follow requests by the same author - we only store one.
678 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
687 * Check if the item array is too old
689 * @param array $item Item record
690 * @return boolean item is too old
692 public static function isTooOld(array $item): bool
694 // check for create date and expire time
695 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
697 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
698 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
699 $expire_interval = $user['expire'];
702 if (($expire_interval > 0) && !empty($item['created'])) {
703 $expire_date = time() - ($expire_interval * 86400);
704 $created_date = strtotime($item['created']);
705 if ($created_date < $expire_date) {
706 Logger::notice('Item created before expiration interval.', [
707 'created' => date('c', $created_date),
708 'expired' => date('c', $expire_date),
719 * Return the id of the given item array if it has been stored before
721 * @param array $item Item record
722 * @return integer Item id or zero on error
724 private static function getDuplicateID(array $item): int
726 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
728 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
731 Protocol::ACTIVITYPUB,
736 $existing = Post::selectFirst(['id', 'network'], $condition);
737 if (DBA::isResult($existing)) {
738 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
739 if ($item['uid'] != 0) {
740 Logger::notice('Item already existed for user', [
741 'uri-id' => $item['uri-id'],
742 'uid' => $item['uid'],
743 'network' => $item['network'],
744 'existing_id' => $existing['id'],
745 'existing_network' => $existing['network']
749 return $existing['id'];
756 * Fetch the uri-id of the parent for the given uri-id
758 * @param integer $uriid
761 public static function getParent(int $uriid): int
763 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
764 if (empty($thread_parent)) {
768 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
772 return self::getParent($thread_parent['thr-parent-id']);
776 * Fetch top-level parent data for the given item array
779 * @return array item array with parent data
782 private static function getTopLevelParent(array $item): array
785 'uid', 'uri', 'parent-uri', 'id', 'deleted',
786 'uri-id', 'parent-uri-id',
787 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
788 'wall', 'private', 'origin', 'author-id'
790 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
791 $params = ['order' => ['id' => false]];
792 $parent = Post::selectFirst($fields, $condition, $params);
794 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
795 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
796 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
797 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
800 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
801 $parent = Post::selectFirst($fields, $condition, $params);
805 if (!DBA::isResult($parent)) {
806 Logger::notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
810 if ($parent['uri-id'] == $parent['parent-uri-id']) {
815 'uri-id' => $parent['parent-uri-id'],
816 'parent-uri-id' => $parent['parent-uri-id'],
817 'uid' => $parent['uid']
819 $params = ['order' => ['id' => false]];
820 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
822 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
823 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
824 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
825 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
828 if (!DBA::isResult($toplevel_parent)) {
829 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
833 return $toplevel_parent;
837 * Get the gravity for the given item array
840 * @return integer gravity
842 private static function getGravity(array $item): int
844 $activity = DI::activity();
846 if (isset($item['gravity'])) {
847 return intval($item['gravity']);
848 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
849 return self::GRAVITY_PARENT;
850 } elseif ($activity->match($item['verb'], Activity::POST)) {
851 return self::GRAVITY_COMMENT;
852 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
853 return self::GRAVITY_ACTIVITY;
854 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
855 return self::GRAVITY_ACTIVITY;
858 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
859 return self::GRAVITY_UNKNOWN; // Should not happen
862 private static function prepareOriginPost(array $item): array
864 $item = DI::contentItem()->initializePost($item);
865 $item = DI::contentItem()->finalizePost($item);
871 * Inserts item record
873 * @param array $item Item array to be inserted
874 * @param int $notify Notification (type?)
875 * @param bool $post_local (???)
876 * @return int Zero means error, otherwise primary key (id) is being returned
878 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
882 $priority = Worker::PRIORITY_HIGH;
884 // If it is a posting where users should get notifications, then define it as wall posting
886 $item = self::prepareOriginPost($item);
888 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
892 // Mastodon style API visibility
893 $copy_permissions = ($item['visibility'] ?? 'private') == 'private';
894 unset($item['visibility']);
896 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
899 $uid = intval($item['uid']);
901 $item['guid'] = self::guid($item, $notify);
902 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
905 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
907 // Backward compatibility: parent-uri used to be the direct parent uri.
908 // If it is provided without a thr-parent, it probably is the old behavior.
909 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
910 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
911 $item['parent-uri'] = $item['thr-parent'];
914 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
915 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
917 // Store conversation data
918 $source = $item['source'] ?? '';
919 unset($item['conversation-uri']);
920 unset($item['conversation-href']);
921 unset($item['source']);
924 * Do we already have this item?
925 * We have to check several networks since Friendica posts could be repeated
926 * via OStatus (maybe Diaspora as well)
928 $duplicate = self::getDuplicateID($item);
933 // Additional duplicate checks
934 /// @todo Check why the first duplication check returns the item number and the second a 0
935 if (self::isDuplicate($item)) {
939 if (!isset($item['post-type'])) {
940 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
943 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
945 $item['wall'] = intval($item['wall'] ?? 0);
946 $item['extid'] = trim($item['extid'] ?? '');
947 $item['author-name'] = trim($item['author-name'] ?? '');
948 $item['author-link'] = trim($item['author-link'] ?? '');
949 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
950 $item['owner-name'] = trim($item['owner-name'] ?? '');
951 $item['owner-link'] = trim($item['owner-link'] ?? '');
952 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
953 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
954 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
955 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
956 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
957 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
958 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
959 $item['location'] = trim($item['location'] ?? '');
960 $item['coord'] = trim($item['coord'] ?? '');
961 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
962 $item['deleted'] = 0;
963 $item['verb'] = trim($item['verb'] ?? '');
964 $item['object-type'] = trim($item['object-type'] ?? '');
965 $item['object'] = trim($item['object'] ?? '');
966 $item['target-type'] = trim($item['target-type'] ?? '');
967 $item['target'] = trim($item['target'] ?? '');
968 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
969 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
970 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
971 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
972 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
973 $item['private'] = intval($item['private'] ?? self::PUBLIC);
974 $item['body'] = trim($item['body'] ?? '');
975 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
976 $item['app'] = trim($item['app'] ?? '');
977 $item['origin'] = intval($item['origin'] ?? 0);
978 $item['postopts'] = trim($item['postopts'] ?? '');
979 $item['resource-id'] = trim($item['resource-id'] ?? '');
980 $item['event-id'] = intval($item['event-id'] ?? 0);
981 $item['inform'] = trim($item['inform'] ?? '');
982 $item['file'] = trim($item['file'] ?? '');
984 // Communities aren't working with the Diaspora protocol
985 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
986 $user = User::getById($uid, ['account-type']);
987 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
988 Logger::info('Community posts are not supported via Diaspora');
993 // Items cannot be stored before they happen ...
994 if ($item['created'] > DateTimeFormat::utcNow()) {
995 $item['created'] = DateTimeFormat::utcNow();
998 // We haven't invented time travel by now.
999 if ($item['edited'] > DateTimeFormat::utcNow()) {
1000 $item['edited'] = DateTimeFormat::utcNow();
1003 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1005 $item['gravity'] = self::getGravity($item);
1008 'url' => $item['author-link'], 'name' => $item['author-name'],
1009 'photo' => $item['author-avatar'], 'network' => $item['network']
1011 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1014 'url' => $item['owner-link'], 'name' => $item['owner-name'],
1015 'photo' => $item['owner-avatar'], 'network' => $item['network']
1017 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1019 $item['post-reason'] = self::getPostReason($item);
1021 // Ensure that there is an avatar cache
1022 Contact::checkAvatarCache($item['author-id']);
1023 Contact::checkAvatarCache($item['owner-id']);
1025 $item['contact-id'] = self::contactId($item);
1028 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1029 empty($item['origin']) && self::isTooOld($item)
1031 Logger::info('Item is too old', ['item' => $item]);
1035 if (!self::isValid($item)) {
1039 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1040 $toplevel_parent = self::getTopLevelParent($item);
1041 if (empty($toplevel_parent)) {
1045 $parent_id = $toplevel_parent['id'];
1046 $item['parent-uri'] = $toplevel_parent['uri'];
1047 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1048 $item['deleted'] = $toplevel_parent['deleted'];
1049 $item['wall'] = $toplevel_parent['wall'];
1051 // Reshares have to keep their permissions to allow groups to work
1052 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1053 // Don't store the permissions on pure AP posts
1054 $store_permissions = ($item['network'] != Protocol::ACTIVITYPUB) || $item['origin'] || !empty($item['diaspora_signed_text']);
1055 $item['allow_cid'] = $store_permissions ? $toplevel_parent['allow_cid'] : '';
1056 $item['allow_gid'] = $store_permissions ? $toplevel_parent['allow_gid'] : '';
1057 $item['deny_cid'] = $store_permissions ? $toplevel_parent['deny_cid'] : '';
1058 $item['deny_gid'] = $store_permissions ? $toplevel_parent['deny_gid'] : '';
1061 $parent_origin = $toplevel_parent['origin'];
1063 // Don't federate received participation messages
1064 if ($item['verb'] != Activity::FOLLOW) {
1065 $item['wall'] = $toplevel_parent['wall'];
1067 $item['wall'] = false;
1068 // Participations are technical messages, so they are set to "seen" automatically
1069 $item['unseen'] = false;
1073 * If the parent is private, force privacy for the entire conversation
1074 * This differs from the above settings as it subtly allows comments from
1075 * email correspondents to be private even if the overall thread is not.
1077 if (!$defined_permissions && $toplevel_parent['private']) {
1078 $item['private'] = $toplevel_parent['private'];
1081 // If its a post that originated here then tag the thread as "mention"
1082 if ($item['origin'] && $item['uid']) {
1083 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1084 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1087 // Update the contact relations
1088 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1091 $parent_origin = $item['origin'];
1093 if ($item['wall'] && empty($item['conversation'])) {
1094 $item['conversation'] = $item['parent-uri'] . '#context';
1098 if ($item['origin']) {
1100 Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])
1101 && ($item['object-type'] != Activity\ObjectType::EVENT)
1103 $item['object-type'] = Activity\ObjectType::IMAGE;
1106 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1109 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1110 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1112 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1113 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1116 // Is this item available in the global items (with uid=0)?
1117 if ($item['uid'] == 0) {
1118 $item['global'] = true;
1120 // Set the global flag on all items if this was a global item entry
1121 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1123 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1127 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1128 $item['private'] = self::PRIVATE;
1131 if ($notify && $post_local) {
1132 $item['edit'] = false;
1133 $item['parent'] = $parent_id;
1135 // Trigger automatic reactions for addons
1136 if (!isset($item['api_source'])) {
1137 $item['api_source'] = true;
1140 // We have to tell the hooks who we are - this really should be improved
1141 if (!DI::userSession()->getLocalUserId()) {
1142 $_SESSION['authenticated'] = true;
1143 $_SESSION['uid'] = $uid;
1144 $dummy_session = true;
1146 $dummy_session = false;
1149 Hook::callAll('post_local', $item);
1151 if ($dummy_session) {
1152 unset($_SESSION['authenticated']);
1153 unset($_SESSION['uid']);
1155 } elseif (!$notify) {
1156 Hook::callAll('post_remote', $item);
1159 if (!empty($item['cancel'])) {
1160 Logger::notice('post cancelled by addon.');
1164 if (empty($item['vid']) && !empty($item['verb'])) {
1165 $item['vid'] = Verb::getID($item['verb']);
1168 // Creates or assigns the permission set
1169 $item['psid'] = DI::permissionSet()->selectOrCreate(
1170 DI::permissionSetFactory()->createFromString(
1179 if (!empty($item['extid'])) {
1180 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1183 if ($item['verb'] == Activity::ANNOUNCE) {
1184 self::setOwnerforResharedItem($item);
1187 if (isset($item['attachments'])) {
1188 foreach ($item['attachments'] as $attachment) {
1189 $attachment['uri-id'] = $item['uri-id'];
1190 Post\Media::insert($attachment);
1192 unset($item['attachments']);
1195 if (empty($item['quote-uri-id'])) {
1196 $quote_id = self::getQuoteUriId($item['body']);
1197 if (!empty($quote_id)) {
1198 // This is one of these "should not happen" situations.
1199 // The protocol implementations should already have done this job.
1200 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
1201 $item['quote-uri-id'] = $quote_id;
1205 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) {
1206 Logger::info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1207 unset($item['quote-uri-id']);
1210 if (!empty($item['quote-uri-id'])) {
1211 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1212 $item['body'] = BBCode::removeSharedData($item['body']);
1215 // Remove all media attachments from the body and store them in the post-media table
1216 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1217 $item['raw-body'] = self::setHashtags($item['raw-body']);
1219 $author = Contact::getById($item['author-id'], ['network']);
1220 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1222 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1223 $item['body'] = BBCode::removeAttachment($item['body']);
1224 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1226 // Check for hashtags in the body and repair or add hashtag links
1227 $item['body'] = self::setHashtags($item['body']);
1229 $notify_type = Delivery::POST;
1231 // Filling item related side tables
1232 if (!empty($item['attach'])) {
1233 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1236 if (empty($item['event-id'])) {
1237 unset($item['event-id']);
1239 $ev = Event::fromBBCode($item['body']);
1240 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1241 Logger::info('Event found.');
1242 $ev['cid'] = $item['contact-id'];
1243 $ev['uid'] = $item['uid'];
1244 $ev['uri'] = $item['uri'];
1245 $ev['edited'] = $item['edited'];
1246 $ev['private'] = $item['private'];
1247 $ev['guid'] = $item['guid'];
1248 $ev['plink'] = $item['plink'];
1249 $ev['network'] = $item['network'];
1250 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1251 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1252 $ev['source'] = $item['source'] ?? '';
1254 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1255 if (DBA::isResult($event)) {
1256 $ev['id'] = $event['id'];
1259 $event_id = Event::store($ev);
1260 $item = Event::getItemArrayForImportedId($event_id, $item);
1262 Logger::info('Event was stored', ['id' => $event_id]);
1266 if (empty($item['causer-id'])) {
1267 unset($item['causer-id']);
1270 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1271 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1272 if (!empty($content_warning) && empty($item['content-warning'])) {
1273 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1277 $item['language'] = self::getLanguage($item);
1279 $inserted = Post::insert($item['uri-id'], $item);
1281 if ($item['gravity'] == self::GRAVITY_PARENT) {
1282 Post\Thread::insert($item['uri-id'], $item);
1285 // The content of activities normally doesn't matter - except for likes from Misskey
1286 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1287 Post\Content::insert($item['uri-id'], $item);
1290 $item['parent'] = $parent_id;
1292 // Create Diaspora signature
1293 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1294 $signed = Diaspora::createCommentSignature($item);
1295 if (!empty($signed)) {
1296 $item['diaspora_signed_text'] = json_encode($signed);
1300 if (!empty($item['diaspora_signed_text'])) {
1301 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1304 // Attached file links
1305 if (!empty($item['file'])) {
1306 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1309 // Delivery relevant data
1310 $delivery_data = Post\DeliveryData::extractFields($item);
1312 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1313 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1316 // Store tags from the body if this hadn't been handled previously in the protocol classes
1317 if (!Tag::existsForPost($item['uri-id'])) {
1318 Tag::storeFromBody($item['uri-id'], $item['body']);
1321 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1322 if (Post::exists($condition)) {
1323 Logger::notice('Item is already inserted - aborting', $condition);
1327 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1328 if (!$post_user_id) {
1329 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1333 if ($item['gravity'] == self::GRAVITY_PARENT) {
1334 $item['post-user-id'] = $post_user_id;
1335 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1338 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1340 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1341 if (!DBA::isResult($posted_item)) {
1342 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1343 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1344 self::spool($orig_item);
1348 // update the commented timestamp on the parent
1349 if (DI::config()->get('system', 'like_no_comment')) {
1350 // Update when it is a comment
1351 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1353 // Update when it isn't a follow or tag verb
1354 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1357 if ($update_commented) {
1358 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1360 $fields = ['changed' => DateTimeFormat::utcNow()];
1363 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1365 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1366 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1367 // Get the user information for the logging
1368 $user = User::getById($uid);
1370 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1375 DI::contentItem()->postProcessPost($posted_item);
1376 if ($copy_permissions && ($posted_item['thr-parent-id'] != $posted_item['uri-id']) && ($posted_item['private'] == self::PRIVATE)) {
1377 DI::contentItem()->copyPermissions($posted_item['thr-parent-id'], $posted_item['uri-id'], $posted_item['parent-uri-id']);
1380 Hook::callAll('post_remote_end', $posted_item);
1383 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1384 self::addShadow($post_user_id);
1386 self::addShadowPost($post_user_id);
1389 self::updateContact($posted_item);
1391 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1393 // Distribute items to users who subscribed to their tags
1394 self::distributeByTags($posted_item);
1396 // Automatically reshare the item if the "remote_self" option is selected
1397 self::autoReshare($posted_item);
1399 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1402 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1403 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1406 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1407 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1410 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1411 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1415 // Don't relay participation messages
1416 if (($posted_item['verb'] == Activity::FOLLOW) &&
1417 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1419 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1424 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1425 Post\Activity::insert($posted_item['uri-id'], $source);
1429 ActivityPub\Transmitter::storeReceiversForItem($posted_item);
1431 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1435 // Fill the cache with the rendered content.
1436 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT])) {
1437 self::updateDisplayCache($posted_item['uri-id']);
1440 if (in_array($posted_item['gravity'], [self::GRAVITY_ACTIVITY, self::GRAVITY_COMMENT])) {
1441 Post\Counts::update($posted_item['thr-parent-id'], $posted_item['parent-uri-id'], $posted_item['vid'], $posted_item['verb'], $posted_item['body']);
1444 $engagement_uri_id = Post\Engagement::storeFromItem($posted_item);
1445 if ($engagement_uri_id) {
1446 self::reshareChannelPost($engagement_uri_id);
1450 return $post_user_id;
1453 private static function reshareChannelPost(int $uri_id)
1455 $item = Post::selectFirst(['id', 'private', 'network', 'language', 'owner-id'], ['uri-id' => $uri_id, 'uid' => 0]);
1456 if (empty($item['id'])) {
1460 if (($item['private'] != self::PUBLIC) || !in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1464 $engagement = DBA::selectFirst('post-engagement', ['searchtext', 'media-type'], ['uri-id' => $uri_id]);
1465 if (empty($engagement['searchtext'])) {
1469 $language = !empty($item['language']) ? array_key_first(json_decode($item['language'], true)) : '';
1470 $tags = array_column(Tag::getByURIId($uri_id, [Tag::HASHTAG]), 'name');
1472 foreach (DI::userDefinedChannel()->getMatchingChannelUsers($engagement['searchtext'], $language, $tags, $engagement['media-type'], $item['owner-id']) as $uid) {
1473 Logger::debug('Reshare post', ['uid' => $uid, 'uri-id' => $uri_id, 'language' => $language, 'tags' => $tags, 'searchtext' => $engagement['searchtext'], 'media_type' => $engagement['media-type']]);
1474 self::performActivity($item['id'], 'announce', $uid);
1479 * Fetch the post reason for a given item array
1481 * @param array $item
1485 public static function getPostReason(array $item): int
1487 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1488 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1489 return self::PR_FOLLOWER;
1492 if (!empty($item['origin']) && empty($item['post-reason'])) {
1493 return self::PR_LOCAL;
1496 return $item['post-reason'] ?? self::PR_NONE;
1500 * Update the display cache
1502 * @param integer $uri_id
1504 * @throws InternalServerErrorException
1505 * @throws \ImagickException
1507 public static function updateDisplayCache(int $uri_id)
1509 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1514 self::prepareBody($item, false, false, true);
1518 * Change the owner of a parent item if it had been shared by a group
1520 * (public) group posts in the new format consist of the regular post by the author
1521 * followed by an announce message sent from the group account.
1522 * Changing the owner helps in grouping group posts.
1524 * @param array $item
1527 private static function setOwnerforResharedItem(array $item)
1529 if ($item['uid'] == 0) {
1533 $parent = Post::selectFirst(
1534 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1535 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1537 if (!DBA::isResult($parent)) {
1538 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1542 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1543 if (!DBA::isResult($author)) {
1544 Logger::error('Author not found', ['id' => $item['author-id']]);
1548 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1549 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1551 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1552 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1553 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1557 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1558 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1559 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']]);
1563 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1564 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1569 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1570 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1574 * Distribute the given item to users who subscribed to their tags
1576 * @param array $item Processed item
1578 private static function distributeByTags(array $item)
1580 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1584 $languages = $item['language'] ? array_keys(json_decode($item['language'], true)) : [];
1586 foreach (Tag::getUIDListByURIId($item['uri-id']) as $uid => $tags) {
1587 if (!empty($languages)) {
1589 $user_languages = User::getWantedLanguages($uid);
1590 foreach ($user_languages as $language) {
1591 if (in_array($language, $languages)) {
1596 Logger::debug('Wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]);
1598 Logger::debug('No wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]);
1603 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1604 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1605 foreach ($tags as $tag) {
1606 $stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag);
1607 Logger::debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]);
1613 * Distributes public items to the receivers
1615 * @param integer $itemid Item ID that should be added
1616 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1617 * @throws \Exception
1619 public static function distribute(int $itemid, string $signed_text = '')
1621 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1622 $parent = Post::selectFirst(['owner-id'], $condition);
1623 if (!DBA::isResult($parent)) {
1624 Logger::warning('Item not found', ['condition' => $condition]);
1628 // Only distribute public items from native networks
1630 'id' => $itemid, 'uid' => 0,
1631 'network' => array_merge(Protocol::FEDERATED, ['']),
1632 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1634 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1635 if (!DBA::isResult($item)) {
1636 Logger::warning('Item not found', ['condition' => $condition]);
1640 $origin = $item['origin'];
1644 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1645 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1646 if (!DBA::isResult($owner)) {
1650 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1651 $contacts = DBA::select('contact', ['uid'], $condition);
1652 while ($contact = DBA::fetch($contacts)) {
1653 if ($contact['uid'] == 0) {
1657 $users[$contact['uid']] = $contact['uid'];
1659 DBA::close($contacts);
1661 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1662 $contacts = DBA::select('contact', ['uid'], $condition);
1663 while ($contact = DBA::fetch($contacts)) {
1664 if ($contact['uid'] == 0) {
1668 $users[$contact['uid']] = $contact['uid'];
1670 DBA::close($contacts);
1672 if (!empty($owner['alias'])) {
1673 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1674 $contacts = DBA::select('contact', ['uid'], $condition);
1675 while ($contact = DBA::fetch($contacts)) {
1676 if ($contact['uid'] == 0) {
1680 $users[$contact['uid']] = $contact['uid'];
1682 DBA::close($contacts);
1687 if ($item['uri-id'] != $item['parent-uri-id']) {
1688 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1689 while ($parent = Post::fetch($parents)) {
1690 $users[$parent['uid']] = $parent['uid'];
1691 if ($parent['origin'] && !$origin) {
1692 $origin_uid = $parent['uid'];
1695 DBA::close($parents);
1698 foreach ($users as $uid) {
1699 if ($origin_uid == $uid) {
1700 $item['diaspora_signed_text'] = $signed_text;
1702 $item['post-reason'] = self::PR_DISTRIBUTE;
1703 self::storeForUser($item, $uid);
1708 * Store a public item defined by their URI-ID for the given users
1710 * @param integer $uri_id URI-ID of the given item
1711 * @param integer $uid The user that will receive the item entry
1712 * @param array $fields Additional fields to be stored
1713 * @param integer $source_uid User id of the source post
1714 * @return integer stored item id
1716 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1718 if ($uid == $source_uid) {
1719 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1723 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1724 if (!DBA::isResult($item)) {
1725 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1729 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1730 $owner = User::getOwnerDataById($uid);
1731 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1732 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1737 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1738 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']]);
1742 $item['post-reason'] = self::PR_STORED;
1744 $item = array_merge($item, $fields);
1746 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1747 $item['post-reason'] = self::PR_FOLLOWER;
1750 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1752 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1753 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1754 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1756 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']]);
1760 $causer = $item['causer-id'] ?: $item['author-id'];
1762 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1763 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1764 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1767 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1768 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1769 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1770 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1773 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1776 $stored = self::storeForUser($item, $uid);
1777 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1782 * Fetch the parent with the given uri-id
1784 * @param integer $uri_id
1785 * @param integer $uid
1786 * @param integer $causer
1790 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1792 // Fetch the origin user for the post
1793 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1794 if (is_null($origin_uid)) {
1795 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1799 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1803 * Returns the origin uid of a post if the given user is allowed to see it.
1809 private static function GetOriginUidForUriId(int $uriid, int $uid)
1811 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1815 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1816 if (!empty($post)) {
1817 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1818 return $post['uid'];
1821 $pcid = Contact::getPublicIdByUserId($uid);
1826 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1827 if ($receiver == $pcid) {
1828 return $post['uid'];
1835 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1839 // When the post belongs to a a group then all group users are allowed to access it
1840 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1841 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1842 $target_uid = User::getIdForURL($tag['url']);
1843 if (!empty($target_uid)) {
1853 * Store a public item array for the given users
1855 * @param array $item The item entry that will be stored
1856 * @param integer $uid The user that will receive the item entry
1857 * @return integer stored item id
1858 * @throws \Exception
1860 private static function storeForUser(array $item, int $uid): int
1862 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1863 if (!empty($post['id'])) {
1864 if (!empty($item['event-id'])) {
1865 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1866 if (!empty($event_post['event-id'])) {
1867 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1868 if (!empty($event)) {
1869 // We aren't using "Event::store" here, since we don't want to trigger any further action
1870 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1871 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1875 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1879 // Data from the "post-user" table
1881 unset($item['mention']);
1882 unset($item['starred']);
1883 unset($item['unseen']);
1884 unset($item['psid']);
1885 unset($item['pinned']);
1886 unset($item['ignored']);
1887 unset($item['pubmail']);
1888 unset($item['event-id']);
1889 unset($item['hidden']);
1890 unset($item['notification-type']);
1892 // Data from the "post-delivery-data" table
1893 unset($item['postopts']);
1894 unset($item['inform']);
1896 $item['uid'] = $uid;
1897 $item['origin'] = 0;
1901 if ($item['gravity'] == self::GRAVITY_PARENT) {
1902 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1903 if (DBA::isResult($contact)) {
1904 $notify = self::isRemoteSelf($contact, $item);
1905 $item['wall'] = (bool)$notify;
1909 $item['contact-id'] = self::contactId($item);
1910 $distributed = self::insert($item, $notify);
1912 if (!$distributed) {
1913 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1915 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1917 return $distributed;
1921 * Add a shadow entry for a given item id that is a thread starter
1923 * We store every public item entry additionally with the user id "0".
1924 * This is used for the community page and for the search.
1925 * It is planned that in the future we will store public item entries only once.
1927 * @param integer $itemid Item ID that should be added
1928 * @throws \Exception
1930 private static function addShadow(int $itemid)
1932 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1933 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1934 $item = Post::selectFirst($fields, $condition);
1936 if (!DBA::isResult($item)) {
1940 // is it already a copy?
1941 if (($itemid == 0) || ($item['uid'] == 0)) {
1945 // Is it a visible public post?
1946 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1950 // is it an entry from a connector? Only add an entry for natively connected networks
1951 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1955 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1959 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1961 if (DBA::isResult($item)) {
1962 // Preparing public shadow (removing user specific data)
1965 unset($item['parent']);
1966 unset($item['wall']);
1967 unset($item['mention']);
1968 unset($item['origin']);
1969 unset($item['starred']);
1970 unset($item['postopts']);
1971 unset($item['inform']);
1972 unset($item['post-reason']);
1973 if ($item['uri-id'] == $item['parent-uri-id']) {
1974 $item['contact-id'] = $item['owner-id'];
1976 $item['contact-id'] = $item['author-id'];
1979 $public_shadow = self::insert($item);
1981 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1986 * Add a shadow entry for a given item id that is a comment
1988 * This function does the same like the function above - but for comments
1990 * @param integer $itemid Item ID that should be added
1991 * @throws \Exception
1993 private static function addShadowPost(int $itemid)
1995 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1996 if (!DBA::isResult($item)) {
2000 // Is it a toplevel post?
2001 if ($item['gravity'] == self::GRAVITY_PARENT) {
2002 self::addShadow($itemid);
2006 // Is this a shadow entry?
2007 if ($item['uid'] == 0) {
2011 // Is there a shadow parent?
2012 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
2016 // Is there already a shadow entry?
2017 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
2021 // Save "origin" and "parent" state
2022 $origin = $item['origin'];
2023 $parent = $item['parent'];
2025 // Preparing public shadow (removing user specific data)
2028 unset($item['parent']);
2029 unset($item['wall']);
2030 unset($item['mention']);
2031 unset($item['origin']);
2032 unset($item['starred']);
2033 unset($item['postopts']);
2034 unset($item['inform']);
2035 unset($item['post-reason']);
2036 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2038 $public_shadow = self::insert($item);
2040 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
2042 // If this was a comment to a Diaspora post we don't get our comment back.
2043 // This means that we have to distribute the comment by ourselves.
2044 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2045 self::distribute($public_shadow);
2050 * Adds a language specification in a "language" element of given $arr.
2051 * Expects "body" element to exist in $arr.
2053 * @param array $item
2054 * @return string detected language
2055 * @throws \Text_LanguageDetect_Exception
2057 private static function getLanguage(array $item): ?string
2059 if (!empty($item['language'])) {
2060 return $item['language'];
2064 foreach ($item['transmitted-languages'] ?? [] as $language) {
2065 $transmitted[$language] = 0;
2068 $content = trim(($item['title'] ?? '') . ' ' . ($item['content-warning'] ?? '') . ' ' . ($item['body'] ?? ''));
2070 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($content)) {
2071 return !empty($transmitted) ? json_encode($transmitted) : null;
2074 $languages = self::getLanguageArray($content, 3, $item['uri-id'], $item['author-id']);
2075 if (empty($languages)) {
2076 return !empty($transmitted) ? json_encode($transmitted) : null;
2079 if (!empty($transmitted)) {
2080 $languages = array_merge($transmitted, $languages);
2084 return json_encode($languages);
2088 * Get a language array from a given text
2090 * @param string $body
2091 * @param integer $count
2092 * @param integer $uri_id
2093 * @param integer $author_id
2096 public static function getLanguageArray(string $body, int $count, int $uri_id = 0, int $author_id = 0): array
2098 $searchtext = BBCode::toSearchText($body, $uri_id);
2100 if ((count(explode(' ', $searchtext)) < 10) && (mb_strlen($searchtext) < 30) && $author_id) {
2101 $author = Contact::selectFirst(['about'], ['id' => $author_id]);
2102 if (!empty($author['about'])) {
2103 $about = BBCode::toSearchText($author['about'], 0);
2104 Logger::debug('About field added', ['author' => $author_id, 'body' => $searchtext, 'about' => $about]);
2105 $searchtext .= ' ' . $about;
2109 if (empty($searchtext)) {
2113 $ld = new Language(DI::l10n()->getDetectableLanguages());
2117 foreach (self::splitByBlocks($searchtext) as $block) {
2118 $languages = $ld->detect($block)->close() ?: [];
2122 'detected' => $languages,
2123 'uri-id' => $uri_id,
2124 'author-id' => $author_id,
2126 Hook::callAll('detect_languages', $data);
2128 foreach ($data['detected'] as $language => $quality) {
2129 $result[$language] = max($result[$language] ?? 0, $quality * (strlen($block) / strlen($searchtext)));
2133 if (empty($result)) {
2137 $result = self::compactLanguages($result);
2140 return array_slice($result, 0, $count);
2144 * Concert the language code in the detection result to ISO 639-1.
2145 * On duplicates the system uses the higher quality value.
2147 * @param array $result
2150 private static function compactLanguages(array $result): array
2153 foreach ($result as $language => $quality) {
2154 if ($quality == 0) {
2157 $code = DI::l10n()->toISO6391($language);
2158 if (empty($languages[$code]) || ($languages[$code] < $quality)) {
2159 $languages[$code] = $quality;
2166 * Split a string into different unicode blocks
2167 * Currently the text is split into the latin and the non latin part.
2169 * @param string $body
2172 private static function splitByBlocks(string $body): array
2174 if (!class_exists('IntlChar')) {
2179 $previous_block = 0;
2181 for ($i = 0; $i < mb_strlen($body); $i++) {
2182 $character = mb_substr($body, $i, 1);
2183 $previous = ($i > 0) ? mb_substr($body, $i - 1, 1) : '';
2184 $next = ($i < mb_strlen($body)) ? mb_substr($body, $i + 1, 1) : '';
2186 if (!\IntlChar::isalpha($character)) {
2187 if (($previous != '') && (\IntlChar::isalpha($previous))) {
2188 $previous_block = self::getBlockCode($previous);
2191 $block = (($next != '') && \IntlChar::isalpha($next)) ? self::getBlockCode($next) : $previous_block;
2192 $blocks[$block] = ($blocks[$block] ?? '') . $character;
2194 $block = self::getBlockCode($character);
2195 $blocks[$block] = ($blocks[$block] ?? '') . $character;
2199 foreach (array_keys($blocks) as $key) {
2200 $blocks[$key] = trim($blocks[$key]);
2201 if (empty($blocks[$key])) {
2202 unset($blocks[$key]);
2206 return array_values($blocks);
2210 * returns the block code for the given character
2212 * @param string $character
2213 * @return integer 0 = no alpha character (blank, signs, emojis, ...), 1 = latin character, 2 = character in every other language
2215 private static function getBlockCode(string $character): int
2217 if (!\IntlChar::isalpha($character)) {
2220 return self::isLatin($character) ? 1 : 2;
2224 * Checks if the given character is in one of the latin code blocks
2226 * @param string $character
2229 private static function isLatin(string $character): bool
2231 return in_array(\IntlChar::getBlockCode($character), [
2232 \IntlChar::BLOCK_CODE_BASIC_LATIN, \IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT,
2233 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_A, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_B,
2234 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_C, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_D,
2235 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_E, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL
2239 public static function getLanguageMessage(array $item): string
2241 $iso639 = new \Matriphe\ISO639\ISO639;
2243 $used_languages = '';
2244 foreach (json_decode($item['language'], true) as $language => $reliability) {
2245 $code = DI::l10n()->toISO6391($language);
2247 if ($code == 'un') {
2248 $native = $language = DI::l10n()->t('Undetermined');
2250 $native = $iso639->nativeByCode1($code);
2251 $language = $iso639->languageByCode1($code);
2254 if ($native != $language) {
2255 $used_languages .= DI::l10n()->t('%s (%s - %s): %s', $native, $language, $code, number_format($reliability, 5)) . '\n';
2257 $used_languages .= DI::l10n()->t('%s (%s): %s', $native, $code, number_format($reliability, 5)) . '\n';
2260 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2261 return $used_languages;
2265 * Creates an unique guid out of a given uri.
2266 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2267 * Posts that are created on this system are using System::createUUID.
2268 * Received ActivityPub posts are using Processor::getGUIDByURL.
2270 * @param string $uri uri of an item entry
2271 * @param string|null $host hostname for the GUID prefix
2272 * @return string Unique guid
2273 * @throws \Exception
2275 public static function guidFromUri(string $uri, string $host = null): string
2277 // Our regular guid routine is using this kind of prefix as well
2278 // We have to avoid that different routines could accidentally create the same value
2279 $parsed = parse_url($uri);
2281 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2282 unset($parsed['scheme']);
2284 $hostPart = $host ?: $parsed['host'] ?? '';
2286 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed]);
2289 // Glue it together to be able to make a hash from it
2290 if (!empty($parsed)) {
2291 $host_id = implode('/', (array)$parsed);
2296 // Use a mixture of several hashes to provide some GUID like experience
2297 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2301 * generate an unique URI
2303 * @param string $guid An existing GUID (Otherwise it will be generated)
2306 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2308 public static function newURI(string $guid = ''): string
2311 $guid = System::createUUID();
2314 return DI::baseUrl() . '/objects/' . $guid;
2318 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2320 * This can be used to filter for inactive contacts.
2321 * Only do this for public postings to avoid privacy problems, since poco data is public.
2322 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2324 * @param array $arr Contains the just posted item record
2325 * @throws \Exception
2327 private static function updateContact(array $arr)
2329 // Unarchive the author
2330 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2331 if (DBA::isResult($contact)) {
2332 Contact::unmarkForArchival($contact);
2335 // Unarchive the contact if it's not our own contact
2336 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2337 if (DBA::isResult($contact)) {
2338 Contact::unmarkForArchival($contact);
2341 /// @todo On private posts we could obfuscate the date
2342 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2344 // Is it a group? Then we don't care about the rules from above
2345 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2346 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2352 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2353 // So we have to ensure to only update the last item when it had been our own post,
2354 // or it had been done by a "regular" contact.
2355 if (!empty($arr['wall'])) {
2356 $condition = ['id' => $arr['contact-id']];
2358 $condition = ['id' => $arr['contact-id'], 'self' => false];
2360 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2362 // Now do the same for the system wide contacts with uid=0
2363 if ($arr['private'] != self::PRIVATE) {
2365 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2366 ['id' => $arr['owner-id']]
2369 if ($arr['owner-id'] != $arr['author-id']) {
2371 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2372 ['id' => $arr['author-id']]
2378 public static function setHashtags(string $body): string
2380 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2381 $tags = BBCode::getTags($body);
2384 if (!count($tags)) {
2388 // This sorting is important when there are hashtags that are part of other hashtags
2389 // Otherwise there could be problems with hashtags like #test and #test2
2390 // Because of this we are sorting from the longest to the shortest tag.
2391 usort($tags, function ($a, $b) {
2392 return strlen($b) <=> strlen($a);
2395 $URLSearchString = "^\[\]";
2397 // All hashtags should point to the home server if "local_tags" is activated
2398 if (DI::config()->get('system', 'local_tags')) {
2399 $body = preg_replace(
2400 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2401 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2406 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2407 $body = preg_replace_callback(
2408 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2410 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2415 $body = preg_replace_callback(
2416 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2418 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2423 $body = preg_replace_callback(
2424 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2426 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2431 // Repair recursive urls
2432 $body = preg_replace(
2433 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2438 foreach ($tags as $tag) {
2439 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2443 $basetag = str_replace('_', ' ', substr($tag, 1));
2444 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2446 $body = str_replace($tag, $newtag, $body);
2449 // Convert back the masked hashtags
2450 $body = str_replace("#", "#", $body);
2459 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2462 * @param int $item_id
2463 * @return boolean true if item was deleted, else false
2464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2465 * @throws \ImagickException
2467 private static function tagDeliver(int $uid, int $item_id): bool
2469 $owner = User::getOwnerDataById($uid);
2470 if (!DBA::isResult($owner)) {
2471 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2475 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2476 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2480 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2481 if (!DBA::isResult($item)) {
2482 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2486 if ($item['gravity'] == self::GRAVITY_PARENT) {
2487 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2488 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2490 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2491 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2495 $arr = ['item' => $item, 'user' => $owner];
2497 Hook::callAll('tagged', $arr);
2499 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2500 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2502 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2507 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2509 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2511 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2514 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2516 self::performActivity($item['id'], 'announce', $uid);
2519 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2524 * Automatically reshare the item if the "remote_self" option is selected
2526 * @param array $item
2529 private static function autoReshare(array $item)
2531 if ($item['gravity'] != self::GRAVITY_PARENT) {
2535 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2536 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2540 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => LocalRelationship::MIRROR_NATIVE_RESHARE])) {
2544 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2548 if (User::getById($item['uid'], ['blocked'])['blocked'] ?? false) {
2552 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2554 self::performActivity($item['id'], 'announce', $item['uid']);
2557 public static function isRemoteSelf(array $contact, array &$datarray): bool
2559 if ($contact['remote_self'] != LocalRelationship::MIRROR_OWN_POST) {
2563 // Prevent the forwarding of posts that are forwarded
2564 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2565 Logger::info('Already forwarded');
2569 // Prevent to forward already forwarded posts
2570 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2571 Logger::info('Already forwarded (second test)');
2575 // Only forward posts
2576 if ($datarray['verb'] != Activity::POST) {
2577 Logger::info('No post');
2581 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2582 Logger::info('Not public');
2586 if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) {
2587 Logger::info('User is blocked', ['contact' => $contact]);
2591 $datarray2 = $datarray;
2592 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2594 $self = DBA::selectFirst(
2596 ['id', 'name', 'url', 'thumb'],
2597 ['uid' => $contact['uid'], 'self' => true]
2599 if (!DBA::isResult($self)) {
2600 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2604 $datarray['contact-id'] = $self['id'];
2606 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2607 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2608 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2610 unset($datarray['edited']);
2612 unset($datarray['network']);
2613 unset($datarray['owner-id']);
2614 unset($datarray['author-id']);
2616 if ($contact['network'] != Protocol::FEED) {
2617 $old_uri_id = $datarray['uri-id'] ?? 0;
2618 $datarray['guid'] = System::createUUID();
2619 unset($datarray['plink']);
2620 $datarray['uri'] = self::newURI($datarray['guid']);
2621 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2622 $datarray['extid'] = Protocol::DFRN;
2623 $urlpart = parse_url($datarray2['author-link']);
2624 $datarray['app'] = $urlpart['host'];
2625 if (!empty($old_uri_id)) {
2626 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2629 unset($datarray['parent-uri']);
2630 unset($datarray['thr-parent']);
2632 // Store the original post
2633 $result = self::insert($datarray2);
2634 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2636 $datarray['app'] = 'Feed';
2641 unset($datarray['private']);
2644 return (bool)$result;
2651 * @param array $item
2654 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2655 * @throws \ImagickException
2657 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2659 if (DI::config()->get('system', 'disable_embedded')) {
2663 Logger::info('check for photos');
2664 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2669 $img_start = strpos($orig_body, '[img');
2670 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2671 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2673 while (($img_st_close !== false) && ($img_len !== false)) {
2674 $img_st_close++; // make it point to AFTER the closing bracket
2675 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2677 Logger::info('found photo', ['image' => $image]);
2679 if (stristr($image, $site . '/photo/')) {
2680 // Only embed locally hosted photos
2682 $i = basename($image);
2683 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2684 $x = strpos($i, '-');
2687 $res = substr($i, $x + 1);
2688 $i = substr($i, 0, $x);
2689 $photo = Photo::getPhotoForUser($uid, $i, $res);
2690 if (DBA::isResult($photo)) {
2692 * Check to see if we should replace this photo link with an embedded image
2693 * 1. No need to do so if the photo is public
2694 * 2. If there's a contact-id provided, see if they're in the access list
2695 * for the photo. If so, embed it.
2696 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2697 * permissions, regardless of order but first check to see if they're an exact
2698 * match to save some processing overhead.
2700 if (self::hasPermissions($photo)) {
2702 $recips = self::enumeratePermissions($photo);
2703 if (in_array($cid, $recips)) {
2707 if (self::samePermissions($uid, $item, $photo)) {
2713 $photo_img = Photo::getImageForPhoto($photo);
2714 // If a custom width and height were specified, apply before embedding
2715 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2716 Logger::info('scaling photo');
2718 $width = intval($match[1]);
2719 $height = intval($match[2]);
2721 $photo_img->scaleDown(max($width, $height));
2724 $data = $photo_img->asString();
2725 $type = $photo_img->getType();
2727 Logger::info('replacing photo');
2728 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2729 Logger::debug('replaced', ['image' => $image]);
2735 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2736 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2737 if ($orig_body === false) {
2741 $img_start = strpos($orig_body, '[img');
2742 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2743 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2746 $new_body = $new_body . $orig_body;
2751 private static function hasPermissions(array $obj)
2753 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2754 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2757 // @TODO $uid is unused parameter
2758 private static function samePermissions($uid, array $obj1, array $obj2): bool
2760 // first part is easy. Check that these are exactly the same.
2761 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2762 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2763 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2764 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2769 // This is harder. Parse all the permissions and compare the resulting set.
2770 $recipients1 = self::enumeratePermissions($obj1);
2771 $recipients2 = self::enumeratePermissions($obj2);
2775 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2776 return ($recipients1 == $recipients2);
2780 * Returns an array of contact-ids that are allowed to see this object
2782 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2783 * @param bool $check_dead Prunes unavailable contacts from the result
2784 * @param bool $expand_followers Expand the list of followers
2786 * @throws \Exception
2788 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2790 $aclFormatter = DI::aclFormatter();
2792 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2793 $expand_followers = true;
2796 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2797 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2798 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2799 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2800 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2801 $deny = array_unique(array_merge($deny_people, $deny_circles));
2802 $recipients = array_diff($recipients, $deny);
2806 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2808 if (!$uid || ($days < 1)) {
2813 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2814 $uid, self::GRAVITY_PARENT
2818 * $expire_network_only = save your own wall posts
2819 * and just expire conversations started by others
2821 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2823 if ($expire_network_only) {
2824 $condition[0] .= " AND NOT `wall`";
2827 if ($network != "") {
2828 $condition[0] .= " AND `network` = ?";
2829 $condition[] = $network;
2832 $condition[0] .= " AND `received` < ?";
2833 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2835 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2837 if (!DBA::isResult($items)) {
2841 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2843 // Forcing expiring of items - but not notes and marked items
2845 $expire_items = true;
2848 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2849 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2850 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2854 $priority = DI::config()->get('system', 'expire-notify-priority');
2856 while ($item = Post::fetch($items)) {
2857 // don't expire filed items
2858 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2862 // Only expire posts, not photos and photo comments
2864 if (!$expire_photos && !empty($item['resource-id'])) {
2866 } elseif (!$expire_starred && intval($item['starred'])) {
2868 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2870 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2874 self::markForDeletionById($item['id'], $priority);
2879 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]);
2882 public static function firstPostDate(int $uid, bool $wall = false)
2884 $user = User::getById($uid, ['register_date']);
2890 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2891 $uid, $wall, $user['register_date']
2893 $params = ['order' => ['received' => false]];
2894 $thread = Post::selectFirstThread(['received'], $condition, $params);
2895 if (DBA::isResult($thread)) {
2896 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2903 * add/remove activity to an item
2905 * Toggle activities as like,dislike,attend of an item
2907 * @param int $item_id
2908 * @param string $verb
2909 * Activity verb. One of
2910 * like, unlike, dislike, undislike, attendyes, unattendyes,
2911 * attendno, unattendno, attendmaybe, unattendmaybe,
2912 * announce, unannounce
2914 * @param string $allow_cid
2915 * @param string $allow_gid
2916 * @param string $deny_cid
2917 * @param string $deny_gid
2919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2920 * @throws \ImagickException
2921 * @hook 'post_local_end'
2923 * 'post_id' => ID of posted item
2925 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
2931 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2933 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2934 if (!DBA::isResult($item)) {
2935 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2939 $uri_id = $item['uri-id'];
2941 if (!in_array($item['uid'], [0, $uid])) {
2945 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2946 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2947 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2948 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2949 if (!DBA::isResult($item)) {
2950 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2956 // Retrieves the local post owner
2957 $owner = User::getOwnerDataById($uid);
2958 if (empty($owner)) {
2959 Logger::info('Empty owner for user', ['uid' => $uid]);
2963 // Retrieve the current logged in user's public contact
2964 $author_id = Contact::getPublicIdByUserId($uid);
2965 if (empty($author_id)) {
2966 Logger::info('Empty public contact');
2974 $activity = Activity::LIKE;
2978 $activity = Activity::DISLIKE;
2982 $activity = Activity::ATTEND;
2986 $activity = Activity::ATTENDNO;
2989 case 'unattendmaybe':
2990 $activity = Activity::ATTENDMAYBE;
2994 $activity = Activity::FOLLOW;
2998 $activity = Activity::ANNOUNCE;
3001 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3005 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3007 // Enable activity toggling instead of on/off
3008 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3010 // Look for an existing verb row
3011 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3012 if ($event_verb_flag) {
3013 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3015 // Translate to the index based activity index
3017 foreach ($verbs as $verb) {
3018 $vids[] = Verb::getID($verb);
3021 $vids = Verb::getID($activity);
3025 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
3026 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
3028 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
3030 if (DBA::isResult($like_item)) {
3032 * Truth table for existing activities
3034 * | Inputs || Outputs |
3035 * |----------------------------||-------------------|
3036 * | Mode | Event | Same verb || Delete? | Return? |
3037 * |--------|-------|-----------||---------|---------|
3038 * | create | Yes | Yes || No | Yes |
3039 * | create | Yes | No || Yes | No |
3040 * | create | No | Yes || No | Yes |
3041 * | create | No | No || N/A†|
3042 * | delete | Yes | Yes || Yes | N/A‡ |
3043 * | delete | Yes | No || No | N/A‡ |
3044 * | delete | No | Yes || Yes | N/A‡ |
3045 * | delete | No | No || N/A†|
3046 * |--------|-------|-----------||---------|---------|
3047 * | A | B | C || A xor C | !B or C |
3049 * †Can't happen: It's impossible to find an existing non-event activity without
3050 * the same verb because we are only looking for this single verb.
3052 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
3054 if ($mode == 'create' xor $like_item['verb'] == $activity) {
3055 self::markForDeletionById($like_item['id']);
3058 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3063 // No need to go further if we aren't creating anything
3064 if ($mode == 'delete') {
3068 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3071 'guid' => System::createUUID(),
3072 'uri' => self::newURI(),
3074 'contact-id' => $owner['id'],
3075 'wall' => $item['wall'],
3077 'network' => Protocol::DFRN,
3078 'protocol' => Conversation::PARCEL_DIRECT,
3079 'direction' => Conversation::PUSH,
3080 'gravity' => self::GRAVITY_ACTIVITY,
3081 'parent' => $item['id'],
3082 'thr-parent' => $item['uri'],
3083 'owner-id' => $author_id,
3084 'author-id' => $author_id,
3085 'body' => $activity,
3086 'verb' => $activity,
3087 'object-type' => $objtype,
3088 'allow_cid' => $allow_cid ?? $item['allow_cid'],
3089 'allow_gid' => $allow_gid ?? $item['allow_gid'],
3090 'deny_cid' => $deny_cid ?? $item['deny_cid'],
3091 'deny_gid' => $deny_gid ?? $item['deny_gid'],
3096 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
3097 $signed = Diaspora::createLikeSignature($uid, $new_item);
3098 if (!empty($signed)) {
3099 $new_item['diaspora_signed_text'] = json_encode($signed);
3103 self::insert($new_item, true);
3105 // If the parent item isn't visible then set it to visible
3106 // @todo Check if this is still needed
3107 if (!$item['visible']) {
3108 self::update(['visible' => true], ['id' => $item['id']]);
3114 * Fetch the SQL condition for the given user id
3116 * @param integer $owner_id User ID for which the permissions should be fetched
3117 * @return array condition
3119 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
3121 $local_user = DI::userSession()->getLocalUserId();
3122 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
3124 // default permissions - anonymous user
3125 $condition = ["`private` != ?", self::PRIVATE];
3127 if ($local_user && ($local_user == $owner_id)) {
3128 // Profile owner - everything is visible
3130 } elseif ($remote_user) {
3131 // Authenticated visitor - fetch the matching permissionsets
3132 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3135 "(`private` != ? OR (`private` = ? AND `wall`
3136 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
3137 self::PRIVATE, self::PRIVATE
3139 $condition = array_merge($condition, $permissionSets->column('id'));
3147 * Get a permission SQL string for the given user
3149 * @param int $owner_id
3150 * @param string $table
3153 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
3155 $local_user = DI::userSession()->getLocalUserId();
3156 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
3158 if (!empty($table)) {
3159 $table = DBA::quoteIdentifier($table) . '.';
3163 * Construct permissions
3165 * default permissions - anonymous user
3167 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
3169 // Profile owner - everything is visible
3170 if ($local_user && ($local_user == $owner_id)) {
3172 } elseif ($remote_user) {
3174 * Authenticated visitor. Unless pre-verified,
3175 * check that the contact belongs to this $owner_id
3176 * and load the circles the visitor belongs to.
3177 * If pre-verified, the caller is expected to have already
3178 * done this and passed the circles into this function.
3180 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3183 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
3188 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
3195 * get translated item type
3197 * @param array $item
3198 * @param \Friendica\Core\L10n $l10n
3201 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
3203 if (!empty($item['event-id'])) {
3204 return $l10n->t('event');
3205 } elseif (!empty($item['resource-id'])) {
3206 return $l10n->t('photo');
3207 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
3208 return $l10n->t('activity');
3209 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
3210 return $l10n->t('comment');
3213 return $l10n->t('post');
3217 * Sets the "rendered-html" field of the provided item
3219 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3221 * @param array $item
3223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3224 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3226 private static function putInCache(&$item)
3228 // Save original body to prevent addons to modify it
3229 $body = $item['body'];
3231 $rendered_hash = $item['rendered-hash'] ?? '';
3232 $rendered_html = $item['rendered-html'] ?? '';
3235 $rendered_hash == ''
3236 || $rendered_html == ''
3237 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3238 || DI::config()->get('system', 'ignore_cache')
3240 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3241 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3243 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3244 Hook::callAll('put_item_in_cache', $hook_data);
3245 $item['rendered-html'] = $hook_data['rendered-html'];
3246 $item['rendered-hash'] = $hook_data['rendered-hash'];
3249 // Update if the generated values differ from the existing ones
3250 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3253 'rendered-html' => $item['rendered-html'],
3254 'rendered-hash' => $item['rendered-hash']
3256 ['id' => $item['id']]
3261 $item['body'] = $body;
3265 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3266 * If attach is true, also add icons for item attachments.
3268 * @param array $item Record from item table
3269 * @param boolean $attach If true, add icons for item attachments as well
3270 * @param boolean $is_preview Whether this is a preview
3271 * @param boolean $only_cache Whether only cached HTML should be updated
3272 * @return string item body html
3273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3274 * @throws \ImagickException
3275 * @hook prepare_body_init item array before any work
3276 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3277 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3278 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3280 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3283 Hook::callAll('prepare_body_init', $item);
3286 // In order to provide theme developers more possibilities, event items
3287 // are treated differently.
3288 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3289 $ev = Event::getItemHTML($item);
3293 $tags = Tag::populateFromItem($item);
3295 $item['tags'] = $tags['tags'];
3296 $item['hashtags'] = $tags['hashtags'];
3297 $item['mentions'] = $tags['mentions'];
3300 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3301 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3302 $item['body'] = Post\Media::replaceImage($item['body']);
3305 $body = $item['body'];
3307 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3310 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3314 $quote_shared_links = [];
3316 $shared = DI::contentItem()->getSharedPost($item, $fields);
3317 if (!empty($shared['post'])) {
3318 $shared_item = $shared['post'];
3319 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3320 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3321 $quote_uri_id = $shared['post']['uri-id'];
3322 $shared_links[] = strtolower($shared['post']['uri']);
3323 $item['body'] = BBCode::removeSharedData($item['body']);
3324 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3325 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3326 if (!empty($media) && ($media[0]['media-uri-id'] != $item['uri-id'])) {
3327 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3328 if (empty($shared_item['uri-id'])) {
3329 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3330 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3331 $shared_links[] = strtolower($media[0]['url']);
3334 if (empty($shared_item['uri-id'])) {
3335 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3336 $shared_links[] = strtolower($media[0]['url']);
3339 if (!empty($shared_item['uri-id'])) {
3340 $data = BBCode::getAttachmentData($shared_item['body']);
3341 if (!empty($data['url'])) {
3342 $quote_shared_links[] = $data['url'];
3345 $quote_uri_id = $shared_item['uri-id'];
3350 if (!empty($quote_uri_id)) {
3351 if (isset($shared_item['plink'])) {
3352 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item, false, true);
3354 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3358 if (!empty($shared_item['uri-id'])) {
3359 $shared_uri_id = $shared_item['uri-id'];
3360 $shared_links[] = strtolower($shared_item['plink']);
3361 $sharedSplitAttachments = DI::postMediaRepository()->splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3362 $shared_links = array_merge($shared_links, $sharedSplitAttachments['visual']->column('url'));
3363 $shared_links = array_merge($shared_links, $sharedSplitAttachments['link']->column('url'));
3364 $shared_links = array_merge($shared_links, $sharedSplitAttachments['additional']->column('url'));
3365 $item['body'] = self::replaceVisualAttachments($sharedSplitAttachments['visual'], $item['body']);
3368 $itemSplitAttachments = DI::postMediaRepository()->splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3369 $item['body'] = self::replaceVisualAttachments($itemSplitAttachments['visual'], $item['body'] ?? '');
3371 self::putInCache($item);
3372 $item['body'] = $body;
3373 $s = $item["rendered-html"];
3379 // Compile eventual content filter reasons
3380 $filter_reasons = [];
3381 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3382 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3383 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3384 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3385 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3386 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3387 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3390 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3391 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3394 $item['attachments'] = $itemSplitAttachments;
3398 'filter_reasons' => $filter_reasons
3400 Hook::callAll('prepare_body_content_filter', $hook_data);
3401 $filter_reasons = $hook_data['filter_reasons'];
3408 'preview' => $is_preview,
3409 'filter_reasons' => $filter_reasons
3411 Hook::callAll('prepare_body', $hook_data);
3412 $s = $hook_data['html'];
3417 // Replace the blockquotes with quotes that are used in mails.
3418 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3419 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3423 if (!empty($sharedSplitAttachments)) {
3424 $s = self::addGallery($s, $sharedSplitAttachments['visual']);
3425 $s = self::addVisualAttachments($sharedSplitAttachments['visual'], $shared_item, $s, true);
3426 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $sharedSplitAttachments, $body, $s, true, $quote_shared_links);
3427 $s = self::addNonVisualAttachments($sharedSplitAttachments['additional'], $item, $s, true);
3428 $body = BBCode::removeSharedData($body);
3431 $pos = strpos($s, BBCode::SHARED_ANCHOR);
3433 $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR));
3434 $s = substr($s, 0, $pos);
3437 $s = self::addGallery($s, $itemSplitAttachments['visual']);
3438 $s = self::addVisualAttachments($itemSplitAttachments['visual'], $item, $s, false);
3439 $s = self::addLinkAttachment($item['uri-id'], $itemSplitAttachments, $body, $s, false, $shared_links);
3440 $s = self::addNonVisualAttachments($itemSplitAttachments['additional'], $item, $s, false);
3441 $s = self::addQuestions($item, $s);
3444 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3445 $x = Map::byCoordinates(trim($item['coord']));
3447 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3451 // Replace friendica image url size with theme preference.
3452 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3453 $ps = $a->getThemeInfoValue('item_image_size');
3454 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3457 if (!empty($shared_html)) {
3461 $s = HTML::applyContentFilter($s, $filter_reasons);
3463 $hook_data = ['item' => $item, 'html' => $s];
3464 Hook::callAll('prepare_body_final', $hook_data);
3465 return $hook_data['html'];
3469 * Modify links to pictures to links for the "Fancybox" gallery
3472 * @param PostMedias $PostMedias
3475 private static function addGallery(string $s, PostMedias $PostMedias): string
3477 foreach ($PostMedias as $PostMedia) {
3478 if (!$PostMedia->preview || ($PostMedia->type !== Post\Media::IMAGE)) {
3482 if ($PostMedia->hasDimensions()) {
3483 $pattern = '#<a href="' . preg_quote($PostMedia->url) . '">(.*?)"></a>#';
3485 $s = preg_replace_callback($pattern, function () use ($PostMedia) {
3486 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image/single_with_height_allocation.tpl'), [
3487 '$image' => $PostMedia,
3488 '$allocated_height' => $PostMedia->getAllocatedHeight(),
3489 '$allocated_max_width' => ($PostMedia->previewWidth ?? $PostMedia->width) . 'px',
3493 $s = str_replace('<a href="' . $PostMedia->url . '"', '<a data-fancybox="uri-id-' . $PostMedia->uriId . '" href="' . $PostMedia->url . '"', $s);
3501 * Check if the body contains a link
3503 * @param string $body
3504 * @param string $url
3508 public static function containsLink(string $body, string $url, int $type = 0): bool
3510 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3511 $urlparts = parse_url($url);
3512 if (empty($urlparts)) {
3516 unset($urlparts['query']);
3517 unset($urlparts['fragment']);
3520 $url = (string)Uri::fromParts((array)$urlparts);
3521 } catch (\InvalidArgumentException $e) {
3522 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3523 /* See https://github.com/friendica/friendica/issues/12113
3524 * Malformed URLs will result in a Fatal Error
3529 // Remove media links to only search in embedded content
3530 // @todo Check images for image link, audio for audio links, ...
3531 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3532 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3535 if (strpos($body, $url)) {
3539 foreach ([0, 1, 2] as $size) {
3541 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3542 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3552 * Replace visual attachments in the body
3554 * @param PostMedias $PostMedias
3555 * @param string $body
3556 * @return string modified body
3558 private static function replaceVisualAttachments(PostMedias $PostMedias, string $body): string
3560 DI::profiler()->startRecording('rendering');
3562 foreach ($PostMedias as $PostMedia) {
3563 if ($PostMedia->preview) {
3564 if (DI::baseUrl()->isLocalUri($PostMedia->preview)) {
3567 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3568 $search = ['[img=' . $PostMedia->preview . ']', ']' . $PostMedia->preview . '[/img]'];
3569 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3571 $body = str_replace($search, $replace, $body);
3572 } elseif ($PostMedia->mimetype->type == 'image') {
3573 if (DI::baseUrl()->isLocalUri($PostMedia->url)) {
3576 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3577 $search = ['[img=' . $PostMedia->url . ']', ']' . $PostMedia->url . '[/img]'];
3578 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3580 $body = str_replace($search, $replace, $body);
3583 DI::profiler()->stopRecording();
3588 * Add visual attachments to the content
3590 * @param PostMedias $PostMedias
3591 * @param array $item
3592 * @param string $content
3593 * @param bool $shared
3594 * @return string modified content
3595 * @throws ServiceUnavailableException
3597 private static function addVisualAttachments(PostMedias $PostMedias, array $item, string $content, bool $shared): string
3599 DI::profiler()->startRecording('rendering');
3602 $images = new PostMedias();
3604 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3605 foreach ($PostMedias as $PostMedia) {
3606 if (self::containsLink($item['body'], $PostMedia->preview ?? $PostMedia->url, $PostMedia->type)) {
3610 if ($PostMedia->mimetype->type == 'image' || $PostMedia->preview) {
3611 $preview_size = Proxy::SIZE_MEDIUM;
3612 $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($preview_size);
3618 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3622 if ($PostMedia->mimetype->type == 'video') {
3623 /// @todo Move the template to /content as well
3624 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3626 'id' => $PostMedia->id,
3627 'src' => (string)$PostMedia->url,
3628 'name' => $PostMedia->name ?: $PostMedia->url,
3629 'preview' => $preview_url,
3630 'mime' => (string)$PostMedia->mimetype,
3633 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3636 $trailing .= $media;
3638 } elseif ($PostMedia->mimetype->type == 'audio') {
3639 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3641 'id' => $PostMedia->id,
3642 'src' => (string)$PostMedia->url,
3643 'name' => $PostMedia->name ?: $PostMedia->url,
3644 'mime' => (string)$PostMedia->mimetype,
3647 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3650 $trailing .= $media;
3652 } elseif ($PostMedia->mimetype->type == 'image') {
3653 $src_url = DI::baseUrl() . $PostMedia->getPhotoPath();
3654 if (self::containsLink($item['body'], $src_url)) {
3658 $images[] = $PostMedia->withUrl(new Uri($src_url))->withPreview(new Uri($preview_url), $preview_size);
3662 $media = Image::getBodyAttachHtml($images);
3664 // On Diaspora posts the attached pictures are leading
3665 if ($item['network'] == Protocol::DIASPORA) {
3668 $trailing .= $media;
3672 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3673 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3675 if ($leading != '') {
3676 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3679 if ($trailing != '') {
3680 $content .= '<div class="body-attach">' . $trailing . '</div>';
3684 DI::profiler()->stopRecording();
3689 * Add link attachment to the content
3692 * @param PostMedias[] $attachments
3693 * @param string $body
3694 * @param string $content
3695 * @param bool $shared
3696 * @param array $ignore_links A list of URLs to ignore
3697 * @return string modified content
3698 * @throws InternalServerErrorException
3699 * @throws ServiceUnavailableException
3701 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3703 DI::profiler()->startRecording('rendering');
3704 // Don't show a preview when there is a visual attachment (audio or video)
3705 $types = $attachments['visual']->column('type');
3706 $preview = !in_array(PostMedia::TYPE_IMAGE, $types) && !in_array(PostMedia::TYPE_VIDEO, $types);
3708 /** @var ?PostMedia $attachment */
3710 foreach ($attachments['link'] as $PostMedia) {
3712 foreach ($ignore_links as $ignore_link) {
3713 if (Strings::compareLink($PostMedia->url, $ignore_link)) {
3717 // @todo Judge between the links to use the one with most information
3718 if (!$found && (empty($attachment) || $PostMedia->authorName ||
3719 (!$attachment->name && $PostMedia->name) ||
3720 (!$attachment->description && $PostMedia->description) ||
3721 (!$attachment->preview && $PostMedia->preview))) {
3722 $attachment = $PostMedia;
3726 if (!empty($attachment)) {
3729 'author_name' => $attachment->authorName ?? '',
3730 'author_url' => (string)($attachment->authorUrl ?? ''),
3731 'description' => $attachment->description ?? '',
3734 'provider_name' => $attachment->publisherName ?? '',
3735 'provider_url' => (string)($attachment->publisherUrl ?? ''),
3737 'title' => $attachment->name ?? '',
3739 'url' => (string)$attachment->url,
3742 if ($preview && $attachment->preview) {
3743 if ($attachment->previewWidth >= 500) {
3744 $data['image'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3746 $data['preview'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3750 if (!empty($data['description']) && !empty($content)) {
3751 similar_text($data['description'], $content, $percent);
3756 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3757 $data['description'] = '';
3760 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3761 $data['author_name'] = '';
3764 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3765 $data['author_url'] = '';
3767 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3768 $data = BBCode::getAttachmentData($match[1]);
3770 DI::profiler()->stopRecording();
3772 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3773 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3774 $parts = parse_url($data['url']);
3775 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3776 if (empty($data['provider_name'])) {
3777 $data['provider_name'] = $parts['host'];
3779 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3780 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3782 if (!empty($parts['port'])) {
3783 $data['provider_url'] .= ':' . $parts['port'];
3788 // @todo Use a template
3789 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3790 if ($preview_mode != BBCode::PREVIEW_NONE) {
3791 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3795 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3796 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3797 '$url' => $data['url'],
3798 '$title' => $data['title'],
3805 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3807 return $content . $rendered;
3814 * Add non-visual attachments to the content
3816 * @param PostMedias $PostMedias
3817 * @param array $item
3818 * @param string $content
3819 * @return string modified content
3820 * @throws InternalServerErrorException
3821 * @throws \ImagickException
3823 private static function addNonVisualAttachments(PostMedias $PostMedias, array $item, string $content): string
3825 DI::profiler()->startRecording('rendering');
3827 foreach ($PostMedias as $PostMedia) {
3828 if (strpos($item['body'], (string)$PostMedia->url)) {
3834 'id' => $item['author-id'],
3835 'network' => $item['author-network'],
3836 'url' => $item['author-link'],
3837 'alias' => $item['author-alias']
3839 $the_url = Contact::magicLinkByContact($author, $PostMedia->url);
3841 $title = Strings::escapeHtml(trim($PostMedia->description ?? '' ?: $PostMedia->url));
3843 if ($PostMedia->size) {
3844 $title .= ' ' . $PostMedia->size . ' ' . DI::l10n()->t('bytes');
3847 /// @todo Use a template
3848 $icon = '<div class="attachtype icon s22 type-' . $PostMedia->mimetype->type . ' subtype-' . $PostMedia->mimetype->subtype . '"></div>';
3849 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3852 if ($trailing != '') {
3853 $content .= '<div class="body-attach">' . $trailing . '</div>';
3856 DI::profiler()->stopRecording();
3860 private static function addQuestions(array $item, string $content): string
3862 DI::profiler()->startRecording('rendering');
3863 if (!empty($item['question-id'])) {
3865 'id' => $item['question-id'],
3866 'multiple' => $item['question-multiple'],
3867 'voters' => $item['question-voters'],
3868 'endtime' => $item['question-end-time']
3871 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3872 foreach ($options as $key => $option) {
3873 if ($question['voters'] > 0) {
3874 $percent = $option['replies'] / $question['voters'] * 100;
3875 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%3$d%%, %1$d vote)', '%2$s (%3$d%%, %1$d votes)', $option['replies'] ?? 0, $option['name'], round($percent, 1));
3877 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'] ?? 0, $option['name']);
3881 if (!empty($question['voters']) && !empty($question['endtime'])) {
3882 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'] ?? 0, Temporal::getRelativeDate($question['endtime']));
3883 } elseif (!empty($question['voters'])) {
3884 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters'] ?? 0);
3885 } elseif (!empty($question['endtime'])) {
3886 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3891 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3892 '$question' => $question,
3893 '$options' => $options,
3894 '$summary' => $summary,
3897 DI::profiler()->stopRecording();
3902 * get private link for item
3904 * @param array $item
3905 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3906 * @throws \Exception
3908 public static function getPlink(array $item)
3910 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3911 $plink = $item['plink'];
3912 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3913 $plink = $item['uri'];
3916 if (DI::userSession()->getLocalUserId()) {
3918 'href' => "display/" . $item['guid'],
3919 'orig' => "display/" . $item['guid'],
3920 'title' => DI::l10n()->t('View on separate page'),
3921 'orig_title' => DI::l10n()->t('View on separate page'),
3924 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3927 'id' => $item['author-id'],
3928 'network' => $item['author-network'],
3929 'url' => $item['author-link'],
3930 'alias' => $item['author-alias'],
3932 $plink = Contact::magicLinkByContact($author, $plink);
3935 if (!empty($plink)) {
3936 $ret['href'] = DI::baseUrl()->remove($plink);
3937 $ret['title'] = DI::l10n()->t('Link to source');
3939 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3943 'title' => DI::l10n()->t('Link to source'),
3944 'orig_title' => DI::l10n()->t('Link to source'),
3954 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3955 * This does apply to posts that are sent via ! and not in parallel to a group via @
3957 * @param int $uri_id
3959 * @return boolean "true" when it is a group post
3961 public static function isGroupPost(int $uri_id): bool
3963 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3967 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3968 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3969 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3970 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3978 * Search item id for given URI or plink
3980 * @param string $uri
3981 * @param integer $uid
3983 * @return integer item id
3985 public static function searchByLink(string $uri, int $uid = 0): int
3987 $ssl_uri = str_replace('http://', 'https://', $uri);
3988 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3990 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3991 if (DBA::isResult($item)) {
3995 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3996 if (DBA::isResult($item)) {
4004 * Return the URI for a link to the post
4006 * @param string $uri URI or link to post
4008 * @return string URI
4010 public static function getURIByLink(string $uri): string
4012 $ssl_uri = str_replace('http://', 'https://', $uri);
4013 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
4015 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
4016 if (DBA::isResult($item)) {
4017 return $item['uri'];
4020 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
4021 if (DBA::isResult($item)) {
4022 return $item['uri'];
4029 * Fetches item for given URI or plink
4031 * @param string $uri
4033 * @param int $completion
4035 * @return integer item id
4037 public static function fetchByLink(string $uri, int $uid = 0, int $completion = ActivityPub\Receiver::COMPLETION_MANUAL): int
4039 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
4040 $item_id = self::searchByLink($uri, $uid);
4041 if (!empty($item_id)) {
4042 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
4052 Hook::callAll('item_by_link', $hookData);
4054 if (isset($hookData['item_id'])) {
4055 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
4058 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', $completion, $uid);
4061 $item_id = self::searchByLink($fetched_uri, $uid);
4063 $item_id = Diaspora::fetchByURL($uri);
4066 if (!empty($item_id)) {
4067 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
4071 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
4076 * Fetch the uri-id of a quote
4078 * @param string $body
4081 public static function getQuoteUriId(string $body, int $uid = 0): int
4083 $shared = BBCode::fetchShareAttributes($body);
4084 if (empty($shared['guid']) && empty($shared['message_id'])) {
4088 if (empty($shared['link']) && empty($shared['message_id'])) {
4089 Logger::notice('Invalid share block.', ['share' => $shared]);
4093 if (!empty($shared['guid'])) {
4094 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
4095 if (!empty($shared_item['uri-id'])) {
4096 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
4097 return $shared_item['uri-id'];
4101 if (!empty($shared['message_id'])) {
4102 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
4103 if (!empty($shared_item['uri-id'])) {
4104 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
4105 return $shared_item['uri-id'];
4109 if (!empty($shared['link'])) {
4110 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
4111 if (!empty($shared_item['uri-id'])) {
4112 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
4113 return $shared_item['uri-id'];
4117 $url = $shared['message_id'] ?: $shared['link'];
4118 $id = self::fetchByLink($url, 0, ActivityPub\Receiver::COMPLETION_ASYNC);
4120 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
4124 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
4125 if (!empty($shared_item['uri-id'])) {
4126 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
4127 return $shared_item['uri-id'];
4130 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);